重写 rsi

来源:https://uqer.io/community/share/560dfd84f9f06c4ca82fb597

  1. import talib as ta
  2. import numpy as np
  3. import pandas as pd
  4. from pandas import DataFrame,Series
  5. start = '2014-01-01' # 回测起始时间
  6. end = '2015-01-01' # 回测结束时间
  7. benchmark = 'HS300' # 策略参考标准
  8. universe = set_universe('HS300') # 证券池,支持股票和基金
  9. capital_base = 10000000 # 起始资金
  10. freq = 'd' # 策略类型,'d'表示日间策略使用日线回测
  11. refresh_rate = 1 # 调仓频率,表示执行handle_data的时间间隔,由于freq = 'd',时间间隔的单位为交易日
  12. pieces=10 #每个标的最多买1/10
  13. def initaialize(account):
  14. pass
  15. def handle_data(account):
  16. prices=account.get_attribute_history('closePrice',100)
  17. for s in universe:
  18. cun_price=price[s][-1]
  19. cun_amount[s]=account.secpos.get(s,0)
  20. RSI=ta.RSI(prices[s],9)
  21. buy_flag=RSI[-1]>RSI[-2] and RSI[-1]>30 #计算买入条件
  22. sell_flag = RSI[-1]<RSI[-2] and RSI[-1]<70 #计算卖出条件
  23. amount_max=int((0.1*capital_base)/cun_price) #计算单支仓位上限
  24. amount = min(int(2500000/cun_price),amount_max-cun-amount[s]) #计算下单量
  25. if buy_flag and (cun_amount[s]<amount_max):
  26. order(s,amount)
  27. elif sell_flag and (cun_amount[s]>0):
  28. order_to(s,0)
  29. ---------------------------------------------------------------------------
  30. ValueError Traceback (most recent call last)
  31. <mercury-input-6-72d5ab71705d> in <module>()
  32. 61 perf = quartz.perf_parse(bt, quartz_acct)
  33. 62 elif QUARTZ_CACHE.get('start', 0) == sim_params.first_trading_day and QUARTZ_CACHE.get('end', 0) == sim_params.last_trading_day and QUARTZ_CACHE.get('benchmark', 0) == benchmark and QUARTZ_CACHE.get('universe', 0) == sim_params.universe:
  34. ---> 63 strategy = quartz.sim_condition.strategy.TradingStrategy(initialize, handle_data)
  35. 64 bt, quartz_acct = quartz.quick_backtest_generator(sim_params = QUARTZ_CACHE['sim_params'],
  36. 65 strategy = strategy,
  37. python2.7/site-packages/quartz/sim_condition/strategy.pyc in __init__(self, initialize, handle_data)
  38. 19 def __init__(self, initialize=None, handle_data=None):
  39. 20 if not hasattr(initialize, '__call__'):
  40. ---> 21 raise ValueError('initialize must be a function!')
  41. 22 else:
  42. 23 self._initialize = initialize
  43. ValueError: initialize must be a function!