基于Random Forest的决策策略

来源:https://uqer.io/community/share/54a10ef8f9f06c4bb886324b

版本:1.0

作者:李丞

联系:cheng.li@datayes.com

利用随机树分类算法,通过历史价格的上升状态变化规律,预测下一日股价变动的方向。预测上涨则买入,下跌则卖出(如果可以的话);

  1. from sklearn.ensemble import RandomForestClassifier
  2. from collections import deque
  3. import pandas as pd
  4. import numpy as np
  5. start = pd.datetime(2010, 4, 1)
  6. end = pd.datetime(2014, 9, 16)
  7. longest_history = 1
  8. bm = 'HS300'
  9. universe = ['600000.XSHG']
  10. csvs = []
  11. capital_base = 1e5
  12. refresh_rate = 1
  13. window_length = 10
  14. def initialize(account):
  15. account.security = universe[0]
  16. account.window_length = window_length
  17. account.classifier = RandomForestClassifier()
  18. # 先进先出的deque序列,设定了最长的长度,在序列超过最长长度的时候,会将头部序列移出
  19. account.recent_prices = deque(maxlen=account.window_length+2) # 保存最近的股价
  20. account.X = deque(maxlen=100) # 自变量
  21. account.Y = deque(maxlen=100) # 应变量
  22. account.prediction = 0 # 保存最近的预测值
  23. def handle_data(account):
  24. hist = account.get_history(1)
  25. if account.security in hist:
  26. account.recent_prices.append(hist[account.security]['closePrice'][0]) # 更新最近的股价
  27. if len(account.recent_prices) >= account.window_length+2: # 如果我们已经获取了足够的股价
  28. RecentPrice=list(account.recent_prices) # 将deque转换为对应的list
  29. # 制作一组1和0,标记股价是否相对于上一日价格上升。
  30. changes = np.diff(RecentPrice) > 0
  31. account.X.append(RecentPrice[1:-1])
  32. account.Y.append(changes[-1])
  33. if len(account.Y) >= 100: # 已经拥有足够的数据im
  34. account.classifier.fit(account.X, account.Y) # 设定模型
  35. account.prediction = account.classifier.predict(changes[1:]) # 预测
  36. # 如果过大0.5,买入;小于0.5,卖出
  37. if account.prediction > 0.5:
  38. buyAmount = int(account.position.cash / hist[account.security]['closePrice'][0])
  39. order(account.security, buyAmount)
  40. else:
  41. order_to(account.security, 0)

基于Random Forest的决策策略 - 图1