1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55
| import pandas as pd import plotly.graph_objects as go
# 计算移动平均线 (关键步骤)[1,3](@ref) df['MA5'] = df['收盘'].rolling(window=5).mean() # 5日均线 df['MA20'] = df['收盘'].rolling(window=20).mean() # 20日均线 df['MA30'] = df['收盘'].rolling(window=30).mean() # 30日均线
# 创建Candlestick图 fig = go.Figure(data=[go.Candlestick( x=df.index, open=df['开盘'], high=df['最高'], low=df['最低'], close=df['收盘'], name='K线' )])
# 添加均线轨迹 (核心功能)[1,3](@ref) fig.add_trace(go.Scatter( x=df.index, y=df['MA5'], mode='lines', name='5日均线', line=dict(color='royalblue', width=2) ))
fig.add_trace(go.Scatter( x=df.index, y=df['MA20'], mode='lines', name='20日均线', line=dict(color='orange', width=2) ))
fig.add_trace(go.Scatter( x=df.index, y=df['MA30'], mode='lines', name='30日均线', line=dict(color='green', width=2) ))
# 设置布局 fig.update_layout( title="股票K线图 (含均线系统)", xaxis_title="日期", yaxis_title="价格", legend_title="图例说明", xaxis_rangeslider_visible=False, hovermode="x unified" # 鼠标悬停时显示所有数据[5](@ref) )
# 显示图形 fig.show()
|