macross

来源:https://uqer.io/community/share/55a92cdcf9f06c57a11b53be

  1. #第一次写大家帮看看有问题么
  2. #策略 : 日收盘价高于ma20 买入; 低于ma20 卖出清仓
  3. from matplotlib import pylab
  4. import numpy as np
  5. import pandas as pd
  6. import DataAPI
  7. import seaborn as sns
  8. sns.set_style('white')
  9. ################
  10. start = datetime(2008, 1, 1) # 回测起始时间
  11. end = datetime(2015, 4, 23) # 回测结束时间
  12. benchmark = 'SH50' # 策略参考标准
  13. universe = ['510050.XSHG'] # 股票池
  14. #benchmark = 'HS300'
  15. #universe = ['510300.XSHG']
  16. capital_base = 100000 # 起始资金
  17. commission = Commission(0.0,0.0)
  18. window_short = 20
  19. window_long = 300
  20. longest_history = window_long
  21. #longest_history = window_short
  22. SD = 0.05
  23. def initialize(account): # 初始化虚拟账户状态
  24. account.fund = universe[0]
  25. account.SD = SD
  26. account.window_short = window_short
  27. account.window_long = window_long
  28. def handle_data(account): # 每个交易日的买入卖出指令
  29. hist = account.get_history(longest_history)
  30. fund = account.fund
  31. short_mean = np.mean(hist[fund]['closePrice'][-account.window_short:]) # 计算短均线值
  32. long_mean = np.mean(hist[fund]['closePrice'][-account.window_long:]) #计算长均线值
  33. now_price = hist[fund]['closePrice'][-1:]
  34. #print len(short_mean)
  35. #print type(now_price)
  36. #print(now_price)
  37. #now_price.plot
  38. #all_close_prices = account.get_attribute_history('closePrice', 1)
  39. # 计算买入卖出信号
  40. # flag = True if (short_mean - long_mean) > account.SD * long_mean else False
  41. flag = True if (now_price - short_mean) > account.SD * short_mean else False
  42. if flag:
  43. if account.position.secpos.get(fund, 0) == 0:
  44. # 空仓时全仓买入,买入股数为100的整数倍
  45. approximationAmount = int(account.cash / hist[fund]['closePrice'][-1]/100.0) * 100
  46. order(fund, approximationAmount)
  47. else:
  48. # 卖出时,全仓清空
  49. if account.position.secpos.get(fund, 0) >= 0:
  50. order_to(fund, 0)

macross - 图1