def testInvalidInstrument(self): instrument = "inexistent" # Don't skip errors. with self.assertRaisesRegexp(Exception, "HTTP Error 400: Bad Request"): with common.TmpDir() as tmpPath: bf = googlefinance.build_feed([instrument], 2100, 2101, storage=tmpPath, frequency=bar.Frequency.DAY) # Skip errors. with common.TmpDir() as tmpPath: bf = googlefinance.build_feed( [instrument], 2100, 2101, storage=tmpPath, frequency=bar.Frequency.DAY, skipErrors=True ) bf.loadAll() self.assertNotIn(instrument, bf)
def testBuildDailyFeed(self): with common.TmpDir() as tmpPath: instrument = "orcl" bf = googlefinance.build_feed([instrument], 2010, 2010, storage=tmpPath) bf.loadAll() self.assertEqual(bf[instrument][-1].getOpen(), 31.22) self.assertEqual(bf[instrument][-1].getClose(), 31.30)
def main(plot): import tusharefinance instrument = "600848" feed = tusharefinance.build_feed([instrument], 2012, 2016, ".") return instrument = "000300" feed = googlefinance.build_feed([instrument], 2012, 2016, ".") 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 = "DIA" entrySMA = 200 exitSMA = 5 rsiPeriod = 2 overBoughtThreshold = 90 overSoldThreshold = 10 # Download the bars. feed = googlefinance.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 main(plot): instrument = "yhoo" bBandsPeriod = 40 # Download the bars. feed = googlefinance.build_feed([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 __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 setUpClass(cls): rowFilter = lambda row: row["Close"] == "-" or row["Open"] == "-" or row["High"] == "-" or row["Low"] == "-" or \ row["Volume"] == "-" instruments = ["PETR4", "PETR3"] googleFeed = googlefinance.build_feed(instruments, 2015, 2015, storage="./googlefinance", skipErrors=True, rowFilter=rowFilter) cls.dynamicFeed = DynamicFeed("./sqlitedb", instruments, maxLen=10) cls.dynamicFeed.getDatabase().addBarsFromFeed(googleFeed)
def testBuildDailyFeed(self): with common.TmpDir() as tmpPath: instrument = "orcl" bf = googlefinance.build_feed([instrument], 2010, 2010, storage=tmpPath) bf.loadAll() self.assertEqual(bf[instrument][-1].getOpen(), 31.22) self.assertEqual(bf[instrument][-1].getClose(), 31.30)
def setUpClass(cls): feed = DynamicFeed(cls.db, cls.codes) days = feed.getAllDays() if len(days) == 247: return rowFilter = lambda row: row["Close"] == "-" or row["Open"] == "-" or row["High"] == "-" or row["Low"] == "-" or \ row["Volume"] == "-" googleFeed = googlefinance.build_feed(cls.codes, 2014, 2014, storage=cls.csvStorage, skipErrors=True, rowFilter=rowFilter) feed = DynamicFeed(cls.db, cls.codes, maxLen=10) feed.getDatabase().addBarsFromFeed(googleFeed)
def main(plot): instruments = ["AA", "AES", "AIG"] feed = googlefinance.build_feed(instruments, 2008, 2009, ".") predicate = BuyOnGap(feed) eventProfiler = eventprofiler.Profiler(predicate, 5, 5) eventProfiler.run(feed, True) results = eventProfiler.getResults() print "%d events found" % (results.getEventCount()) if plot: eventprofiler.plot(results)
def testInvalidInstrument(self): instrument = "inexistent" # Don't skip errors. with self.assertRaisesRegexp(Exception, "HTTP Error 400: Bad Request"): with common.TmpDir() as tmpPath: bf = googlefinance.build_feed([instrument], 2100, 2101, storage=tmpPath, frequency=bar.Frequency.DAY) # Skip errors. with common.TmpDir() as tmpPath: bf = googlefinance.build_feed([instrument], 2100, 2101, storage=tmpPath, frequency=bar.Frequency.DAY, skipErrors=True) bf.loadAll() self.assertNotIn(instrument, bf)
def main(plot): instruments = ["aapl", "orcl", "msft", "fb", "googl"] name = { "aapl": "apple", "orcle": "oracle", "msft": "microsoft", "fb": "facebook", "googl": "google" } vwapWindowSize = 5 threshold = 0.01 profits = {} # Download the bars. for instrument in instruments: feed = googlefinance.build_feed([instrument], 2016, 2017, ".") strat = basicMomentum(feed, instrument, vwapWindowSize, threshold) sharpeRatioAnalyzer = sharpe.SharpeRatio() strat.attachAnalyzer(sharpeRatioAnalyzer) # tells us the sharpe ratio of the stock during the time if plot: plt = plotter.StrategyPlotter(strat, True, False, True) plt.getInstrumentSubplot(instrument).addDataSeries( "vwap", strat.getVWAP()) strat.run() profits[instrument] = (strat.getBroker().getEquity()) print "Sharpe ratio: %.2f" % sharpeRatioAnalyzer.getSharpeRatio(0.05) if plot: plt.plot() profit_array = [] name_array = [] for item in profits: profits[item] -= 1000000 profit_array.append(profits[item]) name_array.append(item) print(profits) import matplotlib.pyplot as plt n = len(instruments) profit_std = (9851, 15829, 4111, 20111, 40213) index = np.arange(n) width = 0.35 plt.figure() plt.bar(index, profit_array, align='center', color='b', yerr=profit_std) plt.ylabel('Profit') plt.title('Profit over 1 year using basic Momentum Trading') plt.xlabel('Company') plt.xticks(index, name_array) plt.show()
def setUpClass(cls): rowFilter = ( lambda row: row["Close"] == "-" or row["Open"] == "-" or row["High"] == "-" or row["Low"] == "-" or row["Volume"] == "-" ) instruments = ["PETR4", "PETR3"] googleFeed = googlefinance.build_feed( instruments, 2015, 2015, storage="./googlefinance", skipErrors=True, rowFilter=rowFilter ) cls.dynamicFeed = DynamicFeed("./sqlitedb", instruments, maxLen=10) cls.dynamicFeed.getDatabase().addBarsFromFeed(googleFeed)
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 = googlefinance.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 main(plot): instrument = "aapl" smaPeriod = 163 # Download the bars. feed = googlefinance.build_feed([instrument], 2011, 2012, ".") strat = sma_crossover.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 "Sharpe ratio: %.2f" % sharpeRatioAnalyzer.getSharpeRatio(0.05) if plot: plt.plot()
def main(plot): instrument = "aapl" vwapWindowSize = 5 threshold = 0.01 # Download the bars. feed = googlefinance.build_feed([instrument], 2011, 2012, ".") 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): instruments = ["gld", "gdx"] windowSize = 50 # Download the bars. feed = googlefinance.build_feed(instruments, 2006, 2012, ".") 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 __init__(self, instruments, initialCash, year, debugMode=True, csvStorage="./googlefinance"): 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, year, year, storage=csvStorage, skipErrors=True, rowFilter=rowFilter) # 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) # 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), 3): p = plotter.StrategyPlotter(self.__strategy, plotAllInstruments=False, plotPortfolio=False) p.getInstrumentSubplot(instruments[i]) self.__plotters.append(p) if i < len(instruments) - 1: p.getInstrumentSubplot(instruments[i + 1]) if i < len(instruments) - 2: p.getInstrumentSubplot(instruments[i + 2])
def updateStockData(self, fromDate=None, toDate=None): if fromDate is None: lastDate = self.getLastStockDate() fromDate = dt.unlocalize( lastDate if lastDate is not None else self.__currentDate - timedelta(days=365 * 2)) if toDate is None: toDate = dt.unlocalize(self.__currentDate) rowFilter = lambda row: row["Close"] == "-" or row["Open"] == "-" or row["High"] == "-" or row["Low"] == "-" or \ row["Volume"] == "-" or googlefeed.parse_date(row["Date"]) < fromDate or googlefeed.parse_date(row["Date"]) > toDate [ os.remove(self.__googleFinanceDir + '/' + f) for f in glob.glob1(self.__googleFinanceDir, '*' + str(toDate.year) + '*') ] googleFeed = googlefinance.build_feed(self.__codes, fromDate.year, toDate.year, storage=self.__googleFinanceDir, skipErrors=False, rowFilter=rowFilter) self.__feed.getDatabase().addBarsFromFeed(googleFeed)