bug1.py
# -*- coding: utf-8 -*-
import traceback
import datetime
import os.path
import sys
import pickle
import backtrader as bt
from backtrader.indicators import EMA
import pandas as pd
class TestStrategy(bt.Strategy):
global_last_buy = 0
global_success_times = 0
global_failed_times = 0
global_stock_code = ''
global_ready_count = 0
def __init__(self):
self.dataclose = self.datas[0].close
self.volume = self.datas[0].volume
self.order = None
self.buyprice = None
self.buycomm = None
# 9個交易日內最高價
self.high_nine = bt.indicators.Highest(self.data.high, period=9)
# 9個交易日內最低價
self.low_nine = bt.indicators.Lowest(self.data.low, period=9)
# 計算rsv值
self.rsv = 100 * bt.DivByZero(
self.data_close - self.low_nine, self.high_nine - self.low_nine, zero=None
)
# 計算rsv的3周期加權平均值,即K值
self.K = bt.indicators.EMA(self.rsv, period=3, plot=False)
# D值=K值的3周期加權平均值
self.D = bt.indicators.EMA(self.K, period=3, plot=False)
# J=3*K-2*D
self.J = 3 * self.K - 2 * self.D
# MACD策略引數
me1 = EMA(self.data, period=12)
me2 = EMA(self.data, period=26)
self.macd = me1 - me2
self.signal = EMA(self.macd, period=9)
bt.indicators.MACDHisto(self.data)
def next(self):
#print('global_stock_code:'+global_stock_code)
if TestStrategy.global_ready_count<20:
TestStrategy.global_ready_count = TestStrategy.global_ready_count + 1
return
if not self.position:
# 買入:基于MACD策略
condition1 = self.macd[-1] - self.signal[-1]
condition2 = self.macd[0] - self.signal[0]
if condition1 < 0 and condition2 > 0:
self.order = self.buy()
print('buy:'+str(self.datetime.date())+",price:"+str(self.dataclose[0]))
TestStrategy.global_last_buy = self.dataclose[0]
else:
# 賣出:基于KDJ策略
condition1 = self.J[-1] - self.D[-1]
condition2 = self.J[0] - self.D[0]
if condition1 > 0 or condition2 < 0:
self.order = self.sell()
print('sell:'+str(self.datetime.date())+",price:"+str(self.dataclose[0]))
diff = self.dataclose[0]-TestStrategy.global_last_buy
if(diff>0):
TestStrategy.global_success_times = TestStrategy.global_success_times + 1
else:
TestStrategy.global_failed_times = TestStrategy.global_failed_times + 1
def run_cerebro(stock_code, result):
"""
運行策略
:param stock_file: 股票資料檔案位置
:param result: 回測結果存盤變數
"""
cerebro = bt.Cerebro()
cerebro.addstrategy(TestStrategy)
start_date='2019-01-01'
global_start_date = start_date
global_end_date = '2020-12-01'
df = pd.read_csv('bug_data.csv')
print(df)
df['stock_date'] = pd.to_datetime(df['stock_date'],infer_datetime_format=True)
# 加載資料到模型中
data = bt.feeds.PandasData(
dataname=df,
fromdate=datetime.datetime(2019, 1, 1),
todate=datetime.datetime.now().date(),
datetime=0,
open=3,
high=4,
low=5,
close=2,
volume=1
)
cerebro.adddata(data)
# 本金10000,每次交易100股
cerebro.broker.setcash(10000)
cerebro.addsizer(bt.sizers.FixedSize, stake=100)
# 千三傭金
cerebro.broker.setcommission(commission=0.003)
# 運行策略
cerebro.run()
# 剩余本金
cerebro.broker.get_value()
money_left = cerebro.broker.getvalue()
# 將最侄訓報率以百分比的形式回傳
result['stock_code']=stock_code
result['stock_name']=stock_name
result['result'] = float(money_left - 10000) / 10000
result['start_date']=global_start_date
result['end_date']=global_end_date
def run_it():
result = {}
base_rows = []
all_rows = []
TestStrategy.global_success_times=0
TestStrategy.global_failed_times=0
TestStrategy.global_stock_code = 'sh.600185'
stock_code = 'sh.600185'
try:
run_cerebro(stock_code, result)
print(result)
start_date = result['start_date']
end_date = result['end_date']
money = result['result']
print('------------------------------')
except Exception as e:
print(e)
traceback.print_exc()
# 計算
# pos = []
# neg = []
# for data in result:
# res = result[data]
# if res > 0:
# pos.append(res)
# else:
# neg.append(res)
# print(f'正收益數量: {len(pos)}, 負收益數量:{len(neg)}')
# print(result)
run_it()
# scheduler = BlockingScheduler()
# scheduler.add_job(run_it, 'cron', day_of_week='1-5', hour=19, minute=55)
# scheduler.start()
F:\dev\python\stock>python bug1.py
stock_date stock_volume stock_close stock_open stock_high stock_low
0 2019-01-02 11824389.0 4.06 4.06 4.09 3.98
1 2019-01-03 6728744.0 3.97 4.06 4.07 3.95
2 2019-01-04 8933075.0 4.05 3.92 4.05 3.90
3 2019-01-07 12017628.0 4.05 4.05 4.09 4.00
4 2019-01-08 5025040.0 3.99 4.03 4.03 3.97
.. ... ... ... ... ... ...
461 2020-11-26 25736046.0 8.24 8.35 8.37 8.13
462 2020-11-27 16375927.0 8.28 8.23 8.30 8.14
463 2020-11-30 24285227.0 8.08 8.25 8.34 8.04
464 2020-12-01 38463484.0 8.18 8.06 8.25 7.92
465 2020-12-02 31435215.0 8.24 8.20 8.34 8.13
[466 rows x 6 columns]
must be real number, not NoneType
Traceback (most recent call last):
File "bug1.py", line 170, in run_it
run_cerebro(stock_code, result)
File "bug1.py", line 140, in run_cerebro
cerebro.run()
File "C:\Users\Administrator\AppData\Local\Programs\Python\Python37\lib\site-packages\backtrader\cerebro.py", line 1127, in run
runstrat = self.runstrategies(iterstrat)
File "C:\Users\Administrator\AppData\Local\Programs\Python\Python37\lib\site-packages\backtrader\cerebro.py", line 1293, in runstrategies
self._runonce(runstrats)
File "C:\Users\Administrator\AppData\Local\Programs\Python\Python37\lib\site-packages\backtrader\cerebro.py", line 1652, in _runonce
strat._once()
File "C:\Users\Administrator\AppData\Local\Programs\Python\Python37\lib\site-packages\backtrader\lineiterator.py", line 297, in _once
indicator._once()
File "C:\Users\Administrator\AppData\Local\Programs\Python\Python37\lib\site-packages\backtrader\linebuffer.py", line 631, in _once
self.once(self._minperiod, self.buflen())
File "C:\Users\Administrator\AppData\Local\Programs\Python\Python37\lib\site-packages\backtrader\functions.py", line 73, in once
dst[i] = srca[i] / b if b else zero
TypeError: must be real number, not NoneType
求教為什么出錯
csv檔案 :https://download.csdn.net/download/ying1979/13244690
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/229529.html
上一篇:給label設定了一個父布局,然后給label設定圖片,也設定了自適應,但是圖片仍然會原圖顯示為什么呢?如何更改
下一篇:Python pandas 報錯
