from pyalgotrade_tushare import tools, barfeed instruments = ["000001"] feeds = tools.build_feed(instruments, 2016, 2018, "histdata")
def __init__(self, feed, instrument, brk): super().__init__(feed, brk) self.__position = None self.__instrument = instrument self.getBroker() self.__cost = 0.0 def onEnterOk(self, position): execInfo = position.getEntryOrder().getExecutionInfo() def onEnterCanceled(self, position): self.__position = None def onExitOk(self, position): execInfo = position.getExitOrder().getExecutionInfo() self.info("卖出 %.2f" % (execInfo.getPrice())) self.__position = None def onExitCanceled(self, position): # If the exit was canceled, re-submit it. self.__position.exitMarket() def onBars(self, bars): brk = self.getBroker() shares = 100 price = bars[self.__instrument].getPrice() if brk.getCash() < price*shares: self.info("现金不足") return self.__position = self.enterLong(self.__instrument, shares, True) self.__cost += brk.getCommission().calculate(brk, price, shares) self.info("可用现金%.2f 股价%.2f 持股数量%d 市值1:%.2f 市值2:%.2f 计算市值:%.2f 交易成本%.2f" % (brk.getCash(), price, brk.getShares(self.__instrument), brk.getEquity(), self.getResult(), (brk.getCash() + brk.getShares(self.__instrument)*price), self.__cost))
# x = input("按任意键继续")
# 设置手续费 broker_commision = broker.backtesting.TradePercentage(0.0003) brk = broker.backtesting.Broker(cash, feeds, broker_commision)
myStrategy = MyStrategy(feeds, instruments[0], brk)
retAnalyzer = returns.Returns() myStrategy.attachAnalyzer(retAnalyzer) sharpeAnalyzer = sharpe.SharpeRatio() myStrategy.attachAnalyzer(sharpeAnalyzer) drawDownAnalyzer = drawdown.DrawDown() myStrategy.attachAnalyzer(drawDownAnalyzer) tradesAnalyzer = trades.Trades() myStrategy.attachAnalyzer(tradesAnalyzer)
from pyalgotrade import plotter plter = plotter.StrategyPlotter(myStrategy)
plter.getOrCreateSubplot("return").addDataSeries("retuens", retAnalyzer.getReturns())
plter.getOrCreateSubplot("CumReturn").addDataSeries("CumReturn",retAnalyzer.getCumulativeReturns
量化投资学习笔记01——初识Pyalgotrade量化交易回测框架
原文:https://www.cnblogs.com/zwdnet/p/12027268.html