230429_bt.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329
  1. import os
  2. import traceback
  3. import numpy as np
  4. from sqlalchemy import create_engine
  5. import pandas as pd
  6. import pymysql
  7. import backtrader as bt
  8. import backtrader.indicators as btind
  9. import datetime
  10. import math
  11. from datetime import datetime as dt
  12. import multiprocessing as mp
  13. from backtrader.feeds import PandasData
  14. import platform
  15. # import multiprocessing
  16. # import matplotlib
  17. class MyPandasData(PandasData):
  18. lines = ('hl', 'dif', 'dea', 'macd', 'rsi_6', 'rsi_12', 'rsi_24',)
  19. params = (('hl', 7),
  20. ('dif', 8),
  21. ('dea', 9),
  22. ('macd', 10),
  23. ('rsi_6', 11),
  24. ('rsi_12', 12),
  25. ('rsi_24', 13),
  26. )
  27. '''
  28. lines = ('change_pct', 'net_amount_main', 'net_pct_main', 'net_amount_xl', 'net_pct_xl', 'net_amount_l', 'net_pct_l'
  29. , 'net_amount_m', 'net_pct_m', 'net_amount_s', 'net_pct_s',)
  30. params = (('change_pct', 7),
  31. ('net_amount_main', 8),
  32. ('net_pct_main', 9),
  33. ('net_amount_xl', 10),
  34. ('net_pct_xl', 11),
  35. ('net_amount_l', 12),
  36. ('net_pct_l', 13),
  37. ('net_amount_m', 14),
  38. ('net_pct_m', 15),
  39. ('net_amount_s', 16),
  40. ('net_pct_s', 17),
  41. )
  42. '''
  43. class TestStrategy(bt.Strategy):
  44. params = (
  45. ("num", 3),
  46. ('Volatility', 0),
  47. ('rate', 5), # 注意要有逗号!!
  48. )
  49. def log(self, txt, dt=None):
  50. ''' Logging function for this strategy'''
  51. dt = dt or self.datas[0].datetime.date(0)
  52. # print('%s, %s' % (dt.isoformat(), txt))
  53. def __init__(self):
  54. # self.num = num
  55. # self.Volatility = Volatility/100
  56. # Keep a reference to the "close" line in the data[0] dataseries
  57. self.pos_price = 0
  58. self.dataclose = self.datas[0].close
  59. self.dataopen = self.datas[0].open
  60. self.high = self.datas[0].high
  61. self.low = self.datas[0].low
  62. self.volume = self.datas[0].volume
  63. self.hl = self.datas[0].hl
  64. self.dif = self.datas[0].dif
  65. self.dea = self.datas[0].dea
  66. self.macd = self.datas[0].macd
  67. self.rsi_6 = self.datas[0].rsi_6
  68. self.rsi_12 = self.datas[0].rsi_12
  69. self.rsi_24 = self.datas[0].rsi_24
  70. # self.change_pct = self.datas[0].change_pct
  71. # self.net_amount_main = self.datas[0].net_amount_main
  72. # self.net_pct_main = self.datas[0].net_pct_main
  73. # self.net_amount_xl = self.datas[0].net_amount_xl
  74. # self.net_pct_xl = self.datas[0].net_pct_xl
  75. # self.net_amount_l = self.datas[0].net_amount_l
  76. # self.net_pct_l = self.datas[0].net_pct_l
  77. self.sma5 = btind.MovingAverageSimple(self.datas[0].close, period=5)
  78. self.sma10 = btind.MovingAverageSimple(self.datas[0].close, period=10)
  79. self.sma20 = btind.MovingAverageSimple(self.datas[0].close, period=20)
  80. self.sma60 = btind.MovingAverageSimple(self.datas[0].close, period=60)
  81. def notify_order(self, order):
  82. """
  83. 订单状态处理
  84. Arguments:
  85. order {object} -- 订单状态
  86. """
  87. if order.status in [order.Submitted, order.Accepted]:
  88. # 如订单已被处理,则不用做任何事情
  89. return
  90. # 检查订单是否完成
  91. if order.status in [order.Completed]:
  92. if order.isbuy():
  93. self.buyprice = order.executed.price
  94. self.buycomm = order.executed.comm
  95. self.bar_executed = len(self)
  96. # 订单因为缺少资金之类的原因被拒绝执行
  97. elif order.status in [order.Canceled, order.Margin, order.Rejected]:
  98. pass
  99. # self.log('Order Canceled/Margin/Rejected')
  100. # 订单状态处理完成,设为空
  101. self.order = None
  102. def notify_trade(self, trade):
  103. """
  104. 交易成果
  105. Arguments:
  106. trade {object} -- 交易状态
  107. """
  108. if not trade.isclosed:
  109. return
  110. # 显示交易的毛利率和净利润
  111. # self.log('OPERATION PROFIT, GROSS %.2f, NET %.2f' % (trade.pnl, trade.pnlcomm))
  112. def next(self):
  113. # print(self.num,self.Volatility)
  114. # Simply log the closing price of the series from the reference
  115. # self.sma20[-2] < self.sma20[-1] < self.sma20[0] and self.sma10[-2] < self.sma10[-1] < self.sma10[0]
  116. # and (self.sma5[-1] < self.sma10[-1])
  117. # and (self.net_pct_l[0] > 10) and (self.net_pct_xl[0] > 3) \
  118. # and (self.net_amount_main[-1] > 0) and (self.net_amount_main[0] > 0)
  119. if len(self) > self.params.num:
  120. vola = self.params.Volatility / 100
  121. rate = self.params.rate / 100
  122. lowest = np.min(self.low.get(size=self.params.num))
  123. highest = np.max(self.high.get(size=self.params.num))
  124. if (self.hl[-2] == 2 or self.hl[-2] == 1) and self.dataclose[0] > self.sma5[0] > self.sma5[-1] \
  125. and self.sma5[-3]/self.sma5[-2] > self.sma5[-2]/self.sma5[-1] > (1+rate) \
  126. and self.sma5[0] > self.sma5[-1] > (1+rate)\
  127. and (((lowest * (1 - vola)) < self.low[-2] < (lowest * (1 + vola))) or (
  128. (lowest * (1 - vola)) < self.low[-1] < (lowest * (1 + vola)))) \
  129. and self.volume[0] >= self.volume[-1] and self.dataclose[0] > self.dataopen[0] \
  130. and self.sma5[0] < self.sma10[0] and self.sma10[0] > self.sma20[0]:
  131. while True:
  132. m = -3
  133. if (self.hl[m] == 2 or self.hl[m] == 1) and self.macd[m] < self.macd[-1] and self.dataclose[m] > self.dataclose[-1]:
  134. self.order = self.buy()
  135. self.pos_price = self.low[-1]
  136. break
  137. m -= 1
  138. if m < (-len(self)):
  139. break
  140. elif ((self.hl[0] == 5 or self.dataclose[0] < self.sma5[0]) and ((highest * (1 - vola)) < self.high[-2] < (highest * (1 + vola)))) \
  141. or self.dataclose[0] < self.pos_price:
  142. self.order = self.close()
  143. self.pos_price = 0
  144. def stop(self):
  145. # pass
  146. self.log(u'(MA趋势交易效果) Ending Value %.2f' % (self.broker.getvalue()))
  147. def err_call_back(err):
  148. print(f'出错啦~ error:{str(err)}')
  149. traceback.format_exc(err)
  150. def to_df(lt):
  151. print('开始存数据')
  152. df = pd.DataFrame(list(lt), columns=['周期', '波动率', 'MA5斜率', '盈利个数', '盈利比例', '总盈利', '平均盈利', '最大盈利',
  153. '最小盈利', '总亏损', '平均亏损', '最大亏损', '最小亏损'])
  154. df.sort_values(by=['周期', '波动率', 'MA5斜率'], ascending=True, inplace=True)
  155. df = df.reset_index(drop=True)
  156. if platform.node() == 'DanieldeMBP.lan':
  157. df.to_csv(f"/Users/daniel/Documents/策略/策略穷举{dt.now().strftime('%Y%m%d')}.csv", index=True, encoding='utf-8', mode='w')
  158. else:
  159. df.to_csv(f"C:\Daniel\策略\策略穷举{dt.now().strftime('%Y%m%d')}.csv", index=True, encoding='utf-8', mode='w')
  160. print(f'结果:{df}')
  161. def backtrader(list_date, table_list, result, result_change, result_change_fall, num, Volatility, rate, err_list):
  162. print(f'{num}天波动率为{Volatility}%MA5斜率为{rate}', 'myPID is ', os.getpid())
  163. sttime = dt.now()
  164. engine = create_engine('mysql+pymysql://root:r6kEwqWU9!v3@localhost:3307/qmt_stocks_tech?charset=utf8')
  165. for stock in table_list:
  166. # print(stock)
  167. stk_df = pd.read_sql_table(stock, engine)
  168. stk_df.time = pd.to_datetime(stk_df.time)
  169. try:
  170. stk_df['HL'] = stk_df['HL'].map({'L': 1,
  171. 'LL': 2,
  172. 'L*': 3,
  173. 'H': 4,
  174. 'HH': 5,
  175. 'H*': 6,
  176. '-': 7})
  177. except BaseException:
  178. print(f'{stock}数据不全,不做测试')
  179. else:
  180. if len(stk_df) > 60:
  181. cerebro = bt.Cerebro()
  182. cerebro.addstrategy(TestStrategy, num=num, Volatility=Volatility, rate=rate)
  183. cerebro.addsizer(bt.sizers.FixedSize, stake=10000)
  184. data = MyPandasData(dataname=stk_df,
  185. fromdate=datetime.datetime(2017, 1, 1),
  186. todate=datetime.datetime(2022, 10, 30),
  187. datetime='time',
  188. open='open_back',
  189. close='close_back',
  190. high='high_back',
  191. low='low_back',
  192. volume='volume_back',
  193. hl='HL',
  194. dif='dif',
  195. dea='dea',
  196. macd='macd',
  197. rsi_6='rsi_6',
  198. rsi_12='rsi_12',
  199. rsi_24='rsi_24',
  200. )
  201. # print('取值完成')
  202. cerebro.adddata(data, name=stock)
  203. cerebro.broker.setcash(100000.0)
  204. cerebro.broker.setcommission(0.005)
  205. cerebro.addanalyzer(bt.analyzers.PyFolio)
  206. # 策略执行前的资金
  207. # print('启动资金: %.2f' % cerebro.broker.getvalue())
  208. try:
  209. # 策略执行
  210. cerebro.run()
  211. except IndexError:
  212. err_list.append(stock)
  213. else:
  214. if cerebro.broker.getvalue() > 100000.0:
  215. result_change.append((cerebro.broker.getvalue() / 10000 - 1))
  216. result.append(stock)
  217. # print('recode!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!')
  218. # print(result)
  219. else:
  220. result_change_fall.append((1 - cerebro.broker.getvalue() / 10000))
  221. # print('aaaaaaaaaaa')
  222. # print(result_change_fall)
  223. if len(result) * len(result_change) * len(result_change_fall) != 0:
  224. print(f'以{num}内最低值波动{Volatility}为支撑、MA5斜率为{rate}%,结果状态为:')
  225. print('正盈利的个股为:', len(result_change), '成功率为:', len(result) / len(table_list))
  226. print(
  227. f'总盈利:{np.sum(result_change)} 平均盈利:{np.mean(result_change)},最大盈利:{np.max(result_change)}, 最小盈利:{np.min(result_change)}')
  228. print(
  229. f'总亏损:{np.sum(result_change_fall)},平均亏损:{np.mean(result_change_fall)},最大亏损:{np.min(result_change_fall)} 最小亏损:{np.max(result_change_fall)}')
  230. list_date.append([num, Volatility, rate, len(result), len(result) / len(table_list), np.nansum(result_change),
  231. np.nanmean(result_change), np.nanmax(result_change), np.min(result_change),
  232. np.nansum(result_change_fall), np.nanmean(result_change_fall),
  233. np.nanmin(result_change_fall), np.nanmax(result_change_fall)])
  234. to_df(list_date)
  235. endtime = dt.now()
  236. print(f'{num}天波动率为{Volatility}%MA5斜率为{rate},myPID is {os.getpid()}.本轮耗时为{endtime - sttime}')
  237. else:
  238. print('阿欧', len(result), len(result_change), len(result_change_fall), num, Volatility, rate, err_list)
  239. list_date.append([num, Volatility, rate, 0, len(result) / len(table_list), len(result),
  240. len(result), len(result), len(result), len(result), len(result), len(result), 0])
  241. to_df(list_date)
  242. # cerebro.plot()
  243. # df = pd.DataFrame(
  244. # columns=['周期', '波动率', 'MA5斜率', '盈利个数', '盈利比例', '总盈利', '平均盈利', '最大盈利', '最小盈利', '总亏损',
  245. # '平均亏损', '最大亏损', '最小亏损'])
  246. if __name__ == '__main__':
  247. starttime = dt.now()
  248. print(starttime)
  249. # print(type(platform.node()))
  250. # engine = create_engine('mysql+pymysql://root:r6kEwqWU9!v3@localhost:3307/hlfx?charset=utf8', poolclass=NullPool)
  251. # stocks = pd.read_sql_query(
  252. # 'select value from MA5_1d', engine_hlfx)
  253. fre = '1d'
  254. db = pymysql.connect(host='localhost',
  255. user='root',
  256. port=3307,
  257. password='r6kEwqWU9!v3',
  258. database='qmt_stocks_tech')
  259. cursor = db.cursor()
  260. cursor.execute("show tables like '%%%s%%' " % fre)
  261. table_list = [tuple[0] for tuple in cursor.fetchall()]
  262. # print(table_list)
  263. # table_list = table_list[0:10]
  264. list_date = mp.Manager().list()
  265. thread_list = []
  266. pool = mp.Pool(processes=mp.cpu_count())
  267. for num in range(60, 180, 20):
  268. for Volatility in range(5, 10, 1):
  269. for rate in range(1, 4, 1):
  270. step = math.ceil(len(table_list) / mp.cpu_count())
  271. result = []
  272. result_change = []
  273. result_change_fall = []
  274. err_list = []
  275. print(f'{num}天波动率为{Volatility}%MA5斜率为{rate}')
  276. # for i in range(0, len(table_list), step):
  277. stattime = dt.now()
  278. # thd = threading.local()
  279. # print(i)
  280. # p = mp.Process(target=backtrader, args=(df, table_list, result, result_change, result_change_fall,
  281. # num, Volatility, rate, err_list))
  282. # thread_list.append(p)
  283. pool.apply_async(func=backtrader,
  284. args=(list_date, table_list, result, result_change, result_change_fall,
  285. num, Volatility, rate, err_list,), error_callback=err_call_back)
  286. # p.start()
  287. # p.join()
  288. # print(thread_list)
  289. # for thread in thread_list:
  290. # thread.start()
  291. # for thread in thread_list:
  292. # thread.join()
  293. pool.close()
  294. pool.join()
  295. edtime = dt.now()
  296. print('总耗时:', edtime - starttime)
  297. # df.to_csv(r'C:\Users\Daniel\Documents\策略穷举2.csv', index=True)