df_stock['date']=pd.to_datetime(df_stock['time_key']) df_stock.to_csv(path + filename) df_stock.index = pd.to_datetime(df_stock.date) df_stock['openinterest']=0 df_stock = df_stock[['open','high','low','close','volume','openinterest']] df.update({stock:df_stock}) return df if __name__ == "__main__": start = '2017-01-09' end = '2020-09-05' code = ['HK.00700'] name = code df_stock = get_stockdata(code,start,end) df_cn = pd.read_csv('to_cn.csv',index_col=0) df_stock = get_stockdata(code,start,end) backtest = backtest.BackTest(Tech_roll, start, end, code, name,500000,bDraw = True) result = backtest.run() #result = backtest.run() #result = backtest.optRun(myperiod = range(50,150,20)) #print(result) print(result) #maxindex = ret[ret == ret.max()].index #bestResult = result.loc[maxindex,:] #print(bestResult.loc[:, ["夏普比率", "参数名", "参数值", "年化收益率"]])
stock = tradeBar.iloc[i].成交量 commit = tradeBar.iloc[i].手续费 # 进行交易 self.__doTrade(data, name, price, stock, commit, orderType) def next(self): if self.order: return self.doTrade() def stop(self): self.order = self.close() self.log("最大回撤:-%.2f%%" % self.stats.drawdown.maxdrawdown[-1], doprint=True) if __name__ == "__main__": # 加载数据,建立数据源 start = "2018-01-01" end = "2020-07-05" name = ["300ETF", "nasETF"] code = ["510300", "513100"] backtest = backtest.BackTest(TradeStrategy, start, end, code, name, cash = 1000) results = backtest.run() # backtest.output() print(results) #returns = backtest.getReturns() # print(returns) # returns[0].to_csv("1.csv") # returns[1].to_csv("2.csv")
tradeBar = self.df_record.loc[date.strftime("%Y-%m-%d"), :] # print("bar数据", date, data._name) if len(tradeBar) != 0: for i in range(len(tradeBar)): name = tradeBar.iloc[i].证券名称 price = tradeBar.iloc[i].成交均价 stock = tradeBar.iloc[i].成交量 commit = tradeBar.iloc[i].手续费 # 进行交易 self.__doTrade(data, name, price, stock, commit, orderType) def next(self): if self.order: return self.doTrade() def stop(self): self.log("最大回撤:-%.2f%%" % self.stats.drawdown.maxdrawdown[-1], doprint=True) if __name__ == "__main__": # 加载数据,建立数据源 start = "2018-01-01" end = "2020-07-05" name = ["300ETF", "nasETF"] code = ["510300", "513100"] backtest = backtest.BackTest(TradeStrategy, start, end, code, name) backtest.run() backtest.output()
import backtest from random import randint ''' A silly example algorithm for demonstration purposes. BUY/SELL or HOLD based on a coin flip. ''' class Algo: def __init__(self): self.holding = False def tick(self, frame): res = randint(0, 1) if res == 0 and not self.holding: self.holding = True return 'BUY', 100 elif res == 1 and self.holding: self.holding = False return 'SELL', 100 else: return 'NOTHING' stubAlgo = Algo() results = backtest.run(stubAlgo, currency='USDT_BTC') print 'total profit: ' + str(sum(results[1]))