Exemple #1
0
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()
Exemple #2
0
    def __init__(
        self,
        algo: GQAlgo,
        symbols,
        start_datetime,
        end_datetime,
        data_freq=FREQ_DAY,
        initial_cash=10000,
    ):
        self.algo = algo
        self.symbols = symbols
        self.start_datetime = start_datetime
        self.end_datetime = end_datetime
        self.data_freq = data_freq
        self.datasource = algo.datasource
        self.initial_cash = initial_cash

        self.data = GQData()

        freq_map = {
            FREQ_DAY: Frequency.DAY,
            FREQ_MINUTE: Frequency.MINUTE,
        }
        self.datafeed = csvfeed.GenericBarFeed(freq_map[data_freq])
        self._load_datafeed()

        self.my_strategy = MyStrategy(self.datafeed, self.symbols, self.algo,
                                      self.initial_cash)
        self.returnsAnalyzer = returns.Returns()
        self.my_strategy.attachAnalyzer(self.returnsAnalyzer)
Exemple #3
0
    def feed(self, day=False):  # can also use other file if exist
        '''
        通过本地数据库文件读出csv,创建创建数据源对象
        遍历context的category给所有品种读入数据
        :param day 如果为真,使用日线数据。
        '''
        conn = sqlite3.connect('./future_data.db')
        Data = {}
        res = csvfeed.GenericBarFeed(Frequency.MINUTE, maxLen=2000000)

        if day:
            res.setDateTimeFormat('%Y-%m-%d')
        else:
            res.setDateTimeFormat('%Y-%m-%d %H:%M:%S')

        for category in self.context.categorys:
            file = pd.read_sql('SELECT * FROM [' +
                               self.context.categoryToFile[category] + '] ',
                               conn,
                               parse_dates=['Date Time'])
            # file = file.loc[file['Date Time'] > '2018', :].reset_index(drop=True)  # 测试
            if day:
                file = self._resample(file, 'D')
            file.to_csv('temp.csv', index=False)

            res.addBarsFromCSV(category, 'temp.csv')
            Data[category] = file

        os.remove('temp.csv')
        conn.close()
        return Data, res
Exemple #4
0
    def testResampleMtGoxHour(self):
        # Resample.
        feed = mtgoxfeed.CSVTradeFeed()
        feed.addBarsFromCSV(
            common.get_data_file_path("trades-mgtox-usd-2013-01-01.csv"))
        resampledBarDS = resampled.ResampledBarDataSeries(
            feed["BTC"], barfeed.Frequency.HOUR)
        resampledFile = os.path.join(common.get_temp_path(),
                                     "hour-mgtox-usd-2013-01-01.csv")
        resample.resample_to_csv(feed, barfeed.Frequency.HOUR, resampledFile)
        resampledBarDS.pushLast(
        )  # Need to manually push the last stot since time didn't change.

        # Load the resampled file.
        feed = csvfeed.GenericBarFeed(barfeed.Frequency.HOUR)
        feed.addBarsFromCSV("BTC", resampledFile)
        feed.loadAll()

        self.assertEqual(len(feed["BTC"]), 24)
        self.assertEqual(feed["BTC"][0].getDateTime(),
                         datetime.datetime(2013, 01, 01, 00, 59, 59))
        self.assertEqual(feed["BTC"][-1].getDateTime(),
                         datetime.datetime(2013, 01, 01, 23, 59, 59))

        self.assertEqual(len(resampledBarDS), len(feed["BTC"]))
        self.assertEqual(resampledBarDS[0].getDateTime(),
                         dt.as_utc(feed["BTC"][0].getDateTime()))
        self.assertEqual(resampledBarDS[-1].getDateTime(),
                         dt.as_utc(feed["BTC"][-1].getDateTime()))
