Notes
Notes - notes.io |
lines = ('rsv',)
params = (
('period',9),
)
def _init_(self):
self.addminperiod(self.p.period+1)
def next(self):
close0 = self.data.close[0]
lowvar = min(self.data.low.get(size=self.p.period))
highvar = max(self.data.high.get(size=self.p.period))
rsv = (close0-lowvar)/(highvar - lowvar) * 100
self.lines.rsv[0] = rsv
class KDJ(bt.Indicator):
lines = ('K','D','J')
params = (
('period_rsv', 9),
('period_k', 3),
('period_d', 3),
)
def __init__(self):
min_period = self.p.period_rsv * self.p.period_k * self.p.period_d + 1
self.addminperiod(min_period)
rsv = RSV(self.data, period = self.p.period_rsv)
self.line.k = bt.ind.SmoothedMovingAverage(rsv,period=self.p.period_d)
self.line.d = bt.ind.SmoothedMovingAverage(self.line.k,period=self.p.period_d)
self.line.j = self.line.k*3 - self.line.d*2
def next(self):
self.lines.K[0] = self.line.k[0]
self.lines.D[0] = self.line.d[0]
self.lines.J[0] = self.line.j[0]
class StrategyAlpha(bt.Strategy):
def __init__(self):
self.kd = KDJ(
self.data[0],
)
self.signal = bt.ind.CrossUp(self.kd.K, self.kd.D)
self.signal2 = bt.ind.CrossDown(self.kd.K, self.kd.D)
self.buyprice = 0
self.buycomm = 0
self.opsize = 0
def log(self, txt, dt=None):
'''
Logging function for this strategy
'''
dt = dt or self.datas[0].datetime.date(0)
print('%s, %s' % (dt.isoformat(), txt))
def print(self):
print('当前可用资金', self.broker.getcash())
print('当前总资产', self.broker.getvalue())
print('当前持仓量', self.getposition(self.data).size)
print('当前持仓成本', self.getposition(self.data).price)
def notify_order(self, order):
if order.status in [order.Completed]:
cash_amt = self.broker.get_cash()
if order.isbuy():
self.buyprice = order.executed.price
self.buycomm = order.executed.comm
self.opsize = order.executed.size
gross_pnl = (order.executed.price - self.buyprice) * self.opsize
if self.broker.getcommissioninfo(order.data).margin:
gross_pnl *= self.broker.getcommissioninfo(order.data).p.mult
net_pnl = gross_pnl - self.buycomm - order.executed.comm
accountList.append([
len(self),
self.data.datetime.datetime(0),
"Buy Order",
order.executed.price,
self.datas[0].open[0],
self.datas[0].high[0],
self.datas[0].low[0],
self.datas[0].close[0],
self.datas[0].volume[0],
order.executed.size,
order.executed.value,
self.getposition(self.data).size,
self.getposition(self.data).price,
cash_amt,
order.executed.comm,
gross_pnl,
net_pnl,
self.broker.getvalue()
] )
else:
gross_pnl = (order.executed.price - self.buyprice) * self.opsize
if self.broker.getcommissioninfo(order.data).margin:
gross_pnl *= self.broker.getcommissioninfo(order.data).p.mult
net_pnl = gross_pnl - self.buycomm - order.executed.comm
accountList.append([
len(self),
self.data.datetime.datetime(0),
"Sell Order",
order.executed.price,
self.datas[0].open[0],
self.datas[0].high[0],
self.datas[0].low[0],
self.datas[0].close[0],
self.datas[0].volume[0],
order.executed.size,
order.executed.value,
self.getposition(self.data).size,
self.getposition(self.data).price,
cash_amt,
order.executed.comm,
gross_pnl,
net_pnl,
self.broker.getvalue()
] )
def next(self):
accountValueDF.loc[len(accountValueDF.index)] = [self.data.datetime.datetime(0), self.broker.getvalue()]
qsize = int(self.broker.get_cash() / self.data)-5
#print(qsize)
# if self.data.datetime.time() > datetime.time(15,13):
# self.close()
if self.signal > 0:
orderList.append([
len(self),
self.data.datetime.datetime(0),
"Sell Order",
self.datas[0].open[0],
self.datas[0].high[0],
self.datas[0].low[0],
self.datas[0].close[0],
self.datas[0].volume[0]
])
self.close()
# print(self.position)
self.sell(size=qsize)
#print("Buy {} shares".format( self.data.close[0]))
# print(self.position)
elif self.signal2 > 0:
orderList.append([
len(self),
self.data.datetime.datetime(0),
"Buy Order",
self.datas[0].open[0],
self.datas[0].high[0],
self.datas[0].low[0],
self.datas[0].close[0],
self.datas[0].volume[0]
])
self.close()
# print(self.position)
self.buy(size=qsize)
#print("Sale {} shares".format(self.data.close[0]))
# print(self.position)
if __name__ == '__main__':
starttime = time.time()
preprocess()
#data entry to be set in cofig files
#calendar_data_start = {'Year': [2019, 2020, 2021, 2022], 'Month': [1,1,1,1], 'Date': [24,2,4,4]}
#calendar_data_end = {'Year': [2019, 2020, 2021, 2022], 'Month': [12,12,12,1], 'Date': [31,31,31,25]}
calendar_data_start = {'Year': [2021], 'Month': [1], 'Date': [2]}
calendar_data_end = {'Year': [2021], 'Month': [12], 'Date': [31]}
calendar_df_start = pd.DataFrame(calendar_data_start)
calendar_df_end = pd.DataFrame(calendar_data_start)
dict_model_result = {'Year':[],
'AnnualReturn(%)':[],
'MaxDrawback(%)':[],
'Winrate':[]
}
res = pd.DataFrame(dict_model_result)
j=0
for i in calendar_df_start.itertuples():
start_year = getattr(i,'Year')
start_month = getattr(i,'Month')
start_date = getattr(i,'Date')
end_year = calendar_data_end['Year'][j]
end_month = calendar_data_end['Month'][j]
end_date = calendar_data_end['Date'][j]
data = GenericCSV_extend(
dataname=('data.csv'),
dtformat=('%Y-%m-%d %H:%M:%S'),
tmformat=('%H.%M.%S'),
fromdate=datetime.datetime(start_year, start_month, start_date),
todate=datetime.datetime(end_year, end_month, end_date),
timeframe=bt.TimeFrame.Minutes,
datetime=0,
open=1,
high=2,
low=3,
close=4,
rsv1=5,k1=6,d1=7,j1=8,
)
j+=1
datas = data
cerebro = bt.Cerebro()
cashsetting = 12000
cerebro.broker.setcash(cashsetting)
#cerebro.broker.set_slippage_fixed(0.005)
#filler = bt.broker.fillers.FixedBarPerc(perc=70)
filler = bt.broker.fillers.FixedSize(size=80)
cerebro.broker.set_filler(filler)
cerebro.addanalyzer(btanalyzers.SharpeRatio, _name='mysharpe')
cerebro.addanalyzer(btanalyzers.TimeReturn, _name='pnl')
cerebro.addanalyzer(btanalyzers.AnnualReturn, _name='_AnnualReturn')
cerebro.addanalyzer(btanalyzers.DrawDown, _name='_DrawDown')
cerebro.addanalyzer(bt.analyzers.TradeAnalyzer, _name="ta")
cerebro.addanalyzer(bt.analyzers.SQN, _name="sqn")
#cerebro.broker = bt.brokers.BackBroker(slip_perc=0.05)
cerebro.broker.setcommission(commission=0, margin=3, mult=1)
print('Start Testing for Year:', end_year)
cerebro.addstrategy(StrategyAlpha)
cerebro.adddata(datas)
#cerebro.broker.set_coo(True)
thestrats = cerebro.run()
thestrat = thestrats[0]
# Print out the final result
ar = thestrat.analyzers._AnnualReturn.get_analysis()
df = pd.DataFrame(ar,index=[0])#or use print(ar[2019])
dw = thestrat.analyzers._DrawDown.get_analysis()['max']['drawdown']
annual_yield = df[end_year][0]*100
print('Final Portfolio Value: %.2f' % cerebro.broker.getvalue())
print('Annual Return is:', df[end_year][0]*100, '%')
print('Drawdown is:', dw,'%')
# print the analyzers
printTradeAnalysis(thestrat.analyzers.ta.get_analysis())
printSQN(thestrat.analyzers.sqn.get_analysis())
#Get final portfolio Value
portvalue = cerebro.broker.getvalue()
AccountRecord = pd.DataFrame(accountList,columns=dict_AccountRecord)
Orderbook = pd.DataFrame(orderList,columns=dict_Orderbook)
print('Final Portfolio Value: ${}'.format(portvalue))
AccountRecord.to_csv("AccountRecord.csv")
time_cost = time.time() - starttime
|
Notes.io is a web-based application for taking notes. You can take your notes and share with others people. If you like taking long notes, notes.io is designed for you. To date, over 8,000,000,000 notes created and continuing...
With notes.io;
- * You can take a note from anywhere and any device with internet connection.
- * You can share the notes in social platforms (YouTube, Facebook, Twitter, instagram etc.).
- * You can quickly share your contents without website, blog and e-mail.
- * You don't need to create any Account to share a note. As you wish you can use quick, easy and best shortened notes with sms, websites, e-mail, or messaging services (WhatsApp, iMessage, Telegram, Signal).
- * Notes.io has fabulous infrastructure design for a short link and allows you to share the note as an easy and understandable link.
Fast: Notes.io is built for speed and performance. You can take a notes quickly and browse your archive.
Easy: Notes.io doesn’t require installation. Just write and share note!
Short: Notes.io’s url just 8 character. You’ll get shorten link of your note when you want to share. (Ex: notes.io/q )
Free: Notes.io works for 12 years and has been free since the day it was started.
You immediately create your first note and start sharing with the ones you wish. If you want to contact us, you can use the following communication channels;
Email: [email protected]
Twitter: http://twitter.com/notesio
Instagram: http://instagram.com/notes.io
Facebook: http://facebook.com/notesio
Regards;
Notes.io Team