def testStrategy(): from pyalgotrade import bar from pyalgotrade import plotter strat = DoubleMA frequency = bar.Frequency.MINUTE paras = [5, 20] plot = True #############################################path set ############################33 feed = Feed(frequency) feed.loadBars('bitmex_BCHZ18', test_back=True) strat = strat(feed, "bitmex_BCHZ18", *paras) from pyalgotrade.stratanalyzer import returns from pyalgotrade.stratanalyzer import sharpe from pyalgotrade.stratanalyzer import drawdown from pyalgotrade.stratanalyzer import trades retAnalyzer = returns.Returns() strat.attachAnalyzer(retAnalyzer) sharpeRatioAnalyzer = sharpe.SharpeRatio() strat.attachAnalyzer(sharpeRatioAnalyzer) drawDownAnalyzer = drawdown.DrawDown() strat.attachAnalyzer(drawDownAnalyzer) tradesAnalyzer = trades.Trades() strat.attachAnalyzer(tradesAnalyzer) if plot: plt = plotter.StrategyPlotter(strat, True, True, True) strat.run() if plot: plt.plot() # 夏普率 sharp = sharpeRatioAnalyzer.getSharpeRatio(0.02) print(sharp) # 最大回撤 maxdd = drawDownAnalyzer.getMaxDrawDown() print(maxdd) # 收益率 return_ = retAnalyzer.getCumulativeReturns()[-1] print(return_) # 收益曲线 return_list = [] for item in retAnalyzer.getCumulativeReturns(): return_list.append(item) print(return_list)
def main(plot): instruments = ['bitmex_XBTUSD','okex_BTCUSDT'] feed = Feed(Frequency.SECOND) feed.loadBars("bitmex_XBTUSD", test_back=True) feed.loadBars("okex_BTCUSDT", test_back=True) '''初始保证金''' initCash = 1000000 '''手续费设置 目前不支持多标的设置不同的手续费类型 3种手续费类型: NoCommission:None 默认 FixedPerTrade:固定金额 TradePercentage:按比例收费 ''' commission = TradePercentage(0.0003) broker = Broker(initCash,feed,commission) #设置为滑点模型,默认为 NoSlippage #broker.getFillStrategy().setSlippageModel(VolumeShareSlippage) #设置交易量限制 #每一个bar中的 volume * limit #broker.getFillStrategy().setVolumeLimit(0.1) strat = MultiSymbols(feed, instruments, broker) sharpeRatioAnalyzer = sharpe.SharpeRatio() strat.attachAnalyzer(sharpeRatioAnalyzer) returnsAnalyzer = returns.Returns() strat.attachAnalyzer(returnsAnalyzer) if plot: plt = plotter.StrategyPlotter(strat, False, False, True) plt.getOrCreateSubplot("cash").addCallback("Cash", lambda x: strat.getBroker().getCash()) # Plot strategy vs. SPY cumulative returns. # plt.getOrCreateSubplot("returns").addDataSeries("SPY", cumret.CumulativeReturn(feed["SPY"].getPriceDataSeries())) plt.getOrCreateSubplot("returns").addDataSeries("Strategy", returnsAnalyzer.getCumulativeReturns()) strat.run() print("Sharpe ratio: %.2f" % sharpeRatioAnalyzer.getSharpeRatio(0.05)) print("Returns: %.2f %%" % (returnsAnalyzer.getCumulativeReturns()[-1] * 100)) if plot: plt.plot()
def main(plot): initialCash = 10000 instrumentsByClass = { # "bitmex_LTCZ18": ["bitmex_LTCZ18"], "okex_LIGHTBTC": ["okex_LIGHTBTC"], "binance_ADABTC": ["binance_ADABTC"], } # Download the bars. instruments = [] for assetClass in instrumentsByClass: instruments.extend(instrumentsByClass[assetClass]) # feed = yahoofinance.build_feed(instruments, 2007, 2013, "data", skipErrors=True) instrument = "bitmex_LTCZ18" feed = Feed(Frequency.MINUTE) # feed.loadBars(instrument, test_back=True) feed.loadBars('okex_LIGHTBTC', test_back=True) feed.loadBars("binance_ADABTC", test_back=True) strat = MarketTiming(feed, instrumentsByClass, initialCash) sharpeRatioAnalyzer = sharpe.SharpeRatio() strat.attachAnalyzer(sharpeRatioAnalyzer) returnsAnalyzer = returns.Returns() strat.attachAnalyzer(returnsAnalyzer) if plot: plt = plotter.StrategyPlotter(strat, False, False, True) plt.getOrCreateSubplot("cash").addCallback( "Cash", lambda x: strat.getBroker().getCash()) # Plot strategy vs. SPY cumulative returns. # plt.getOrCreateSubplot("returns").addDataSeries("SPY", cumret.CumulativeReturn(feed["SPY"].getPriceDataSeries())) plt.getOrCreateSubplot("returns").addDataSeries( "Strategy", returnsAnalyzer.getCumulativeReturns()) strat.run() print("Sharpe ratio: %.2f" % sharpeRatioAnalyzer.getSharpeRatio(0.05)) print("Returns: %.2f %%" % (returnsAnalyzer.getCumulativeReturns()[-1] * 100)) if plot: plt.plot()
from pyalgotrade.technical import rsi # 构建一个策略 class MyStrategy(strategy.BacktestingStrategy): def __init__(self, feed, instrument): super(MyStrategy, self).__init__(feed) self.__rsi = rsi.RSI(feed[instrument].getCloseDataSeries(), 14) self.__sma_rsi = ma.SMA(self.__rsi, 15) self.__sma = ma.SMA(feed[instrument].getCloseDataSeries(), 2) # self.info("__sma: {}, {}.".format(self.__sma, self.__sma[-1])) self.__instrument = instrument def onBars(self, bars): # 每一个数据都会抵达这里 bar = bars[self.__instrument] self.info("%s %s %s" % (bar.getClose(), self.__sma[-1], self.__sma_rsi[-1])) # 我们打印输出收盘价与两分钟均线值 if __name__ == '__main__': # 获得回测数据 feed = Feed(Frequency.SECOND) feed.loadBars('bitmex_XBTUSD', test_back=True) # feed.loadBarsFuture('okex_ltc', 'this_week_ticker', test_back=True) # feed.loadBarsFutureIndex('okex_ltc', test_back=True, types='index') # 把策略跑起来 myStrategy = MyStrategy(feed, "bitmex_XBTUSD") myStrategy.run()
return bar = bars[self.__instrument] # # If a position was not opened, check if we should enter a long position. if self.__position is None: # 如果手上没有头寸,那么 if bar.getPrice() > self.__sma[-1]: # 开多,如果现价大于移动均线,且当前没有头寸. self.__position = self.enterLong(self.__instrument, 100, True) # 当前有多头头寸,平掉多头头寸. elif bar.getPrice() < self.__sma[-1] and not self.__position.exitActive(): self.__position.exitMarket() if __name__ == '__main__': # 获得回测数据 feed = Feed(Frequency.SECOND) feed.loadBars('bitmex_LTCZ18', test_back=True) feed.loadBars('okex_LIGHTBTC', test_back=True) myStrategy = MyStrategy(feed) # , ('bitmex_LTCZ18', "okex_LIGHTBTC") retAnalyzer = returns.Returns() myStrategy.attachAnalyzer(retAnalyzer) sharpRatioAnalyzer = sharpe.SharpeRatio() myStrategy.attachAnalyzer(sharpRatioAnalyzer) myStrategy.run() myStrategy.info("Final portfolio value: $%.10f" % myStrategy.getResult()) print("Final portfolio value: $%.2f" % myStrategy.getResult()) print("Anual return: %.2f %%" % (retAnalyzer.getCumulativeReturns()[-1] * 100)) print("Average daily return: %.2f %%" % (stats.mean(retAnalyzer.getReturns()) * 100))
# -*- coding:utf-8 -*- from pyalgotrade import strategy from pyalgotrade.bar import Frequency from ccwt_client.ccwt_feed import Feed # 构建一个策略 class MyStrategy(strategy.BacktestingStrategy): def __init__(self, feed, instrument): super(MyStrategy, self).__init__(feed) self.__instrument = instrument def onBars(self, bars): # 每一个数据都会抵达这里,就像becktest中的next bar = bars[self.__instrument] self.info(bar.getClose()) # 我们打印输出收盘价 if __name__ == '__main__': # 获得回测数据 feed = Feed(Frequency.MINUTE) #feed.loadBars('okex_LIGHTUSDT') #feed.loadBars('binance_TRXBTC') feed.loadBars('bitmex_XBTUSD') # 把策略跑起来 #myStrategy = MyStrategy(feed, "okex_LIGHTUSDT") #myStrategy = MyStrategy(feed, "binance_TRXBTC") myStrategy = MyStrategy(feed, "bitmex_XBTUSD") myStrategy.run()
# bar.getTyoicalPrice = (bar.getHigh() + bar.getLow() + bar.getClose())/ 3.0 bar = bars[self.__instrument] # If a position was not opened, check if we should enter a long position. if self.__position is None: if bar.getPrice() > self.__sma[-1]: # 开多头. self.__position = self.enterLong(self.__instrument, 100, True) # 平掉多头头寸. elif bar.getPrice() < self.__sma[-1] and not self.__position.exitActive(): self.__position.exitMarket() if __name__ == '__main__': # 获得回测数据 feed = Feed(Frequency.MINUTE) #feed.loadBars('okex_LIGHTUSDT') feed.loadBars('bitmex_BCHZ18') feed.loadBars('binance_TRXBTC') # 4.设置指标和绘图 # 把策略跑起来 #myStrategy = MyStrategy(feed, "okex_LIGHTUSDT") # myStrategy = MyStrategy(feed, "bitmex_BCHZ18") myStrategy = MyStrategy(feed, "binance_TRXBTC") #returnsAnalyzer = returns.Returns() #myStrategy.attachAnalyzer(returnsAnalyzer) sharpe_ratio = sharpe.SharpeRatio() myStrategy.attachAnalyzer(sharpe_ratio)
from ccwt_client.ccwt_feed import Feed # 构建一个策略 class MyStrategy(strategy.BacktestingStrategy): def __init__(self, feed, instrument): super(MyStrategy, self).__init__(feed) self.__instrument = instrument def onBars(self, bars): # 每一个数据都会抵达这里,就像becktest中的next bar = bars[self.__instrument] self.info(bar.getClose()) # 我们打印输出收盘价 if __name__ == '__main__': # 获得回测数据 feed = Feed(Frequency.MINUTE) #feed.loadBars('okex_LIGHTUSDT') #feed.loadBars('binance_TRXBTC') # feed.loadBars('bitmex_XBTUSD', test_back=True) feed.loadBars('bitmex_XBTUSD', test_back=False, start_date='2018-12-10', end_date='2018-12-12') # 把策略跑起来 #myStrategy = MyStrategy(feed, "okex_LIGHTUSDT") #myStrategy = MyStrategy(feed, "binance_TRXBTC") myStrategy = MyStrategy(feed, "bitmex_XBTUSD") myStrategy.run()
from pyalgotrade import strategy from pyalgotrade.bar import Frequency from ccwt_client.ccwt_feed import Feed from pyalgotrade.technical import ma from pyalgotrade.technical import rsi # 构建一个策略 class MyStrategy(strategy.BacktestingStrategy): def __init__(self, feed, instrument): super(MyStrategy, self).__init__(feed) self.__rsi = rsi.RSI(feed[instrument].getCloseDataSeries(), 14) self.__sma_rsi = ma.SMA(self.__rsi, 15) self.__sma = ma.SMA(feed[instrument].getCloseDataSeries(), 2) self.__instrument = instrument def onBars(self, bars): # 每一个数据都会抵达这里 bar = bars[self.__instrument] self.info("%s %s %s" % (bar.getClose(), self.__sma[-1], self.__sma_rsi[-1])) # 我们打印输出收盘价与两分钟均线值 if __name__ == '__main__': # 获得回测数据 feed = Feed(Frequency.SECOND) feed.loadBars('bitmex_BCHZ18') # 把策略跑起来 myStrategy = MyStrategy(feed, "bitmex_BCHZ18") myStrategy.run()
def onBars(self, bars): # 每一个数据都会抵达这里, # SMA的计算存在窗口,所以前面的几个bar下是没有SMA的数据的. if self.__sma[-1] is None: return # bar.getTyoicalPrice = (bar.getHigh() + bar.getLow() + bar.getClose())/ 3.0 bar = bars[self.__instrument] # If a position was not opened, check if we should enter a long position. if self.__position is None: # 如果手上没有头寸,那么 if bar.getPrice() > self.__sma[-1]: # 开多,如果现价大于移动均线,且当前没有头寸. self.__position = self.enterLong(self.__instrument, 100, True) # 当前有多头头寸,平掉多头头寸. elif bar.getPrice( ) < self.__sma[-1] and not self.__position.exitActive(): self.__position.exitMarket() if __name__ == '__main__': # 获得回测数据 feed = Feed(Frequency.SECOND) feed.loadBars('okex_LIGHTUSDT', test_back=True) # feed.loadBars('bitmex_LTCZ18', test_back=True) # feed.loadBarsFuture('okex_ltc', 'quarter_ticker', test_back=True) # 把策略跑起来 myStrategy = MyStrategy(feed, "okex_LIGHTUSDT") # myStrategy = MyStrategy(feed, "okex_ltc") myStrategy.run() myStrategy.info("Final portfolio value: $%.10f" % myStrategy.getResult())