Home > other >  Ask why error, data problems, how to change
Ask why error, data problems, how to change

Time:12-04

Bug1. Py

# - * - coding: utf-8 - * -

The import traceback
Import a datetime
The import OS. Path
The import sys
The import pickled
The import backtrader as bt
The from backtrader. Indicators import EMA
The import pandas as pd


The 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
The self. The volume=self. Datas [0]. Volume

The self. The order=None
Self. Buyprice=None
Self. Buycomm=None

# 9 days highest
Self. High_nine=bt. Indicators. Highest (self) data), period=9)
Your lowest price for # 9 days
Self. Low_nine=bt. Indicators. The Lowest (self. Data. Low, period=9)
# calculation RSV value
Self. RSV=100 * bt. DivByZero (
Self. Data_close - self. Low_nine, self high_nine - self. Low_nine, zero=None
)
# calculation RSV weighted average of 3 cycles, the K value
Self. K=bt. Indicators. EMA (self. RSV, period=3, the plot=False)
# D=K value weighted average 3 cycle
Self. D=bt. Indicators. EMA (self. K, period=3, the plot=False)
# J=3-2 D * * K
Self. J=3 * self - 2 K * self. D

# MACD strategy parameter
Me1=EMA (self) data, the period=12)
Me2=EMA (self) data, the period=26)
The self. The macd=me1 - me2
The self. The signal=EMA (self. The macd, period=9)
Bt. Indicators. MACDHisto (self) data)




Def next (self) :

# print (+ global_stock_code global_stock_code:)
If TestStrategy. Global_ready_count & lt; 20:
TestStrategy. Global_ready_count=TestStrategy. Global_ready_count + 1
Return
If not the self. Position:
Buy: # based on MACD strategy




Condition1=self. Macd [1] - self. Signal [1]
Condition2=self. The macd [0] - self. Signal [0]
If condition1 & lt; 0 and condition2 & gt; 0:
The self. The order=self. Buy ()
Print (' buy: + STR (self) datetime) date ()) + ", price: "+ STR (self) dataclose [0]))

TestStrategy. Global_last_buy=self. Dataclose [0]


The else:
# sold: based on the strategy of KDJ
Condition1=self. J [1] - self D [1]
Condition2=self. J [0] - self D [0]
If condition1 & gt; 0 or condition2 & lt; 0:
The self. The order=self. Sell ()
Print (" sell: "+ STR (self) datetime) date ()) +", price: "+ STR (self) dataclose [0]))

The diff=self. Dataclose [0] - TestStrategy. Global_last_buy
If (diff> 0) :
TestStrategy. Global_success_times=TestStrategy. Global_success_times + 1
The else:
TestStrategy. Global_failed_times=TestStrategy. Global_failed_times + 1




Def run_cerebro (stock_code, result) :
"" "
Operation strategy
: param stock_file: stock data file location
: param result: back to the measurement results storage variable
"" "
Cerebro=bt. Cerebro ()

Cerebro. Addstrategy (TestStrategy)

The start_date='2019-01-01'
Global_start_date=the start_date is
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)

# to load data into the model
Data=https://bbs.csdn.net/topics/bt.feeds.PandasData (
Dataname=df,
Fromdate=datetime. Datetime (2019, 1, 1),
Todate=datetime. Datetime. Now () the date (),
Datetime=0,
The open=3,
High=4,
Low=5,
The close=2,
Volume=1
)


Cerebro. Adddata (data)


# 10000 of the principal, 100 shares for each trade
Cerebro. Broker. Setcash (10000)
Cerebro. Addsizer (bt) sizers) FixedSize, gaining=100)

# three hundred commission
Cerebro. Broker. Setcommission (appointed=0.003)

Operation strategy #
Cerebro. The run ()

# the remaining principal
Cerebro. Broker. Get_value ()
Money_left=cerebro. Broker. Getvalue ()

# will eventually return in the form of percentage return
Result [' stock_code]=stock_code
Result [' stock_name]=stock_name
Result [' result ']=float (money_left - 10000)/10000
Result [' the 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)
The start_date=result [' the start_date]
End_date=result [' end_date]
Money=result [' result ']
Print (" -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- ')
Except the Exception as e:
Print (e)
Traceback. Print_exc ()

# computing
# pos=[]
# neg=[]
# for the data in the result:
# res=result [data]
# if res & gt; 0:
# pos. Append (res)
# the else:
# neg. Append (res)
# print (f 'number of benefits: {len (pos)}, number of negative earnings: {len (neg)}')
# print (result)

Run_it ()

# scheduler=BlockingScheduler ()
# scheduler. Add_job (run_it, 'cron, day_of_week=' 1-5, hour=19, minute=55)
# scheduler. The start ()




nullnullnullnullnullnullnullnullnullnullnullnullnullnullnullnullnullnullnullnullnullnullnullnullnullnullnullnullnullnullnullnullnullnullnullnullnullnullnull
  • Related