def __init__(self, instruments, initialCash, fromYear, toYear, debugMode=True, csvStorage="./googlefinance", filterInvalidRows=True): self.__logger = logger.getLogger(GoogleFinanceBacktest.LOGGER_NAME) self.__finalPortfolioValue = 0 # Create Feed self.__feed = googlefeed.Feed() rowFilter = lambda row: row["Close"] == "-" or row["Open"] == "-" or row["High"] == "-" or row["Low"] == "-" or \ row["Volume"] == "-" self.__feed = googlefinance.build_feed( instruments, fromYear, toYear, storage=csvStorage, skipErrors=True, rowFilter=rowFilter if filterInvalidRows else None) # Create Broker comissionModel = backtesting.FixedPerTrade(10) self.__broker = backtesting.Broker(initialCash, self.__feed, commission=comissionModel) self.__strategy = TradingSystem(self.__feed, self.__broker, debugMode=debugMode) # Create Analyzers returnsAnalyzer = returns.Returns() self.__strategy.attachAnalyzer(returnsAnalyzer) dailyResultsAnalyzer = DailyTradingResults() self.__strategy.attachAnalyzer(dailyResultsAnalyzer) self.__tradesAnalyzer = Trades() self.__strategy.attachAnalyzer(self.__tradesAnalyzer) # Create plotters self.__plotters = [] self.__plotters.append( plotter.StrategyPlotter(self.__strategy, plotAllInstruments=False, plotPortfolio=True, plotBuySell=False)) self.__plotters[0].getOrCreateSubplot("returns").addDataSeries( "Simple returns", returnsAnalyzer.getReturns()) self.__plotters[0].getOrCreateSubplot("dailyresult").addDataSeries( "Daily Results", dailyResultsAnalyzer.getTradeResults()) for i in range(0, len(instruments)): p = plotter.StrategyPlotter(self.__strategy, plotAllInstruments=False, plotPortfolio=False) p.getInstrumentSubplot(instruments[i]) self.__plotters.append(p)
def main(plot): instrument = "yhoo" bBandsPeriod = 40 # Download the bars. #feed = yahoofinance.build_feed([instrument], 2011, 2012, ".") feed = yahoofeed.Feed() feed.addBarsFromCSV(instrument, "dat\\yhoo-201x.csv") strat = BBands(feed, instrument, bBandsPeriod) sharpeRatioAnalyzer = sharpe.SharpeRatio() strat.attachAnalyzer(sharpeRatioAnalyzer) if plot: mpl.style.use('seaborn-whitegrid'); plt = plotter.StrategyPlotter(strat, True, True, True) plt.getInstrumentSubplot(instrument).addDataSeries("upper", strat.getBollingerBands().getUpperBand()) plt.getInstrumentSubplot(instrument).addDataSeries("middle", strat.getBollingerBands().getMiddleBand()) plt.getInstrumentSubplot(instrument).addDataSeries("lower", strat.getBollingerBands().getLowerBand()) strat.run() print( "Sharpe ratio: %.2f" % sharpeRatioAnalyzer.getSharpeRatio(0.05)) if plot: plt.plot()
def main(plot): initialCash = 10000 instrumentsByClass = { "US Stocks": ["VTI"], "Foreign Stocks": ["VEU"], "US 10 Year Government Bonds": ["IEF"], "Real Estate": ["VNQ"], "Commodities": ["DBC"], } # Download the bars. instruments = ["SPY"] for assetClass in instrumentsByClass: instruments.extend(instrumentsByClass[assetClass]) feed = yahoofinance.build_feed(instruments, 2007, 2013, "data", skipErrors=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()
def run_strategy(smaPeriod): # Load the bar feed from the CSV file feed = quandlfeed.Feed() feed.addBarsFromCSV( "orcl", "D:/Develop/project/python/PycharmProjects/python3/pyalgotrade/samples/data/WIKI-ORCL-2011-quandl.csv" ) # Evaluate the strategy with the feed's bars myStratege = MyStrategy(feed, "orcl", smaPeriod) # Attach a returns analyzer to to strategy returnsAnalyzer = returns.Returns() myStratege.attachAnalyzer(returnsAnalyzer) # Attach the plotter to the strategy plt = plotter.StrategyPlotter(myStratege) # Include the SMA in the instrument's subplot to get it displayed along with the closing prices plt.getInstrumentSubplot("orcl").addDataSeries("SMA", myStratege.getSMA()) # Plot the simple returns on each bar #plt.getOrCreateSubplot("returns").addDataSeries("Simple Returns", returnsAnalyzer.getReturns()) myStratege.run() myStratege.info("Final portfolio value: $%.2f" % myStratege.getBroker().getEquity()) # Plot the strategy plt.plot()
def main(plot): instrument = "btc" vwapWindowSize = 20 # Download the bars. # feed = yahoofinance.build_feed([instrument], 2011, 2012, ".") feed = coinfeed.Feed() # startDate = datetime.datetime.strptime("2014-04-06 11:47:42", "%Y-%m-%d %H:%M:%S") # endDate = datetime.datetime.strptime("2014-04-10 11:47:42", "%Y-%m-%d %H:%M:%S") # feed.setDateRange(startDate, endDate) feed.addBarsFromCSV(instrument, "data/ticker.csv") myStrategy = MyStrategy(feed, instrument, vwapWindowSize) if plot: # plt = plotter.StrategyPlotter(myStrategy, True, False, True) plt = plotter.StrategyPlotter(myStrategy) plt.getInstrumentSubplot(instrument).addDataSeries("vwap", myStrategy.getVWAPDS()) myStrategy.run() print "Result: %.2f" % myStrategy.getResult() if plot: plt.plot()
def main(plot): instrument = "bitmex_LTCZ18" initialCash = 1000 vwapWindowSize = 100 buyThreshold = 0.02 sellThreshold = 0.01 # barFeed = csvfeed.GenericBarFeed(bar.Frequency.MINUTE*30) # barFeed.addBarsFromCSV(instrument, "30min-bitstampUSD.csv") feed = Feed(Frequency.SECOND) feed.loadBars('bitmex_LTCZ18', test_back=True) brk = broker.BacktestingBroker(initialCash, feed) strat = VWAPMomentum(feed, brk, instrument, vwapWindowSize, buyThreshold, sellThreshold) if plot: plt = plotter.StrategyPlotter(strat) plt.getInstrumentSubplot(instrument).addDataSeries( "VWAP", strat.getVWAP()) strat.run() if plot: plt.plot()
def turtle_test(dataString='pyalg'): """ :param dataString: :return: """ feed = yahoofeed.Feed() feed.addBarsFromCSV( "orcl", "../../api/stock/csv/orcl-2000.csv") #注意查看该csv的格式,Open为大写 myStrategy = pdr.turtle(feed, "orcl", 20, 10) # Attach a returns analyzers to the trategy. returnsAnalyzer = returns.Returns() myStrategy.attachAnalyzer(returnsAnalyzer) # Attach the plotter to the strategy. plt = plotter.StrategyPlotter(myStrategy) # Plot the simple returns on each bar. plt.getOrCreateSubplot("returns").addDataSeries( "Simple returns", returnsAnalyzer.getReturns()) if dataString == 'pyalg_util': ds = pyalg_utils.dataSet(myStrategy) # 抽取交易数据集语句,若使用系统自带画图功能则不需要该项 myStrategy.run() myStrategy.info("Final portfolio value: $%.2f" % myStrategy.getResult()) if dataString == 'pyalg_util': rs = ds.getDefault() # 获取默认的交易信息,dic格式 plot(rs["cumulativeReturns"][:, 0], rs["cumulativeReturns"][:, 1]) # 简单作图示例 plt.plot()
def main(plot): instrument = "FG0" sma_Period = 40 # Download the bars. # feed = yahoofinance.build_feed([instrument], 2011, 2012, ".") csv_path = os.path.abspath( '../histdata/commodity') + '/' + instrument + '.csv' feed = sf.Feed() feed.addBarsFromCSV(instrument, csv_path) # feed = csvfeed.Feed('Date', ) strat = SMACrossOver(feed, instrument, sma_Period) sharpeRatioAnalyzer = sharpe.SharpeRatio() strat.attachAnalyzer(sharpeRatioAnalyzer) if plot: plt = plotter.StrategyPlotter(strat, True, True, True) plt.getInstrumentSubplot(instrument).addDataSeries( "sma", strat.getSMA()) # plt.getInstrumentSubplot(instrument).addDataSeries("middle", strat.getBollingerBands().getMiddleBand()) # plt.getInstrumentSubplot(instrument).addDataSeries("lower", strat.getBollingerBands().getLowerBand()) strat.run() print "Sharpe ratio: %.2f" % sharpeRatioAnalyzer.getSharpeRatio(0.05) if plot: plt.plot() pass
def __init__(self, feed, instrument): super(SimpleBacktestStrategy, self).__init__(feed) self.initial_capital = self.getResult() self.positions = {} for symbol in instrument: self.positions[symbol] = {} retAnalyzer = returns.Returns() self.attachAnalyzerEx(retAnalyzer, 'retAnalyzer') sharpeRatioAnalyzer = sharpe.SharpeRatio() self.attachAnalyzerEx(sharpeRatioAnalyzer, 'sharpeRatioAnalyzer') drawDownAnalyzer = drawdown.DrawDown() self.attachAnalyzerEx(drawDownAnalyzer, 'drawDownAnalyzer') tradesAnalyzer = trades.Trades() self.attachAnalyzerEx(tradesAnalyzer, 'tradesAnalyzer') self.plt = plotter.StrategyPlotter(self) self.plt.getOrCreateSubplot("returns").addDataSeries( "Net return", retAnalyzer.getReturns()) self.plt.getOrCreateSubplot("returns").addDataSeries( "Cum. return", retAnalyzer.getCumulativeReturns()) self.strategy_id = 'backtest' if not os.path.exists(self.strategy_id + '.csv'): with open(self.strategy_id + '.csv', 'w') as f: f.write('Date,Type,Signal,Symbol,Price,Shares,PnL,Cash\n')
def __init__(self, feed, brk, instrument): super(LiveStrategy, self).__init__(feed, brk) brk.addBitmexFeed(feed) feed.getNewValuesEvent().subscribe(self.__onBarsImpl) self.initial_capital = self.getResult() brk.setStrategy(self) self.positions = {} for symbol in instrument: self.positions[symbol] = brk.get_synced_position(self, symbol) retAnalyzer = returns.Returns() self.attachAnalyzerEx(retAnalyzer, 'retAnalyzer') sharpeRatioAnalyzer = sharpe.SharpeRatio() self.attachAnalyzerEx(sharpeRatioAnalyzer, 'sharpeRatioAnalyzer') drawDownAnalyzer = drawdown.DrawDown() self.attachAnalyzerEx(drawDownAnalyzer, 'drawDownAnalyzer') tradesAnalyzer = trades.Trades() self.attachAnalyzerEx(tradesAnalyzer, 'tradesAnalyzer') self.plt = plotter.StrategyPlotter(self) self.plt.getOrCreateSubplot("returns").addDataSeries( "Net return", retAnalyzer.getReturns()) self.plt.getOrCreateSubplot("returns").addDataSeries( "Cum. return", retAnalyzer.getCumulativeReturns()) self.strategy_id = brk.getStrategyId() if not os.path.exists(self.strategy_id + '.csv'): with open(self.strategy_id + '.csv', 'w') as f: f.write('Date,Type,Signal,Symbol,Price,Shares,PnL,Cash\n') if not os.path.exists(self.strategy_id + '_orders.csv'): with open(self.strategy_id + '_orders.csv', 'w') as f: f.write( 'Date,OrderDate,OrderId,Type,Signal,Symbol,Price,Size,Filled,Timedelta,StopHit\n' )
def main(plot): instrument = "000300.ss" feed = yahoofinance.build_feed([instrument], 2013, 2015, ".") period = 100 strat = HurstBasedStrategy(feed, instrument, period) sharpeRatioAnalyzer = sharpe.SharpeRatio() strat.attachAnalyzer(sharpeRatioAnalyzer) # Attach a returns analyzers to the strategy. returnsAnalyzer = returns.Returns() strat.attachAnalyzer(returnsAnalyzer) if plot: plt = plotter.StrategyPlotter(strat, True, False, True) plt.getOrCreateSubplot("hurst").addDataSeries("Hurst", strat.getHurst()) plt.getOrCreateSubplot("hurst").addLine("random", 0.5) # Plot the simple returns on each bar. # plt.getOrCreateSubplot("returns").addDataSeries("Simple returns", returnsAnalyzer.getReturns()) strat.run() strat.info("Final portfolio value: $%.2f" % strat.getResult()) # print "Sharpe ratio: %.2f" % sharpeRatioAnalyzer.getSharpeRatio(0.05) if plot: plt.plot()
def main(plot): instrument = "yhoo" bBandsPeriod = 40 # Download the bars. feed = quandl.build_feed("WIKI", [instrument], 2011, 2012, ".") strat = BBands(feed, instrument, bBandsPeriod) sharpeRatioAnalyzer = sharpe.SharpeRatio() strat.attachAnalyzer(sharpeRatioAnalyzer) if plot: plt = plotter.StrategyPlotter(strat, True, True, True) plt.getInstrumentSubplot(instrument).addDataSeries( "upper", strat.getBollingerBands().getUpperBand()) plt.getInstrumentSubplot(instrument).addDataSeries( "middle", strat.getBollingerBands().getMiddleBand()) plt.getInstrumentSubplot(instrument).addDataSeries( "lower", strat.getBollingerBands().getLowerBand()) strat.run() print("Sharpe ratio: %.2f" % sharpeRatioAnalyzer.getSharpeRatio(0.05)) if plot: plt.plot()
def analyzer(self,strat,instrument): SPlotter = plotter.StrategyPlotter(strat, True, True, True) #mid (self, strat, plotAllInstruments=True, plotBuySell=True, plotPortfolio=True) #SPlotter.getInstrumentSubplot(instrument).addDataSeries("upper", strat.getBollingerBands().getUpperBand()) #SPlotter.getInstrumentSubplot(instrument).addDataSeries("middle", strat.getBollingerBands().getMiddleBand()) SPlotter.getInstrumentSubplot(instrument).addDataSeries("short", strat.getSMA()) SPlotter.getInstrumentSubplot(instrument).addDataSeries("long", strat.getLMA()) #SPlotter.getOrCreateSubplot("Returns").addDataSeries("Simple returns", self.returnsAnalyzer.getReturns()) #SPlotter.getOrCreateSubplot("SharpeRatio").addDataSeries("Sharpe Ratio", self.sharpeRatioAnalyzer.getReturns()) #SPlotter.getOrCreateSubplot("SharpeRatio").addDataSeries("Sharpe Ratio", self.tradesAnalyzer.getCommissionsForAllTrades()) def addCallBack(): # mid 使用默认绘图类绘制自定义数据,此处是LineMarker def midBars(bars): midOpen = bars[self.instrument].getOpen() midClose = bars[self.instrument].getClose() print midOpen return midClose SPlotter.getOrCreateSubplot("orders").addCallback("mid's callback",midBars,plotter.LineMarker) def addDataSeries(): feedDataSeries = self.feed.getDataSeries() feedDataSerie = feedDataSeries.getCloseDataSeries() SPlotter.getOrCreateSubplot("orders02").addDataSeries("mid's dataSeries",feedDataSerie,plotter.LineMarker) #addCallBack() #addDataSeries() position = strat.getPositionVolume() SPlotter.getOrCreateSubplot("position").addDataSeries("position", position) return SPlotter
def run_strategy(index, startYear, endYear, smaShort, smaLong): # Load the yahoo feed from the CSV file feed = yahoofeed.Feed() feed.sanitizeBars(True) for year in range(startYear, endYear): feed.addBarsFromCSV(index, "./data/" + index + "-" + str(year) + ".csv") # Evaluate the strategy with the feed. myStrategy = MyStrategy(feed, index, smaShort, smaLong) # Attach analyzers to the strategy. sharpeAnalyzer = sharpe.SharpeRatio() myStrategy.attachAnalyzer(sharpeAnalyzer) # Attach a plotter to the strategy plt = plotter.StrategyPlotter(myStrategy) # Run the strategy myStrategy.run() myStrategy.info("Final portfolio value: $%.2f" % myStrategy.getBroker().getEquity()) myStrategy.info("Annualized Sharpe Ratio: " + str(sharpeAnalyzer.getSharpeRatio(0, True))) # Plot the strategy. plt.plot()
def main(plot): get_ticker_list() smaPeriod = 163 for instrument in ticker_list[:10]: # Download the bars feed = csvfeed.GenericBarFeed(frequency=300) feed.addBarsFromCSV( instrument, r"C:/Users/Rohit/Python_source_code/nse 500 stock data/Date Time Data/" + instrument + ".csv") strat = SMACrossOver(feed, instrument, smaPeriod) sharpeRatioAnalyzer = sharpe.SharpeRatio() strat.attachAnalyzer(sharpeRatioAnalyzer) if plot: plt = plotter.StrategyPlotter(strat, True, False, True) plt.getInstrumentSubplot(instrument).addDataSeries( "sma", strat.getSMA()) strat.run() print(instrument) print("Sharpe ratio: %.2f" % sharpeRatioAnalyzer.getSharpeRatio(0.05)) if plot: plt.plot()
def main(plot): instrument = "n225" CalibratedBollingerBandsPeriod = 40 feed = yahoofeed.Feed() feed.addBarsFromCSV(instrument, r".\Data\n225.csv") strat = BollingerBandsStrategy(feed, instrument, CalibratedBollingerBandsPeriod) sharpeRatioAnalyzer = sharpe.SharpeRatio() strat.attachAnalyzer(sharpeRatioAnalyzer) if plot: plt = plotter.StrategyPlotter(strat, True, True, True) plt.getInstrumentSubplot(instrument).addDataSeries( "upper", strat.getBollingerBands().getUpperBand()) plt.getInstrumentSubplot(instrument).addDataSeries( "middle", strat.getBollingerBands().getMiddleBand()) plt.getInstrumentSubplot(instrument).addDataSeries( "lower", strat.getBollingerBands().getLowerBand()) strat.run() strat.info("Final portfolio value: $%.2f" % strat.getResult()) print("Sharpe ratio: %.2f" % sharpeRatioAnalyzer.getSharpeRatio(0.05)) if plot: plt.plot()
def main(): instrument = "yhoo" bBandsPeriod = 40 # Download the bars. # feed = yahoofinance.build_feed([instrument], 2011, 2012, ".") feed = yahoofeed.Feed() feed.addBarsFromCSV(instrument, "dat\\yhoo-201x.csv") strat = BBands(feed, instrument, bBandsPeriod) sharpeRatioAnalyzer = sharpe.SharpeRatio() strat.attachAnalyzer(sharpeRatioAnalyzer) retAnalyzer = returns.Returns() strat.attachAnalyzer(retAnalyzer) drawDownAnalyzer = drawdown.DrawDown() strat.attachAnalyzer(drawDownAnalyzer) tradesAnalyzer = trades.Trades() strat.attachAnalyzer(tradesAnalyzer) # ------ mpl.style.use('seaborn-whitegrid'); plt = plotter.StrategyPlotter(strat, True, True, True) plt.getInstrumentSubplot(instrument).addDataSeries("upper", strat.getBollingerBands().getUpperBand()) plt.getInstrumentSubplot(instrument).addDataSeries("middle", strat.getBollingerBands().getMiddleBand()) plt.getInstrumentSubplot(instrument).addDataSeries("lower", strat.getBollingerBands().getLowerBand()) strat.run() plt.plot() # ============================== print("最终资产价值 Final portfolio value: $%.2f" % strat.getResult()) print("累计回报率 Cumulative returns: %.2f %%" % (retAnalyzer.getCumulativeReturns()[-1] * 100)) print("夏普比率 Sharpe ratio: %.2f" % (sharpeRatioAnalyzer.getSharpeRatio(0.05))) print("最大回撤率 Max. drawdown: %.2f %%" % (drawDownAnalyzer.getMaxDrawDown() * 100)) print("最长回撤时间 Longest drawdown duration: %s" % (drawDownAnalyzer.getLongestDrawDownDuration()))
def turtle_test(loadtype='pgs', dataString='pyalg'): """ :param dataString: :return: """ # 从postgres 中加载 if loadtype == 'pgs': from api.stock.histmd import to_postgres_md as tpd dat = tpd.get_h_data('600848') else: from api.stock.histmd.to_mongodb_md import k_data_dao as tmd w = tmd.KdataDbCache() dat = w.get_k_data(index=False,start='2015-02-05', end='2015-02-19',code='300426') feed = dataFramefeed.Feed() feed.addBarsFromDataFrame("orcl", dat) myStrategy = pdr.turtle(feed, "orcl", 20, 10) # Attach a returns analyzers to the strategy. returnsAnalyzer = returns.Returns() myStrategy.attachAnalyzer(returnsAnalyzer) # Attach the plotter to the strategy. plt = plotter.StrategyPlotter(myStrategy) # Plot the simple returns on each bar. plt.getOrCreateSubplot("returns").addDataSeries("Simple returns", returnsAnalyzer.getReturns()) if dataString == 'pyalg_util': ds = pyalg_utils.dataSet(myStrategy) # 抽取交易数据集语句,若使用系统自带画图功能则不需要该项 myStrategy.run() myStrategy.info("Final portfolio value: $%.2f" % myStrategy.getResult()) if dataString == 'pyalg_util': rs = ds.getDefault() # 获取默认的交易信息,dic格式 plot(rs["cumulativeReturns"][:, 0], rs["cumulativeReturns"][:, 1]) # 简单作图示例 plt.plot()
def main(plot): symbol = "yhoo" priceCurrency = "USD" instrument = "%s/%s" % (symbol, priceCurrency) bBandsPeriod = 40 # Download the bars. feed = quandl.build_feed("WIKI", [symbol], priceCurrency, 2011, 2012, ".") broker = backtesting.Broker({priceCurrency: 1000000}, feed) strat = BBands(feed, broker, instrument, bBandsPeriod) sharpeRatioAnalyzer = sharpe.SharpeRatio(priceCurrency) strat.attachAnalyzer(sharpeRatioAnalyzer) if plot: from pyalgotrade import plotter plt = plotter.StrategyPlotter(strat, True, True, True) plt.getInstrumentSubplot(instrument).addDataSeries("upper", strat.getBollingerBands().getUpperBand()) plt.getInstrumentSubplot(instrument).addDataSeries("middle", strat.getBollingerBands().getMiddleBand()) plt.getInstrumentSubplot(instrument).addDataSeries("lower", strat.getBollingerBands().getLowerBand()) strat.run() print("Sharpe ratio: %.2f" % sharpeRatioAnalyzer.getSharpeRatio(0.05)) if plot: plt.plot()
def main(plot): """ """ # 初始化常量 instrument = 'BINA--BTC--USDT' # 数据 # 1、从mysql导出csv数据 # 2、指定数据频率 # 3、读入csv给feed sql_to_csv(True) feed = GenericBarFeed(Frequency.DAY, None, None) feed.addBarsFromCSV(instrument, instrument + '.csv') # 评价器 # 1、初始化一个sharpratio评价器 sharpeRatioAnalyzer = sharpe.SharpeRatio() # 注入 # 1、实例化一个策略 # 2、注入评价器 strat = close_above_sma(feed, instrument) strat.attachAnalyzer(sharpeRatioAnalyzer) if plot: plt = plotter.StrategyPlotter(strat, True, True, True) plt.getInstrumentSubplot(instrument).addDataSeries( "sma", strat.getSma()) strat.run() plt.plot() print("Sharpe ratio: %.2f" % sharpeRatioAnalyzer.getSharpeRatio(0.05))
def main(plot): symbol = sql_to_csv(True) instrument = symbol entrySMA = 200 exitSMA = 5 rsiPeriod = 2 overBoughtThreshold = 90 overSoldThreshold = 10 # Download the bars. feed = GenericBarFeed(Frequency.DAY, None, None) feed.addBarsFromCSV(symbol, symbol + '.csv') strat = RSI2(feed, instrument, entrySMA, exitSMA, rsiPeriod, overBoughtThreshold, overSoldThreshold) sharpeRatioAnalyzer = sharpe.SharpeRatio() strat.attachAnalyzer(sharpeRatioAnalyzer) if plot: plt = plotter.StrategyPlotter(strat, True, False, True) plt.getInstrumentSubplot(instrument).addDataSeries( "Entry SMA", strat.getEntrySMA()) plt.getInstrumentSubplot(instrument).addDataSeries( "Exit SMA", strat.getExitSMA()) plt.getOrCreateSubplot("rsi").addDataSeries("RSI", strat.getRSI()) plt.getOrCreateSubplot("rsi").addLine( "Overbought", overBoughtThreshold) plt.getOrCreateSubplot("rsi").addLine("Oversold", overSoldThreshold) strat.run() print("Sharpe ratio: %.2f" % sharpeRatioAnalyzer.getSharpeRatio(0.05)) if plot: plt.plot()
def main(plot): symbol = "GORO" priceCurrency = "USD" instrument = "%s/%s" % (symbol, priceCurrency) initialBalance = {priceCurrency: 1000000} # Download GORO bars using WIKI source code. feed = quandl.build_feed("WIKI", [symbol], "USD", 2006, 2012, ".") # Load Quandl CSV downloaded from http://www.quandl.com/OFDP-Open-Financial-Data-Project/GOLD_2-LBMA-Gold-Price-London-Fixings-P-M quandlFeed = csvfeed.Feed("Date", "%Y-%m-%d") quandlFeed.setDateRange(datetime.datetime(2006, 1, 1), datetime.datetime(2012, 12, 31)) quandlFeed.addValuesFromCSV("quandl_gold_2.csv") myStrategy = MyStrategy(feed, quandlFeed, instrument, initialBalance) if plot: from pyalgotrade import plotter plt = plotter.StrategyPlotter(myStrategy, True, False, False) plt.getOrCreateSubplot("quandl").addDataSeries("USD", quandlFeed["USD"]) plt.getOrCreateSubplot("quandl").addDataSeries("EUR", quandlFeed["EUR"]) plt.getOrCreateSubplot("quandl").addDataSeries("GBP", quandlFeed["GBP"]) myStrategy.run() if plot: plt.plot()
def main(plot): instrument = "aapl" vwapWindowSize = 5 threshold = 0.01 # Download the bars. # feed = yahoofinance.build_feed([instrument], 2011, 2012, ".") feed = yahoofeed.Feed() feed.addBarsFromCSV(instrument, "dat\\aapl-201x.csv") strat = VWAPMomentum(feed, instrument, vwapWindowSize, threshold) sharpeRatioAnalyzer = sharpe.SharpeRatio() strat.attachAnalyzer(sharpeRatioAnalyzer) if plot: plt = plotter.StrategyPlotter(strat, True, False, True) plt.getInstrumentSubplot(instrument).addDataSeries( "vwap", strat.getVWAP()) strat.run() print "Sharpe ratio: %.2f" % sharpeRatioAnalyzer.getSharpeRatio(0.05) if plot: plt.plot()
def main(plot): symbol = "AAPL" priceCurrency = "USD" instrument = "%s/%s" % (symbol, priceCurrency) initialBalance = {priceCurrency: 1000000} vwapWindowSize = 5 threshold = 0.01 # Download the bars. feed = quandl.build_feed("WIKI", [symbol], priceCurrency, 2011, 2012, ".") strat = VWAPMomentum(feed, instrument, initialBalance, vwapWindowSize, threshold) sharpeRatioAnalyzer = sharpe.SharpeRatio(priceCurrency) strat.attachAnalyzer(sharpeRatioAnalyzer) if plot: from pyalgotrade import plotter plt = plotter.StrategyPlotter(strat, True, False, True) plt.getInstrumentSubplot(instrument).addDataSeries( "vwap", strat.getVWAP()) strat.run() print("Sharpe ratio: %.2f" % sharpeRatioAnalyzer.getSharpeRatio(0.05)) if plot: plt.plot()
def ENE(type='old', code='600281'): dat = pd.read_csv("../../api/stock/csv/%sSH_5min.csv" % code, encoding='gbk') dat = dat.fillna(method='pad') dat['Adj Close'] = dat['Close'] dat = dat.rename(columns={'Open': 'open', 'High': 'high', 'Volume': 'volume', 'Close': 'close', 'Low': 'low'}) dat.index = dat['Date Time'] dat.index.name = 'date' # dat = dat.ix[17000:18000,:] feed = dataFramefeed.Feed(frequency=bar.Frequency.MINUTE) feed.addBarsFromDataFrame("orcl", dat) if type == 'macd': myStrategy = mdd.ENE_backtest(feed, 'orcl') elif type == 'old': myStrategy = mdd.ENE_backtest(feed, 'orcl') sharpeRatioAnalyzer = sharpe.SharpeRatio() myStrategy.attachAnalyzer(sharpeRatioAnalyzer) returnsAnalyzer = returns.Returns() myStrategy.attachAnalyzer(returnsAnalyzer) plt = plotter.StrategyPlotter(myStrategy, True, True, True) plt.getOrCreateSubplot("returns").addDataSeries("Simple returns", returnsAnalyzer.getReturns()) ds = pyalg_utils.dataSet(myStrategy) # 抽取交易数据集语句,若使用系统自带画图功能则不需要该项 myStrategy.run() plt.plot() print('最大回撤:\t%f\t 交易笔数:\t%d\t 盈利笔数:\t%d\n' % (ds.getMaxDrawDown(), ds.getCount(), ds.getProfitableCount())) print('累计收益:\t%f\t 夏普比率:\t%f\t' % (returnsAnalyzer.getCumulativeReturns()[-1], ds.getSharpeRatio()))
def main(plot): instruments = ["gld", "gdx"] windowSize = 50 # Load the bars. These files were manually downloaded from Yahoo Finance. feed = yahoofeed.Feed() for year in range(2006, 2012+1): for instrument in instruments: fileName = "%s-%d-yahoofinance.csv" % (instrument, year) print("Loading bars from %s" % fileName) feed.addBarsFromCSV(instrument, fileName) strat = StatArb(feed, instruments[0], instruments[1], windowSize) sharpeRatioAnalyzer = sharpe.SharpeRatio() strat.attachAnalyzer(sharpeRatioAnalyzer) if plot: plt = plotter.StrategyPlotter(strat, False, False, True) plt.getOrCreateSubplot("hedge").addDataSeries("Hedge Ratio", strat.getHedgeRatioDS()) plt.getOrCreateSubplot("spread").addDataSeries("Spread", strat.getSpreadDS()) strat.run() print("Sharpe ratio: %.2f" % sharpeRatioAnalyzer.getSharpeRatio(0.05)) if plot: plt.plot()
def main(plot): instrument = "002941" bBandsPeriod = 10 # Download the bars. feed = yahoofeed.Feed() feed.addBarsFromCSV("002941", "F:/shuju/002941-orcl.csv") strat = BBands(feed, instrument, bBandsPeriod) sharpeRatioAnalyzer = sharpe.SharpeRatio() strat.attachAnalyzer(sharpeRatioAnalyzer) if plot: plt = plotter.StrategyPlotter(strat, True, True, True) plt.getInstrumentSubplot(instrument).addDataSeries( "upper", strat.getBollingerBands().getUpperBand()) plt.getInstrumentSubplot(instrument).addDataSeries( "middle", strat.getBollingerBands().getMiddleBand()) plt.getInstrumentSubplot(instrument).addDataSeries( "lower", strat.getBollingerBands().getLowerBand()) strat.run() print("Sharpe ratio: %.2f" % sharpeRatioAnalyzer.getSharpeRatio(0.05)) if plot: plt.plot()
def main(plot): instrument = "yhoo" bBandsPeriod = 10 # Download the bars. # feed = yahoofinance.build_feed([instrument], 2011, 2012, ".") feed = coinfeed.Feed() startDate = datetime.datetime.strptime("2014-04-06 11:47:42", "%Y-%m-%d %H:%M:%S") endDate = datetime.datetime.strptime("2014-04-10 11:47:42", "%Y-%m-%d %H:%M:%S") # feed.setDateRange(startDate, endDate) feed.addBarsFromCSV("btc", "data/ticker.csv") myStrategy = MyStrategy(feed, "btc", bBandsPeriod) if plot: plt = plotter.StrategyPlotter(myStrategy, True, True, True) plt.getInstrumentSubplot(instrument).addDataSeries( "upper", myStrategy.getBollingerBands().getUpperBand()) # plt.getInstrumentSubplot(instrument).addDataSeries("middle", myStrategy.getBollingerBands().getMiddleBand()) plt.getInstrumentSubplot(instrument).addDataSeries( "lower", myStrategy.getBollingerBands().getLowerBand()) myStrategy.run() print "Result: %.2f" % myStrategy.getResult() if plot: plt.plot()
def main(plot): instrument = "DIA" entrySMA = 200 exitSMA = 5 rsiPeriod = 2 overBoughtThreshold = 90 overSoldThreshold = 10 # Download the bars. feed = yahoofinance.build_feed([instrument], 2009, 2012, ".") strat = rsi2.RSI2(feed, instrument, entrySMA, exitSMA, rsiPeriod, overBoughtThreshold, overSoldThreshold) sharpeRatioAnalyzer = sharpe.SharpeRatio() strat.attachAnalyzer(sharpeRatioAnalyzer) if plot: plt = plotter.StrategyPlotter(strat, True, False, True) plt.getInstrumentSubplot(instrument).addDataSeries( "Entry SMA", strat.getEntrySMA()) plt.getInstrumentSubplot(instrument).addDataSeries( "Exit SMA", strat.getExitSMA()) plt.getOrCreateSubplot("rsi").addDataSeries("RSI", strat.getRSI()) plt.getOrCreateSubplot("rsi").addLine("Overbought", overBoughtThreshold) plt.getOrCreateSubplot("rsi").addLine("Oversold", overSoldThreshold) strat.run() print "Sharpe ratio: %.2f" % sharpeRatioAnalyzer.getSharpeRatio(0.05) if plot: plt.plot()
def run_strategy(): # Load the yahoo feed from the CSV file feed = GenericBarFeed(Frequency.DAY, None, None) feed.addBarsFromCSV("orcl", "2000.csv") # commission broker_commission = broker.backtesting.TradePercentage(0.002) broker_brk = floatBroker(50000, feed, broker_commission) # broker_brk = broker.backtesting.Broker(50000, feed) # Evaluate the strategy with the feed. myStrategy = MyStrategy(feed, "orcl", broker_brk) returnsAnalyzer = returns.Returns() myStrategy.attachAnalyzer(returnsAnalyzer) # Attach the plotter to the strategy. plt = plotter.StrategyPlotter(myStrategy) # Include the SMA in the instrument's subplot to get it displayed along with the closing prices. plt.getInstrumentSubplot("orcl").addDataSeries("SMA60", myStrategy.getSMA(60)) plt.getInstrumentSubplot("orcl").addDataSeries("SMA10", myStrategy.getSMA(10)) plt.getInstrumentSubplot("orcl").addDataSeries("SMA30", myStrategy.getSMA(30)) # Plot the simple returns on each bar. plt.getOrCreateSubplot("returns").addDataSeries("Simple returns", returnsAnalyzer.getReturns()) myStrategy.run() print("Final portfolio value: $%.2f %.2f %.2f" %(myStrategy.getBroker().getEquity(), myStrategy.getBroker().getCash(), myStrategy.getBroker().getShares('orcl'))) # myStrategy.info("Final portfolio value: $%.2f" % myStrategy.getResult()) # Plot the strategy. plt.plot()