230202_backtrader.py 13 KB

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