Exemple #5
0
    def testResampleNinjaTraderHour(self):
        with common.TmpDir() as tmp_path:
            # Resample.
            feed = ninjatraderfeed.Feed(ninjatraderfeed.Frequency.MINUTE)
            feed.addBarsFromCSV("spy", common.get_data_file_path("nt-spy-minute-2011.csv"))
            resampledBarDS = resampled_ds.ResampledBarDataSeries(feed["spy"], bar.Frequency.HOUR)
            resampledFile = os.path.join(tmp_path, "hour-nt-spy-minute-2011.csv")
            resample.resample_to_csv(feed, bar.Frequency.HOUR, resampledFile)
            resampledBarDS.pushLast()  # Need to manually push the last stot since time didn't change.

            # Load the resampled file.
            feed = csvfeed.GenericBarFeed(bar.Frequency.HOUR, marketsession.USEquities.getTimezone())
            feed.addBarsFromCSV("spy", resampledFile)
            feed.loadAll()

        self.assertEqual(len(feed["spy"]), 340)
        self.assertEqual(feed["spy"][0].getDateTime(), dt.localize(datetime.datetime(2011, 1, 3, 9), marketsession.USEquities.getTimezone()))
        self.assertEqual(feed["spy"][-1].getDateTime(), dt.localize(datetime.datetime(2011, 2, 1, 1), marketsession.USEquities.getTimezone()))
        self.assertEqual(feed["spy"][0].getOpen(), 126.35)
        self.assertEqual(feed["spy"][0].getHigh(), 126.45)
        self.assertEqual(feed["spy"][0].getLow(), 126.3)
        self.assertEqual(feed["spy"][0].getClose(), 126.4)
        self.assertEqual(feed["spy"][0].getVolume(), 3397.0)
        self.assertEqual(feed["spy"][0].getAdjClose(), None)

        self.assertEqual(len(resampledBarDS), len(feed["spy"]))
        self.assertEqual(resampledBarDS[0].getDateTime(), dt.as_utc(datetime.datetime(2011, 1, 3, 9)))
        self.assertEqual(resampledBarDS[-1].getDateTime(), dt.as_utc(datetime.datetime(2011, 2, 1, 1)))
Exemple #6
0
    def testResampleNinjaTraderDay(self):
        with common.TmpDir() as tmp_path:
            # Resample.
            feed = ninjatraderfeed.Feed(ninjatraderfeed.Frequency.MINUTE)
            feed.addBarsFromCSV(
                "spy", common.get_data_file_path("nt-spy-minute-2011.csv"))
            resampledBarDS = resampled_ds.ResampledBarDataSeries(
                feed["spy"], bar.Frequency.DAY)
            resampledFile = os.path.join(tmp_path,
                                         "day-nt-spy-minute-2011.csv")
            resample.resample_to_csv(feed, bar.Frequency.DAY, resampledFile)
            resampledBarDS.pushLast(
            )  # Need to manually push the last stot since time didn't change.

            # Load the resampled file.
            feed = csvfeed.GenericBarFeed(bar.Frequency.DAY)
            feed.addBarsFromCSV("spy", resampledFile,
                                marketsession.USEquities.getTimezone())
            feed.loadAll()

        self.assertEqual(len(feed["spy"]), 25)
        self.assertEqual(
            feed["spy"][0].getDateTime(),
            dt.localize(datetime.datetime(2011, 1, 3),
                        marketsession.USEquities.getTimezone()))
        self.assertEqual(
            feed["spy"][-1].getDateTime(),
            dt.localize(datetime.datetime(2011, 2, 1),
                        marketsession.USEquities.getTimezone()))

        self.assertEqual(len(resampledBarDS), len(feed["spy"]))
        self.assertEqual(resampledBarDS[0].getDateTime(),
                         dt.as_utc(datetime.datetime(2011, 1, 3)))
        self.assertEqual(resampledBarDS[-1].getDateTime(),
                         dt.as_utc(datetime.datetime(2011, 2, 1)))
def main():
    feed = csvfeed.GenericBarFeed(frequency=Frequency.MINUTE)
    feed.addBarsFromCSV("ETH", "sampledata.csv")

    # Evaluate the strategy with the feed's bars.
    myStrategy = Accumulator(feed, "ETH", buy_offset=0.0017, buy_percent=0.49)
    # myStrategy.run()

    returnsAnalyzer = returns.Returns()
    myStrategy.attachAnalyzer(returnsAnalyzer)
    tradesAnalyzer = trades.Trades()
    myStrategy.attachAnalyzer(tradesAnalyzer)

    plt = plotter.StrategyPlotter(myStrategy)
    # Include the SMA in the instrument's subplot to get it displayed along with the closing prices.
    plt.getInstrumentSubplot("ETH").addDataSeries("SMA", myStrategy.getSMA())
    # Plot the simple returns on each bar.
    plt.getOrCreateSubplot("returns").addDataSeries(
        "Simple returns", returnsAnalyzer.getReturns())

    # Run the strategy.
    myStrategy.run()
    myStrategy.info("Final portfolio value: $%.2f" % myStrategy.getResult())

    # Plot the strategy.
    plt.plot()

    print("Final portfolio value: $%.2f" % myStrategy.getResult())
