230505_bt.py 15 KB

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