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
| import pandas as pd import talib
# 假设df是包含OHLC数据的DataFrame,索引为日期 # 列名应为:'open', 'high', 'low', 'close' (小写) # 示例数据: # df = pd.DataFrame({ # 'open': [ ... ], # 'high': [ ... ], # 'low': [ ... ], # 'close': [ ... ] # }, index=pd.DatetimeIndex([ ... ]))
# 获取所有以"CDL"开头的形态识别函数名 pattern_functions = [func for func in dir(talib) if func.startswith('CDL')]
# 创建新的DataFrame存储结果 pattern_df = pd.DataFrame(index=df.index)
# 循环应用所有形态识别函数 for pattern_func in pattern_functions: try: # 获取函数对象 func = getattr(talib, pattern_func) # 应用函数识别形态 pattern_result = func(df['开盘价'], df['最高价'], df['最低价'], df['收盘价']) # 将结果保存到新DataFrame pattern_df[pattern_func] = pattern_result except Exception as e: print(f"Error processing {pattern_func}: {str(e)}") pattern_df[pattern_func] = None # 出错时填充None
# 查看结果 print(f"识别了{len(pattern_functions)}种K线形态") print(pattern_df.tail())
# 可选:保存结果到CSV文件 # pattern_df.to_csv('kline_pattern_results.csv')
# 可选:筛选出现特定形态的日期 # 例如筛选早晨之星(CDLMORNINGSTAR) # morning_star_dates = pattern_df[pattern_df['CDLMORNINGSTAR'] > 0].index
|