kline_processor.py 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. import pandas as pd
  2. class KlineProcessor:
  3. def __init__(self, df):
  4. """
  5. 初始化,处理历史数据中的包含关系
  6. :param df: 历史K线数据,包含 'High' 和 'Low' 列
  7. """
  8. self.df = self.process_inclusion_globally(df)
  9. def process_inclusion_globally(self, df):
  10. """
  11. 全局处理包含关系,结合更早的 K 线进行方向判断
  12. :param df: 包含 'High' 和 'Low' 列的 DataFrame
  13. :return: 处理完成的无包含关系的 DataFrame
  14. """
  15. i = 1
  16. while i < len(df):
  17. # 检查 i 和 i-1 是否有包含关系
  18. if (df.loc[i, 'High'] <= df.loc[i-1, 'High'] and df.loc[i, 'Low'] >= df.loc[i-1, 'Low']) or \
  19. (df.loc[i, 'High'] >= df.loc[i-1, 'High'] and df.loc[i, 'Low'] <= df.loc[i-1, 'Low']):
  20. # 如果有包含关系,判断方向并合并
  21. if i - 2 >= 0: # 检查是否存在 i-2
  22. # 如果 i-2 存在,基于 i-2 和 i-1 的关系判断方向
  23. if df.loc[i-1, 'High'] <= df.loc[i-2, 'High']:
  24. # 当前为 LL 合并
  25. df.loc[i-1, 'High'] = min(df.loc[i, 'High'], df.loc[i-1, 'High'])
  26. df.loc[i-1, 'Low'] = min(df.loc[i, 'Low'], df.loc[i-1, 'Low'])
  27. else:
  28. # 当前为 HH 合并
  29. df.loc[i-1, 'High'] = max(df.loc[i, 'High'], df.loc[i-1, 'High'])
  30. df.loc[i-1, 'Low'] = max(df.loc[i, 'Low'], df.loc[i-1, 'Low'])
  31. else:
  32. # 如果 i-2 不存在,仅根据 i 和 i-1 判断方向
  33. if df.loc[i, 'High'] <= df.loc[i-1, 'High']:
  34. # 当前为 LL 合并
  35. df.loc[i-1, 'High'] = min(df.loc[i, 'High'], df.loc[i-1, 'High'])
  36. df.loc[i-1, 'Low'] = min(df.loc[i, 'Low'], df.loc[i-1, 'Low'])
  37. else:
  38. # 当前为 HH 合并
  39. df.loc[i-1, 'High'] = max(df.loc[i, 'High'], df.loc[i-1, 'High'])
  40. df.loc[i-1, 'Low'] = max(df.loc[i, 'Low'], df.loc[i-1, 'Low'])
  41. # 删除当前 K 线
  42. df = df.drop(index=i).reset_index(drop=True)
  43. # 回溯到前一根,重新检查合并后的关系
  44. i = max(i - 1, 1)
  45. else:
  46. # 如果没有包含关系,检查下一根 K 线
  47. i += 1
  48. print(df.head())
  49. return df