在量化交易和金融分析中K线图是观察股价走势的“眼睛”。而叠加移动平均线(MA),更能揭示趋势方向。今天,我们就用Python轻松实现这一经典组合。
1. 数据获取与预处理,使用akshare获取数据
def get_stock_data(symbol="600519", start_date="20230101", end_date="20231231"):"""获取股票历史行情数据"""# 使用 AKShare 获取 A 股历史行情 (前复权)df = ak.stock_zh_a_hist(symbol=symbol, period="daily", start_date=start_date, end_date=end_date, adjust="qfq")# 数据清洗:重命名列以符合通用习惯,并转换日期格式df.rename(columns={"日期": "Date", "开盘": "Open", "收盘": "Close","最高": "High", "最低": "Low", "成交量": "Volume"}, inplace=True)df["Date"] = pd.to_datetime(df["Date"])df.set_index("Date", inplace=True)# AKShare 的成交量单位通常是"手",为了图表美观,这里转换为"股"(可选)# df["Volume"] = df["Volume"] * 100return df
2. 计算移动平均线 (MA)
def add_moving_averages(df):"""计算并添加 MA5, MA20, MA60"""df['MA5'] = df['Close'].rolling(window=5).mean()df['MA20'] = df['Close'].rolling(window=20).mean()df['MA60'] = df['Close'].rolling(window=60).mean()return df
3. Plotly 可视化绘图
def plot_kline_with_ma(df, title="贵州茅台 K线图 + MA"):# 创建子图:2行1列,K线在上方,成交量在下方# row_heights: 第一行占70%,第二行占30%fig = go.Figure()# --- A. 添加 K线图 (Candlestick) ---fig.add_trace(go.Candlestick(x=df.index,open=df['Open'],high=df['High'],low=df['Low'],close=df['Close'],name='K线',increasing_line_color='#EF5350', # 上涨颜色 (红)decreasing_line_color='#26A69A', # 下跌颜色 (绿)increasing_fillcolor='#EF5350',decreasing_fillcolor='#26A69A',yaxis="y1"))
添加 MA 曲线
fig.add_trace(go.Scatter(x=df.index, y=df['MA5'], line=dict(color='white', width=1), name='MA5'))# MA20 - 黄色线fig.add_trace(go.Scatter(x=df.index, y=df['MA20'], line=dict(color='yellow', width=1.5), name='MA20'))# MA60 - 紫色线 (生命线)fig.add_trace(go.Scatter(x=df.index, y=df['MA60'], line=dict(color='purple', width=2), name='MA60'))
添加成交量 (Bar) ---
颜色逻辑:如果收盘价 > 开盘价,成交量柱为红色,否则为绿色
colors = ['#EF5350' if close >= open_ else '#26A69A' for close, open_ in zip(df['Close'], df['Open'])]fig.add_trace(go.Bar(x=df.index,y=df['Volume'],name='成交量',marker_color=colors,yaxis="y2"))
布局设置
fig.update_layout(title=title,xaxis_rangeslider_visible=False, # 隐藏底部的范围滑块xaxis=dict(title="日期"),yaxis=dict(title="价格 (CNY)", side="right"), # 主坐标轴在右侧yaxis2=dict(title="成交量", side="right", overlaying="y", anchor="x", showgrid=False), # 次坐标轴legend=dict(orientation="h", y=1.05, x=0), # 图例横向排列在顶部template="plotly_dark", # 使用深色主题height=800)fig.show()
最终成果图

附完整代码,复制就能用!需要我打包发GitHub吗?#Python可视化 #量化