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 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94
| import pandas as pd import talib import plotly.graph_objects as go import numpy as np
# 假设df是包含期货OHLC数据的DataFrame,索引为日期 # 示例数据结构: # df = pd.DataFrame({ # 'open': [...], 'high': [...], 'low': [...], 'close': [...] # }, index=pd.date_range('2024-01-01', periods=100))
# 1. 使用TA-Lib识别早晨之星形态 morning_star_signals = talib.CDLMORNINGSTAR( df['开盘价'], df['最高价'], df['最低价'], df['收盘价'] )
# 2. 创建包含信号的DataFrame signals_df = pd.DataFrame({ 'open': df['开盘价'], 'high': df['最高价'], 'low': df['最低价'], 'close': df['收盘价'], 'morning_star': morning_star_signals })
# 3. 筛选出早晨之星信号(值>0表示形态出现) morning_star_dates = signals_df[signals_df['morning_star'] > 0].index
# 4. 创建Plotly K线图 fig = go.Figure()
# 添加K线图 fig.add_trace(go.Candlestick( x=signals_df.index, open=signals_df['open'], high=signals_df['high'], low=signals_df['low'], close=signals_df['close'], increasing_line_color='red', # 根据中国习惯设置涨跌颜色 decreasing_line_color='green', name='K线' ))
# 5. 标注早晨之星形态 for date in morning_star_dates: # 在信号日添加向上箭头标记 fig.add_annotation( x=date, y=signals_df.loc[date, 'low'] * 0.98, # 在最低价下方显示标记 text="早晨之星", showarrow=True, arrowhead=3, arrowsize=1.5, arrowcolor="gold", font=dict(size=12, color="gold"), ax=0, ay=30 # 箭头向上 )
# 6. 设置图表布局 fig.update_layout( title='期货K线图 - 早晨之星形态识别', xaxis_title='日期', yaxis_title='价格', xaxis_rangeslider_visible=False, # 隐藏底部滑动条 template="plotly_dark", height=600, showlegend=False )
# 7. 添加技术分析常用辅助线 fig.update_layout( shapes=[ # 水平支撑/阻力线示例 dict( type="line", x0=signals_df.index[0], x1=signals_df.index[-1], y0=signals_df['close'].min(), y1=signals_df['close'].min(), line=dict(color="RoyalBlue", width=1, dash="dot") ) ] )
# 显示图表 fig.show()
# 8. 输出信号详情 if not morning_star_dates.empty: print("\n检测到的早晨之星形态日期:") print(morning_star_dates.strftime("%Y-%m-%d").values) else: print("在指定时间范围内未检测到早晨之星形态")
|