用5日均线和10日均线进行判断 —- 改进版

来源:https://uqer.io/community/share/561e3a65f9f06c4ca82fb5ec

1、 修改Adobe同学的代码

  1. data=DataAPI.MktEqudGet(ticker="600030",beginDate="20131001") #选取600030股票
  2. a = data.closePrice
  3. B = []
  4. n = len(a)
  5. for i in range(10, n):
  6. x5 = a[i-5:i].mean() #5日均线值
  7. x10 = a[i-10:i].mean() #10日均线值
  8. B.append(x5 > x10)
  1. import matplotlib.pyplot as plt
  2. o = data.openPrice
  3. m = len(B)
  4. w = 0 #利润
  5. cash = 1000000 #操作金额1亿,但考虑买的份额为100的整数,取1百万
  6. amount = 0
  7. PL = [] #利润w的数组
  8. for i in range(1, m):
  9. k = i + 10
  10. if B[i-1] == 0 and B[i] == 1 and not amount:
  11. amount = cash // o[k] #买入份额
  12. cash -= o[k] * amount
  13. elif B[i-1] == 1 and B[i]==0 and amount:
  14. cash += o[k] * amount #卖出的金额
  15. amount = 0
  16. # print cash, amount
  17. PL.append(cash + o[k] * amount)
  18. print("利润:{}".format(PL[-1]))
  19. plt.plot(PL,color="green",label="Profit and Loss")
  20. plt.xlabel("Date")
  21. plt.ylabel("Price")
  22. plt.show()
  23. plt.plot(a[10:], color="red",label="Profit and Loss")
  24. plt.show()
  25. 利润:1559132.78

用5日均线和10日均线进行判断 —- 改进版 - 图1

用5日均线和10日均线进行判断 —- 改进版 - 图2

2、 Uqer框架相同策略

  1. import numpy as np
  2. start = '2013-10-01' # 回测起始时间
  3. end = '2015-10-13' # 回测结束时间
  4. benchmark = 'SH50' # 策略参考标准
  5. universe = ['600030.XSHG'] # 股票池 中信证券
  6. capital_base = 100000 # 起始资金
  7. commission = Commission(0.0,0.0)
  8. window_short = 5 # 短均线周期
  9. window_long = 10 # 长均线周期
  10. def initialize(account): # 初始化虚拟账户状态
  11. account.fund = universe[0]
  12. def handle_data(account): # 每个交易日的买入卖出指令
  13. cp_hist = account.get_attribute_history('closePrice', window_long)[account.fund]
  14. short_mean = np.mean(cp_hist[-window_short:]) # 计算短均线值
  15. long_mean = np.mean(cp_hist[-window_long:]) #计算长均线值
  16. # 计算买入卖出信号
  17. if short_mean - long_mean > 0:
  18. if account.fund not in account.valid_secpos:
  19. # 空仓时全仓买入,买入股数为100的整数倍
  20. approximationAmount = int(account.cash / account.referencePrice[account.fund] / 100) * 100
  21. order(account.fund, approximationAmount)
  22. else:
  23. # 卖出时,全仓清空
  24. if account.fund in account.valid_secpos:
  25. order_to(account.fund, 0)

用5日均线和10日均线进行判断 —- 改进版 - 图3