validate_fractals.py 996 B

123456789101112131415161718192021222324
  1. def identify_fractals(df):
  2. """
  3. 根据基本定义识别初步的顶底分型。
  4. 不进行有效性判定(如间隔、极值强化、交替性等)。
  5. 分型定义(3K线窗口):
  6. - 顶分型(Top): 中间K线的High大于相邻两K线的High
  7. - 底分型(Bottom): 中间K线的Low小于相邻两K线的Low
  8. :param df: 已经去除包含关系的K线DataFrame,要求有 'High'、'Low' 列
  9. :return: 分型列表 [(index, 'Top'), (index, 'Bottom')],按时间顺序列出
  10. """
  11. fractals = []
  12. # 遍历从第1根K线到倒数第2根K线(i-1、i、i+1可用)
  13. for i in range(1, len(df) - 1):
  14. # 顶分型判断
  15. if df.loc[i, 'High'] > df.loc[i - 1, 'High'] and df.loc[i, 'High'] > df.loc[i + 1, 'High']:
  16. fractals.append((i, 'Top'))
  17. # 底分型判断
  18. elif df.loc[i, 'Low'] < df.loc[i - 1, 'Low'] and df.loc[i, 'Low'] < df.loc[i + 1, 'Low']:
  19. fractals.append((i, 'Bottom'))
  20. return fractals