Exemple #8
0
def main(plot):
    instrument = "aapl"
    vwapWindowSize = 5
    threshold = 0.01

    # Download the bars.
    #feed = yahoofinance.build_feed([instrument], 2011, 2012, ".")
    #feed = yahoofinance.build_feed([instrument], 2011, 2012, ".")
    #feed = yahoofeed.Feed()
    feed = csvfeed.GenericBarFeed(1)
    #feed.addBarsFromCSV("aapl", "BTC_NXT_CSV_NOTIME")
    feed.addBarsFromCSV("aapl", "a-2016-yahoofinance.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()
Exemple #9
0
def run_strategy(fastSma, slowSma, tp, stop):
    # Load the bar feed from the CSV file
    feed = csvfeed.GenericBarFeed(frequency=60 * 5)
    feed.setDateTimeFormat("%Y-%m-%dT%H:%M:%S.%fZ")
    feed.addBarsFromCSV("btc", "btc-5m-apr.csv")

    # Create our broker defining the comission(0,01%) and the initial balance($15000)
    commission = backtesting.TradePercentage(0.0001)
    broker = backtesting.Broker(15000, feed, commission)

    # Evaluate the strategy with the feed
    myStrategy = MACrossoverStrategy(feed, "btc", broker, fastSma, slowSma, tp,
                                     stop)

    # Attach the plotter to the strategy
    plt = plotter.StrategyPlotter(myStrategy)

    # Include the MA in the instrument's subplot to get it displayed along with the closing prices
    plt.getOrCreateSubplot("MA").addDataSeries("50 MA",
                                               myStrategy.getFastSMA())
    plt.getOrCreateSubplot("MA").addDataSeries("200 MA",
                                               myStrategy.getSlowSMA())

    # Run the strategy and show the final portfolio value
    myStrategy.run()
    myStrategy.info(f'Final portfolio value: ${myStrategy.getResult()}')

    # Plot the strategy
    plt.plot()
Exemple #10
0
    def testResampleMtGoxMinute(self):
        # Resample.
        feed = mtgoxfeed.CSVTradeFeed()
        feed.addBarsFromCSV(
            common.get_data_file_path("trades-mgtox-usd-2013-01-01.csv"))
        resampledBarDS = resampled.ResampledBarDataSeries(
            feed["BTC"], barfeed.Frequency.MINUTE)
        resample.resample_to_csv(feed, barfeed.Frequency.MINUTE,
                                 "minute-mgtox-usd-2013-01-01.csv")
        resampledBarDS.pushLast(
        )  # Need to manually push the last stot since time didn't change.

        # Load the resampled file.
        feed = csvfeed.GenericBarFeed(barfeed.Frequency.MINUTE)
        feed.addBarsFromCSV("BTC", "minute-mgtox-usd-2013-01-01.csv")
        feed.loadAll()

        self.assertEqual(len(feed["BTC"]), 537)
        self.assertEqual(feed["BTC"][0].getDateTime(),
                         datetime.datetime(2013, 01, 01, 00, 04, 59))
        self.assertEqual(feed["BTC"][-1].getDateTime(),
                         datetime.datetime(2013, 01, 01, 23, 58, 59))

        self.assertEqual(len(resampledBarDS), len(feed["BTC"]))
        self.assertEqual(resampledBarDS[0].getDateTime(),
                         dt.as_utc(feed["BTC"][0].getDateTime()))
        self.assertEqual(resampledBarDS[-1].getDateTime(),
                         dt.as_utc(feed["BTC"][-1].getDateTime()))
Exemple #11
0
def RSIBacktest(nper):
    # Create Instruments object with stock tickers
    instruments = ["BANKNIFTY"]
    # create feed object, add bars to the data feed
    feed = csvfeed.GenericBarFeed(bar.Frequency.DAY)
    feed.addBarsFromCSV(instruments[0], "Data//bnf.csv")
    # create object to run strategy
    rsi_strat = RSIStrategy(feed, instruments[0], nper)
    # Attach Strategy Plotter
    plt = plotter.StrategyPlotter(rsi_strat,
                                  plotAllInstruments=True,
                                  plotBuySell=True,
                                  plotPortfolio=False)
    plt.getOrCreateSubplot("RSI").addDataSeries("RSI", rsi_strat.getRSI())
    plt.getOrCreateSubplot("RSI").addLine("Upper Threshold", 70)
    plt.getOrCreateSubplot("RSI").addLine("Lower Threshold", 40)
    #    plt.getOrCreateSubplot("RSI").addLine("Center Line", 40)
    retAnalyzer = ret.Returns()
    rsi_strat.attachAnalyzer(retAnalyzer)
    sharpeRatioAnalyzer = sharpe.SharpeRatio()
    rsi_strat.attachAnalyzer(sharpeRatioAnalyzer)
    drawDownAnalyzer = drawdown.DrawDown()
    rsi_strat.attachAnalyzer(drawDownAnalyzer)
    tradesAnalyzer = trades.Trades()
    rsi_strat.attachAnalyzer(tradesAnalyzer)
    # Run Strategy
    rsi_strat.run()
    # Print Strategy Trading Statistics
    print
    print "------------------------------"
    print "1. Portfolio statistics"
    print
    print "Portfolio initial equity: $100000.00"
    print "Portfolio final equity: $%.2f" % rsi_strat.getBroker().getEquity()
    print "Portfolio net trading p&l: $%.2f" % tradesAnalyzer.getAll().sum()
    print "Portfolio maximum drawdown: %.2f %%" % (
        drawDownAnalyzer.getMaxDrawDown() * 100)
    print "Portfolio annualized return: %.2f %%" % (
        retAnalyzer.getCumulativeReturns()[-1] * 100)
    print "Portfolio annualized Sharpe ratio (Rf = 0%%): %.2f" % (
        sharpeRatioAnalyzer.getSharpeRatio(0.0))
    print "------------------------------"
    print "2. Total trades statistics"
    print "Total trades: %d" % (tradesAnalyzer.getCount())
    if tradesAnalyzer.getCount() > 0:
        tradesProfits = tradesAnalyzer.getAll()
        print "Total trades average p&l: $%2.f" % (tradesProfits.mean())
        print "Largest Winning Trade: $%2.f" % (tradesProfits.max())
        print "Largest Losing Trade: $%2.f" % (tradesProfits.min())
        tradesReturns = tradesAnalyzer.getAllReturns()
        print "Average return: %2.f %%" % (tradesReturns.mean() * 100)
        print "Largest Winning Trade Return: %2.f %%" % (tradesReturns.max() *
                                                         100)
        print "Largest Losing Trade Return: %2.f %%" % (tradesReturns.min() *
                                                        100)
    print "------------------------------"
    # Plot Strategy
    plt.plot()
Exemple #12
0
def run_strategy(smaPeriod):
    # Load the bar feed from the CSV file
    # feed = quandlfeed.Feed()
    # feed.addBarsFromCSV("orcl", "WIKI-ORCL-2000-quandl.csv")
    feed = csvfeed.GenericBarFeed(Frequency.MINUTE)
    feed.addBarsFromCSV(
        "orcl",
        "../../data/input/EURUSD_Candlestick_15_M_ASK_01.04.2018-21.09.2018_after.csv"
    )

    # Evaluate the strategy with the feed.
    myStrategy = MyStrategy(feed, "orcl", smaPeriod)
    myStrategy.run()
    print("Final portfolio value: $%.2f" % myStrategy.getBroker().getEquity())
Exemple #13
0
def algo_test(target_name,
              target_csv,
              model_name,
              model_csv,
              model_prediction_std=0.0):
    # Load the bar feed from the CSV file
    feed = csvfeed.GenericBarFeed(pyalgotrade.bar.Frequency.DAY)
    feed.addBarsFromCSV(target_name, target_csv)
    feed.addBarsFromCSV(model_name, model_csv)

    # Evaluate the strategy with the feed's bars.
    myStrategy = MyStrategy(feed, target_name, model_prediction_std)
    # myStrategy = MyBasicStrategy(feed, target_name)

    # Attach analyzers.
    retAnalyzer = returns.Returns()
    myStrategy.attachAnalyzer(retAnalyzer)
    sharpeRatioAnalyzer = sharpe.SharpeRatio()
    myStrategy.attachAnalyzer(sharpeRatioAnalyzer)
    drawDownAnalyzer = drawdown.DrawDown()
    myStrategy.attachAnalyzer(drawDownAnalyzer)
    sortinoRatioAnalyzer = sortino.SortinoRatio()
    myStrategy.attachAnalyzer(sortinoRatioAnalyzer)

    # Run the strategy
    myStrategy.run()

    # Print the results.
    print("Final portfolio value: $%.2f" % myStrategy.getResult())
    print("Total return: %.2f %%" %
          (retAnalyzer.getCumulativeReturns()[-1] * 100))
    print("Average daily return: %.2f %%" %
          (stats.mean(retAnalyzer.getReturns()) * 100))
    print("Std. dev. daily return: %.4f" %
          (stats.stddev(retAnalyzer.getReturns())))
    print("Sharpe ratio: %.2f" % (sharpeRatioAnalyzer.getSharpeRatio(0)))
    print("Sortino ratio: %.2f" % (sortinoRatioAnalyzer.getSortinoRatio(0)))

    returnsPerDay = stats.mean(retAnalyzer.getReturns())

    # print("shares list : ")
    # print(myStrategy.getShares())
    output = {
        'sharpe': sharpeRatioAnalyzer.getSharpeRatio(0),
        'sortino': sortinoRatioAnalyzer.getSortinoRatio(0),
        'returnAnalyzer': retAnalyzer,
        'annualReturns': returnsPerDay * 252
    }

    return output
Exemple #14
0
def ZScorePlot(nper, lowerThreshold, upperThreshold):
    # Create Instruments object with stock tickers
    instruments = ["NIFTY"]
    # create feed object, add bars to the data feed
    feed = csvfeed.GenericBarFeed(bar.Frequency.DAY)
    feed.addBarsFromCSV(instruments[0], "Data//NIFTY.csv")
    # create object to run strategy
    zscore_plot = ZScoreStrategy(feed, instruments[0], nper, lowerThreshold, upperThreshold)
    # Attach Strategy Plotter
    plt = plotter.StrategyPlotter(zscore_plot,  plotAllInstruments=True, plotBuySell=True, plotPortfolio=False)
    plt.getOrCreateSubplot("ZScore").addDataSeries("ZScore", zscore_plot.getZScore())
    # plt.getOrCreateSubplot("RSI").addLine("Center Line", 40)
    # Run Strategy
    zscore_plot.run()
    # Plot Strategy
    plt.plot()
Exemple #15
0
    def testResampleMtGoxDay(self):
        # Resample.
        feed = mtgoxfeed.CSVTradeFeed()
        feed.addBarsFromCSV(
            common.get_data_file_path("trades-mgtox-usd-2013-01-01.csv"))
        resampledBarDS = resampled.ResampledBarDataSeries(
            feed["BTC"], barfeed.Frequency.DAY)
        resampledFile = os.path.join(common.get_temp_path(),
                                     "day-mgtox-usd-2013-01-01.csv")
        resample.resample_to_csv(feed, barfeed.Frequency.DAY, resampledFile)
        resampledBarDS.pushLast(
        )  # Need to manually push the last stot since time didn't change.

        # Load the resampled file.
        feed = csvfeed.GenericBarFeed(barfeed.Frequency.DAY)
        feed.addBarsFromCSV("BTC", resampledFile)
        feed.loadAll()

        self.assertEqual(len(feed["BTC"]), 1)
        self.assertEqual(feed["BTC"][0].getDateTime(),
                         datetime.datetime(2013, 01, 01, 23, 59, 59))
        self.assertEqual(feed["BTC"][0].getOpen(), 13.51001)
        self.assertEqual(feed["BTC"][0].getHigh(), 13.56)
        self.assertEqual(feed["BTC"][0].getLow(), 13.16123)
        self.assertEqual(feed["BTC"][0].getClose(), 13.30413)
        self.assertEqual(feed["BTC"][0].getVolume(), 28168.9114596)
        self.assertEqual(feed["BTC"][0].getAdjClose(), 13.30413)

        self.assertEqual(len(resampledBarDS), len(feed["BTC"]))
        self.assertEqual(resampledBarDS[0].getDateTime(),
                         dt.as_utc(feed["BTC"][0].getDateTime()))
        self.assertEqual(resampledBarDS[-1].getDateTime(),
                         dt.as_utc(feed["BTC"][-1].getDateTime()))
        self.assertEqual(resampledBarDS[0].getOpen(), feed["BTC"][0].getOpen())
        self.assertEqual(resampledBarDS[0].getHigh(), feed["BTC"][0].getHigh())
        self.assertEqual(resampledBarDS[0].getLow(), feed["BTC"][0].getLow())
        self.assertEqual(resampledBarDS[0].getClose(),
                         feed["BTC"][0].getClose())
        self.assertEqual(round(resampledBarDS[0].getVolume(), 5),
                         round(feed["BTC"][0].getVolume(), 5))
        self.assertEqual(resampledBarDS[0].getAdjClose(),
                         feed["BTC"][0].getAdjClose())
Exemple #16
0
def main(plot):
    instrument = "BTC"
    initialCash = 1000
    vwapWindowSize = 100
    buyThreshold = 0.02
    sellThreshold = 0.01

    barFeed = csvfeed.GenericBarFeed(bar.Frequency.MINUTE*30)
    barFeed.addBarsFromCSV(instrument, "30min-bitstampUSD.csv")
    brk = broker.BacktestingBroker(initialCash, barFeed)
    strat = VWAPMomentum(barFeed, brk, instrument, vwapWindowSize, buyThreshold, sellThreshold)

    if plot:
        plt = plotter.StrategyPlotter(strat)
        plt.getInstrumentSubplot(instrument).addDataSeries("VWAP", strat.getVWAP())

    strat.run()

    if plot:
        plt.plot()
Exemple #17
0
def MACrossSignals(nfast, nslow):
    # Create Instruments object with stock tickers
    instruments = ["NIFTY"]
    # create feed object, add bars to the data feed
    feed = csvfeed.GenericBarFeed(bar.Frequency.DAY)
    feed.addBarsFromCSV(instruments[0], "Data//NIFTY.csv")
    # create object to run strategy
    ma_signals = MAStrategy(feed, instruments[0], nfast, nslow)
    # Attach Strategy Plotter
    plt = plotter.StrategyPlotter(ma_signals,
                                  plotAllInstruments=True,
                                  plotBuySell=True,
                                  plotPortfolio=False)
    plt.getInstrumentSubplot("NIFTY").addDataSeries("Fast SMA",
                                                    ma_signals.getfastSMA())
    plt.getInstrumentSubplot("NIFTY").addDataSeries("Slow SMA",
                                                    ma_signals.getslowSMA())
    # Run Strategy
    ma_signals.run()
    # Plot Strategy
    plt.plot()
def main(plot):
    #    merge_csv("./hoge.csv", ["./USDJPY_M5_2001.txt","./USDJPY_M5_2002.txt","./USDJPY_M5_2003.txt","./USDJPY_M5_2004.txt",\
    #                             "./USDJPY_M5_2005.txt","./USDJPY_M5_2006.txt","./USDJPY_M5_2007.txt","./USDJPY_M5_2008.txt"])

    instrument = "USDJPY"
    feed = csvfeed.GenericBarFeed(Frequency.MINUTE, pytz.utc)
    feed.addBarsFromCSV(instrument, "./hoge.csv")
    strat = MATrade(feed, instrument)
    sharpeRatioAnalyzer = sharpe.SharpeRatio()
    strat.attachAnalyzer(sharpeRatioAnalyzer)

    if plot:
        plt = plotter.StrategyPlotter(strat, True, True, True)
        plt.getInstrumentSubplot(instrument).addDataSeries(
            "MA20", strat.getSMA())

    strat.run()
    print "Sharpe ratio: %.2f" % sharpeRatioAnalyzer.getSharpeRatio(0.05)

    if plot:
        plt.plot()
def main():
    # Initiate strategy with provided data
    feed = csvfeed.GenericBarFeed(Frequency.DAY)
    feed.addBarsFromCSV(INSTRUMENT, BACKTESTING_DATA)
    momentum_strategy = CryptoMomentumStrategy(feed, INSTRUMENT, MA_LOOKBACK, EMA_LOOKBACK, ATR_LOOKBACK)
    # Attach returns analyzer
    returns_analyzer = returns.Returns()
    momentum_strategy.attachAnalyzer(returns_analyzer)
    # Attach trades analyzer
    trades_analyzer = trades.Trades()
    momentum_strategy.attachAnalyzer(trades_analyzer)
    # Configure plotter
    plt = plotter.StrategyPlotter(momentum_strategy)
    plt.getInstrumentSubplot(INSTRUMENT).addDataSeries('MA', momentum_strategy.get_plot_ma())
    plt.getInstrumentSubplot(INSTRUMENT).addDataSeries('EMA', momentum_strategy.get_plot_ema())
    plt.getOrCreateSubplot('returns').addDataSeries('Simple Returns', returns_analyzer.getReturns())
    # Run strategy
    momentum_strategy.run()
    momentum_strategy.info('Final portfolio value: ${:.2f}'.format(momentum_strategy.getResult()))
    # Plot strategy
    plt.plot()
Exemple #20
0
def MACDPlot(nfastEMA, nslowEMA, nsignalEMA):
    # Create Instruments object with stock tickers
    instruments = ["NIFTY"]
    # create feed object, add bars to the data feed
    feed = csvfeed.GenericBarFeed(bar.Frequency.DAY)
    feed.addBarsFromCSV(instruments[0], "Data//NIFTY.csv")
    # create object to run strategy
    macd_plot = MACDStrategy(feed, instruments[0], nfastEMA, nslowEMA,
                             nsignalEMA)
    # Attach Strategy Plotter
    plt = plotter.StrategyPlotter(macd_plot,
                                  plotAllInstruments=True,
                                  plotBuySell=True,
                                  plotPortfolio=False)
    plt.getOrCreateSubplot("MACD").addDataSeries("MACD", macd_plot.getMACD())
    plt.getOrCreateSubplot("MACD").addDataSeries(
        "Signal",
        macd_plot.getMACD().getSignal())
    plt.getOrCreateSubplot("MACD").addLine("CenterLine", 0)
    # Run Strategy
    macd_plot.run()
    # Plot Strategy
    plt.plot()
def BbandPlot(nper, nstdev):
    # Create Instruments object with stock tickers
    instruments = ["NIFTY"]
    # create feed object, add bars to the data feed
    feed = csvfeed.GenericBarFeed(bar.Frequency.DAY)
    feed.addBarsFromCSV(instruments[0], "Data//NIFTY.csv")
    # create object to run strategy
    bb_plot = BBStrategy(feed, instruments[0], nper, nstdev)
    # Attach Strategy Plotter
    plt = plotter.StrategyPlotter(bb_plot,
                                  plotAllInstruments=True,
                                  plotBuySell=True,
                                  plotPortfolio=False)
    plt.getInstrumentSubplot("NIFTY").addDataSeries(
        "Lower band",
        bb_plot.getBBands().getLowerBand())
    #    plt.getInstrumentSubplot("NIFTY").addDataSeries("Middle band", bb_plot.getBBands().getMiddleBand())
    plt.getInstrumentSubplot("NIFTY").addDataSeries(
        "Upper band",
        bb_plot.getBBands().getUpperBand())
    # Run Strategy
    bb_plot.run()
    # Plot Strategy
    plt.plot()
        fastlist.append(tmp_fast)

    #backtest fastperiod/slowperiod pair
    net_profit_list = []
    for i in range(len(fastvec)):
        fastPeriod = fastvec[i]
        tmp_profit_list = []
        for slowPeriod in slowlist[i]:

            print([fastPeriod, slowPeriod])

            INITIAL_BUDGET = 15000
            NSHARES = 20

            #the data is in the CSV file
            feed = csvfeed.GenericBarFeed(bar.Frequency.DAY)
            feed.addBarsFromCSV(instrument, fname)

            # define the time for the moving average models
            movingAverageStrategy = MovingAverageStrategy(
                feed, instrument, fastPeriod, slowPeriod)

            #define the cost of trading
            movingAverageStrategy.getBroker().setCommission(
                backtesting.FixedPerTrade(cost_per_trade))

            #analyze the returns during the backtest
            returnAnalyzer = ret.Returns()
            movingAverageStrategy.attachAnalyzer(returnAnalyzer)

            #analyze the Sharpe ratio during backtest
def get_generic_feed(instrument, relative_filepath, frequency):
    # feed.setBarFilter(csvfeed.DateRangeFilter(firstDate,endDate))
    feed = csvfeed.GenericBarFeed(frequency)
    feed.addBarsFromCSV(instrument, get_filepath(relative_filepath))
    return feed
def main():
    feed = csvfeed.GenericBarFeed(frequency=Frequency.MINUTE)
    feed.addBarsFromCSV("BTC", "sampledata.csv")

    # Plot the strategy.
    local.run(Accumulator, feed, parameters_generator())
Exemple #25
0
from pyalgotrade.stratanalyzer import returns
from pyalgotrade.stratanalyzer import sharpe
from pyalgotrade.stratanalyzer import drawdown
from pyalgotrade.stratanalyzer import trades
from pyalgotrade import plotter
from pyalgotrade.bar import Frequency
from pyalgotrade_itf_db_feed import ITFDatabaseFeed

import pyalgotrade_sample_strat

# Load the feed from ITF database
feed = ITFDatabaseFeed(frequency=Frequency.HOUR)
feed.addBarsFromDB("BTC")

# Load the feed from a CSV file
feed = csvfeed.GenericBarFeed(frequency=Frequency.HOUR)
feed.addBarsFromCSV("BTC", "sample_data.csv")

# Evaluate the strategy with the feed's bars.
myStrategy = pyalgotrade_sample_strat.SMACrossOver(feed, "BTC", 20)

# Attach different analyzers to a strategy before executing it.
retAnalyzer = returns.Returns()
myStrategy.attachAnalyzer(retAnalyzer)
sharpeRatioAnalyzer = sharpe.SharpeRatio()
myStrategy.attachAnalyzer(sharpeRatioAnalyzer)
drawDownAnalyzer = drawdown.DrawDown()
myStrategy.attachAnalyzer(drawDownAnalyzer)
tradesAnalyzer = trades.Trades()
myStrategy.attachAnalyzer(tradesAnalyzer)
Exemple #26
0
from pyalgotrade.barfeed import csvfeed
from pyalgotrade import bar


def parameters_generator():
    instrument = ["btc"]
    entrySMA = range(120, 155)
    exitSMA = range(10, 15)
    rsiPeriod = range(2, 4)
    overBoughtThreshold = range(70, 90)
    overSoldThreshold = range(19, 35)
    initialAmount = [5000]
    return itertools.product(instrument, entrySMA, exitSMA, rsiPeriod,
                             overBoughtThreshold, overSoldThreshold,
                             initialAmount)


# The if __name__ == '__main__' part is necessary if running on Windows.
if __name__ == '__main__':
    instrument = "btc"
    year = "2015"
    # Load the feed from the CSV files.
    barFeed = csvfeed.GenericBarFeed(bar.Frequency.MINUTE * 30)
    barFeed.addBarsFromCSV(instrument, "30min-%s-%s.csv" % (instrument, year))

    #feed = yahoofeed.Feed()
    # feed.addBarsFromCSV("btc", "btc_all_daily.csv")

    # Run the server.
    server.serve(barFeed, parameters_generator(), "0.0.0.0", 5000)
def BbandBacktest(nper, nstdev):
    # Create Instruments object with stock tickers
    instruments = ["BANKNIFTY"]
    # create feed object, add bars to the data feed
    feed = csvfeed.GenericBarFeed(bar.Frequency.DAY)
    feed.addBarsFromCSV(instruments[0], "Data//bnf.csv")
    # create object to run strategy
    bb_strat = BBStrategy(feed, instruments[0], nper, nstdev)
    # add trading costs using TradePercentage()
    bb_strat.getBroker().setCommission(
        broker.backtesting.TradePercentage(0.01))
    # Attach Strategy Plotter
    plt = plotter.StrategyPlotter(bb_strat,
                                  plotAllInstruments=True,
                                  plotBuySell=True,
                                  plotPortfolio=False)
    plt.getInstrumentSubplot("BANKNIFTY").addDataSeries(
        "Lower band",
        bb_strat.getBBands().getLowerBand())
    #    plt.getInstrumentSubplot("NIFTY").addDataSeries("Middle band", bb_strat.getBBands().getMiddleBand())
    plt.getInstrumentSubplot("BANKNIFTY").addDataSeries(
        "Upper band",
        bb_strat.getBBands().getUpperBand())
    retAnalyzer = ret.Returns()
    bb_strat.attachAnalyzer(retAnalyzer)
    sharpeRatioAnalyzer = sharpe.SharpeRatio()
    bb_strat.attachAnalyzer(sharpeRatioAnalyzer)
    drawDownAnalyzer = drawdown.DrawDown()
    bb_strat.attachAnalyzer(drawDownAnalyzer)
    tradesAnalyzer = trades.Trades()
    bb_strat.attachAnalyzer(tradesAnalyzer)
    # Run Strategy
    bb_strat.run()
    # Print Strategy Trading Statistics
    print
    print "------------------------------"
    print "1. Portfolio statistics"
    print
    print "Portfolio initial equity: $100000.00"
    print "Portfolio final equity: $%.2f" % bb_strat.getBroker().getEquity()
    print "Portfolio net trading p&l: $%.2f" % tradesAnalyzer.getAll().sum()
    print "Portfolio maximum drawdown: %.2f %%" % (
        drawDownAnalyzer.getMaxDrawDown() * 100)
    print "Portfolio annualized return: %.2f %%" % (
        retAnalyzer.getCumulativeReturns()[-1] * 100)
    print "Portfolio annualized Sharpe ratio (Rf = 0%%): %.2f" % (
        sharpeRatioAnalyzer.getSharpeRatio(0.0))
    print "------------------------------"
    print "2. Total trades statistics"
    print "Total trades: %d" % (tradesAnalyzer.getCount())
    if tradesAnalyzer.getCount() > 0:
        tradesProfits = tradesAnalyzer.getAll()
        print "Total trades average p&l: $%2.f" % (tradesProfits.mean())
        print "Largest Winning Trade: $%2.f" % (tradesProfits.max())
        print "Largest Losing Trade: $%2.f" % (tradesProfits.min())
        tradesReturns = tradesAnalyzer.getAllReturns()
        print "Average return: %2.f %%" % (tradesReturns.mean() * 100)
        print "Largest Winning Trade Return: %2.f %%" % (tradesReturns.max() *
                                                         100)
        print "Largest Losing Trade Return: %2.f %%" % (tradesReturns.min() *
                                                        100)
    print "------------------------------"
    # Plot Strategy
    plt.plot()
Exemple #28
0
from pyalgotrade import strategy
from pyalgotrade.barfeed import quandlfeed
from pyalgotrade.barfeed import csvfeed
from pyalgotrade.bar import Frequency


class MyStrategy(strategy.BacktestingStrategy):
    def __init__(self, feed, instrument):
        super(MyStrategy, self).__init__(feed)
        self.__instrument = instrument

    def onBars(self, bars):
        bar = bars[self.__instrument]
        self.info(bar.getClose())


# Load the bar feed from the CSV file
feed = csvfeed.GenericBarFeed(Frequency.MINUTE)
# feed.addBarsFromCSV("orcl", "WIKI-ORCL-2000-quandl.csv")
# feed.addBarsFromCSV("orcl", "../../data/input/EURUSD-2018_04_01-2018_09_24.csv")
feed.addBarsFromCSV(
    "orcl",
    "../../data/input/EURUSD_Candlestick_15_M_ASK_01.04.2018-21.09.2018_after.csv"
)
# feed.addBarsFromCSV("orcl", "../../data/input/EURUSD-2018_09_23-2018_09_24.csv")
# feed.addBarsFromCSV("orcl", "../../data/input/EURUSD_Candlestick_15_M_BID_01.04.2018-21.09.2018.csv")
# Evaluate the strategy with the feed's bars.
myStrategy = MyStrategy(feed, "orcl")
myStrategy.run()