def testProportionalCommissionBug(self):
        # Regression test for a bug reported by 'Jackson Sam' on 30/Aug/2013.
        strat = self.__createStrategy()
        strat.getBroker().setCommission(backtesting.FixedPerTrade(0.01))
        stratAnalyzer = trades.Trades()
        strat.attachAnalyzer(stratAnalyzer)

        # There are 3 trades here:
        # Trade 1 (Long)
        #   Buy 1 @ 127.16 Commission: 0.01
        #   Sell 1 @ 127.26 Commission: 0.005
        # Trade 2 (Short)
        #   Sell 1 @ 127.26 Commission: 0.005
        #   Buy 1 @ 127.37 Commission: 0.005
        # Trade 3 (Long)
        #   Buy 1 @ 127.37 Commission: 0.005
        #   Sell 1 @ 127.4 Commission: 0.01

        strat.addOrder(buildUTCDateTime(2011, 1, 3, 15, 38), strat.getBroker().createMarketOrder, broker.Order.Action.BUY, TradesAnalyzerTestCase.TestInstrument, 1)  # Fill at 127.16
        strat.addOrder(buildUTCDateTime(2011, 1, 3, 15, 42), strat.getBroker().createMarketOrder, broker.Order.Action.SELL, TradesAnalyzerTestCase.TestInstrument, 2)  # Fill at 127.26
        strat.addOrder(buildUTCDateTime(2011, 1, 3, 15, 53), strat.getBroker().createMarketOrder, broker.Order.Action.BUY, TradesAnalyzerTestCase.TestInstrument, 2)  # Fill at 127.37
        strat.addOrder(buildUTCDateTime(2011, 1, 3, 15, 58), strat.getBroker().createMarketOrder, broker.Order.Action.SELL, TradesAnalyzerTestCase.TestInstrument, 1)  # Fill at 127.4

        strat.run()
        allReturns = stratAnalyzer.getAllReturns()
        self.assertEqual(round(allReturns[0], 6), 0.000668)
        self.assertEqual(round(allReturns[1], 6), -0.000943)
        self.assertEqual(round(allReturns[2], 6), 0.000118)
    def testIGE_BrokerWithCommission(self):
        commision = 0.5
        initialCash = 42.09 + commision
        # This testcase is based on an example from Ernie Chan's book:
        # 'Quantitative Trading: How to Build Your Own Algorithmic Trading Business'
        barFeed = yahoofeed.Feed()
        barFeed.addBarsFromCSV("ige", common.get_data_file_path("sharpe-ratio-test-ige.csv"))
        strat = strategy_test.TestStrategy(barFeed, initialCash)
        strat.getBroker().setCommission(backtesting.FixedPerTrade(commision))
        strat.setUseAdjustedValues(True)
        strat.setBrokerOrdersGTC(True)
        stratAnalyzer = sharpe.SharpeRatio()
        strat.attachAnalyzer(stratAnalyzer)

        # Disable volume checks to match book results.
        strat.getBroker().getFillStrategy().setVolumeLimit(None)

        # Manually place the order to get it filled on the first bar.
        order = strat.getBroker().createMarketOrder(broker.Order.Action.BUY, "ige", 1, True)  # Adj. Close: 42.09
        order.setGoodTillCanceled(True)
        strat.getBroker().placeOrder(order)
        strat.addOrder(datetime.datetime(2007, 11, 13), strat.getBroker().createMarketOrder, broker.Order.Action.SELL, "ige", 1, True)  # Adj. Close: 127.64

        strat.run()
        self.assertTrue(round(strat.getBroker().getCash(), 2) == initialCash + (127.64 - 42.09 - commision*2))
        self.assertEqual(strat.orderUpdatedCalls, 4)
        # The results are slightly different only because I'm taking into account the first bar as well,
        # and I'm also adding commissions.
        self.assertEqual(round(stratAnalyzer.getSharpeRatio(0.04, True), 6), 0.776443)
示例#3
0
    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)
示例#4
0
def main(printinfo):
    firstyear = 2007
    lastyear = 2013
    num_instr = 3
    posinstruments = daq.find_instruments_by_year(firstyear)
    instruments = sample(posinstruments, num_instr)
    instruments = ['JCI', 'AAPL', 'YUM', 'ABC']
    feed = daq.build_stock_feed(instruments, [firstyear, lastyear])
    this_Strategy = sgs.SLTRIXCrossover(feed,
                                        instruments,
                                        100000,
                                        12,
                                        27,
                                        .43,
                                        .43,
                                        printinfo=printinfo)
    # this_Strategy = sgs.EMACrossover(feed, instruments, 100000, 28, .5, ('FixedPerTrade', 10))
    retAnalyzer = returns.Returns()
    this_Strategy.attachAnalyzer(retAnalyzer)
    # this_Strategy.getBroker().setCommission(
    # backtesting.TradePercentage(.01))  # 1.% commission per trade
    this_Strategy.getBroker().setCommission(
        backtesting.FixedPerTrade(10))  # $10 commission per trade

    # Attach plotters
    # Attach the plotter to the strategy.
    plt = plotter.StrategyPlotter(this_Strategy)
    # Include the SMA in the instrument's subplot to get it displayed along
    # with the closing prices.

    # for pltinstr in instruments:
    #     plt.getInstrumentSubplot(pltinstr).addDataSeries(
    #         "Short TRIX", this_Strategy.getshorttrix(pltinstr))
    #     plt.getInstrumentSubplot(pltinstr).addDataSeries(
    #         "Long TRIX", this_Strategy.getlongtrix(pltinstr))

    # for pltinstr in instruments:
    #     plt.getInstrumentSubplot(pltinstr).addDataSeries(
    #         "EMA", this_Strategy.getEMA(pltinstr))

    # # Plot the simple returns on each bar.
    # plt.getOrCreateSubplot("returns").addDataSeries(
    #     "Simple returns", retAnalyzer.getReturns())
    # Run the strategy
    this_Strategy.run()

    # Print the results.
    print "Final portfolio value: $%.2f" % this_Strategy.getResult()
    print "Annual return: %.2f %%" % (
        (retAnalyzer.getCumulativeReturns()[-1] * 100) /
        float(lastyear - firstyear))
    print "Average daily return: %.2f %%" % (
        stats.mean(retAnalyzer.getReturns()) * 100)
    print "Std. dev. daily return: %.4f" % (stats.stddev(
        retAnalyzer.getReturns()))
    plt.plot()
    return this_Strategy.getResult()
示例#5
0
 def __init__(self, feed, longsize, shortsize, riskfactor):
     broker = backtesting.Broker(10000, feed, backtesting.FixedPerTrade(10))
     super(SMAStrategyOptimizer,
           self).__init__(feed=feed,
                          broker=broker,
                          tradingAlgorithm=SMATradingAlgorithm(
                              feed, broker, longsize, shortsize,
                              riskfactor),
                          debugMode=False)
示例#6
0
 def __init__(self, feed, entrySize, exitSize, riskFactor):
     broker = backtesting.Broker(10000, feed, backtesting.FixedPerTrade(10))
     super(DonchianStrategyOptimizer,
           self).__init__(feed=feed,
                          broker=broker,
                          tradingAlgorithm=DonchianTradingAlgorithm(
                              feed, broker, entrySize, exitSize,
                              riskFactor),
                          debugMode=False)
示例#7
0
 def __init__(self, feed, instrument):
     super(MyStrategy, self).__init__(feed, 100000)
     self.__position = None
     self.__instrument = instrument
     self.getBroker().setCommission(backtesting.FixedPerTrade(5))
     self.__macd = macd.MACD(feed[instrument].getPriceDataSeries(), 12, 26,
                             9)
     self.__analyzer = Analyzer(self, 'hs300')
     self.__transaction = Transaction(self)
     self.__transposition = TradePosition(self)
示例#8
0
 def __init__(self, feed, instrument, t, clossarr, alpha):
     super(MyStrategy, self).__init__(feed, 100000)
     self.__position = None
     self.__instrument = instrument
     self.getBroker().setCommission(backtesting.FixedPerTrade(5))
     self.__BBcurve = BBCurve.BBCurve(feed[self.__instrument].getPriceDataSeries(), t, clossarr, alpha)
     self.__analyzer = Analyzer(self, 'hs300')
     self.__transaction = Transaction(self)
     self.__transposition = TradePosition(self)
     self.__Value = []
     self.__bull = None
     self.__bear = None
示例#9
0
 def __init__(self, feed, instrument, svmstrategy, scaler, period):
     super(MyStrategy, self).__init__(feed, 100000)
     self.__histValue = []
     self.__svmstrategy = svmstrategy
     self.__period = period
     self.__scaler = scaler
     self.__interval = 5
     self.__position = None
     self.__price = 0
     self.__instrument = instrument
     self.getBroker().setCommission(backtesting.FixedPerTrade(5))
     self.__analyzer = Analyzer(self, 'hs300')
     self.__transaction = Transaction(self)
     self.__transposition = TradePosition(self)
    def testSomeTradesWithCommissions(self):
        strat = self.__createStrategy()
        strat.getBroker().setCommission(backtesting.FixedPerTrade(0.01))
        stratAnalyzer = trades.Trades()
        strat.attachAnalyzer(stratAnalyzer)

        # Losing trade
        strat.addOrder(buildUTCDateTime(2011, 1, 3, 15, 30),
                       strat.getBroker().createMarketOrder,
                       broker.Order.Action.BUY,
                       TradesAnalyzerTestCase.TestInstrument, 1)  # 127.2
        strat.addOrder(buildUTCDateTime(2011, 1, 3, 15, 31),
                       strat.getBroker().createMarketOrder,
                       broker.Order.Action.SELL,
                       TradesAnalyzerTestCase.TestInstrument, 1)  # 127.16
        # Winning trade
        strat.addOrder(buildUTCDateTime(2011, 1, 3, 15, 38),
                       strat.getBroker().createMarketOrder,
                       broker.Order.Action.BUY,
                       TradesAnalyzerTestCase.TestInstrument, 1)  # 127.16
        strat.addOrder(buildUTCDateTime(2011, 1, 3, 15, 42),
                       strat.getBroker().createMarketOrder,
                       broker.Order.Action.SELL,
                       TradesAnalyzerTestCase.TestInstrument, 1)  # 127.26
        # Open trade.
        strat.addOrder(buildUTCDateTime(2011, 1, 3, 15, 47),
                       strat.getBroker().createMarketOrder,
                       broker.Order.Action.BUY,
                       TradesAnalyzerTestCase.TestInstrument, 1)  # 127.34
        strat.run()

        self.assertTrue(
            round(strat.getBroker().getCash(), 2) == round(
                1000 + (127.16 - 127.2) + (127.26 - 127.16) - 127.34 -
                0.01 * 5, 2))
        self.assertTrue(
            numpy.array_equal(stratAnalyzer.getCommissionsForAllTrades(),
                              numpy.array([0.02, 0.02])))
        self.assertTrue(
            numpy.array_equal(
                stratAnalyzer.getCommissionsForProfitableTrades(),
                numpy.array([0.02])))
        self.assertTrue(
            numpy.array_equal(
                stratAnalyzer.getCommissionsForUnprofitableTrades(),
                numpy.array([0.02])))
        self.assertTrue(
            numpy.array_equal(stratAnalyzer.getCommissionsForEvenTrades(),
                              numpy.array([])))
示例#11
0
	def testFixedPerTrade(self):
		comm = backtesting.FixedPerTrade(1.2)
		self.assertEqual(comm.calculate(None, 1, 1), 1.2)
示例#12
0
	def testSellShortWithCommission(self):
		sharePrice = 100
		commission = 10
		brk = backtesting.Broker(1010, barFeed=barfeed.BarFeed(barfeed.Frequency.MINUTE), commission=backtesting.FixedPerTrade(commission))

		# Sell 10 shares
		order = brk.createMarketOrder(broker.Order.Action.SELL_SHORT, BaseTestCase.TestInstrument, 10)
		brk.placeOrder(order)
		brk.onBars(self.buildBars(sharePrice, sharePrice, sharePrice, sharePrice))
		self.assertTrue(order.isFilled())
		self.assertTrue(order.getExecutionInfo().getCommission() == 10)
		self.assertTrue(brk.getCash() == 2000)
		self.assertTrue(brk.getShares(BaseTestCase.TestInstrument) == -10)

		# Buy the 10 shares sold short plus 9 extra
		order = brk.createMarketOrder(broker.Order.Action.BUY_TO_COVER, BaseTestCase.TestInstrument, 19)
		brk.placeOrder(order)
		brk.onBars(self.buildBars(sharePrice, sharePrice, sharePrice, sharePrice))
		self.assertTrue(order.isFilled())
		self.assertTrue(order.getExecutionInfo().getCommission() == 10)
		self.assertTrue(brk.getShares(BaseTestCase.TestInstrument) == 9)
		self.assertTrue(brk.getCash() == sharePrice - commission)
示例#13
0
	def testBuyWithCommission(self):
		brk = backtesting.Broker(1020, barFeed=barfeed.BarFeed(barfeed.Frequency.MINUTE), commission=backtesting.FixedPerTrade(10))

		# Buy
		order = brk.createMarketOrder(broker.Order.Action.BUY, BaseTestCase.TestInstrument, 100)
		brk.placeOrder(order)
		brk.onBars(self.buildBars(10, 15, 8, 12))
		self.assertTrue(order.isFilled())
		self.assertTrue(order.getExecutionInfo().getCommission() == 10)
		self.assertTrue(len(brk.getActiveOrders()) == 0)
		self.assertTrue(brk.getCash() == 10)
		self.assertTrue(brk.getShares(BaseTestCase.TestInstrument) == 100)
示例#14
0
            #the data is in the CSV file (one row per day)
            feed = csvfeed.GenericBarFeed(bar.Frequency.DAY)
            feed.addBarsFromCSV(ticker, file_name)

            #this is where we define the time for the moving average models (slow and fast)
            movingAverageStrategy = sma_9.MovingAverageStrategy(
                feed, ticker, fastPeriod)
            #Set Initial Budget
            movingAverageStrategy.initBackTestStrategy(INITIAL_BUDGET)
            #Set Risk Percent, default is 2
            movingAverageStrategy.setRiskPercent(RISK_PERCENT)
            #Set budget useage
            movingAverageStrategy.setBudgetUse(BUDGET_USE)
            #we can define the cost of trading (cost pre trade)
            movingAverageStrategy.getBroker().setCommission(
                backtesting.FixedPerTrade(0.1))
            #Turn on or off the trade print output
            movingAverageStrategy.setInfoOutput(outputInfo)

            #Prepare plots
            plot = plotter.StrategyPlotter(movingAverageStrategy,
                                           plotAllInstruments=True,
                                           plotBuySell=True,
                                           plotPortfolio=True)
            plot.getInstrumentSubplot(ticker).addDataSeries(
                'Fast SMA', movingAverageStrategy.getFastMA())

            #we can analyze the returns during the backtest
            returnAnalyzer = ret.Returns()
            movingAverageStrategy.attachAnalyzer(returnAnalyzer)
            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
            sharpeRatioAnalyzer = sharpe.SharpeRatio()
            movingAverageStrategy.attachAnalyzer(sharpeRatioAnalyzer)

            # analyze the trades
            tradesAnalyzer = trades.Trades()
            movingAverageStrategy.attachAnalyzer(tradesAnalyzer)

            movingAverageStrategy.run()
	fname=fpath+instrument+ftype

	#first MA indicator tracks the slow trend with period 50
	slowPeriod = 100
	#second MA indicator tracks the fast trend with period 30
	fastPeriod = 50
	
	#the data is in the CSV file (one row per day)
	feed = csvfeed.GenericBarFeed(bar.Frequency.DAY)
	feed.addBarsFromCSV(instrument,fname)
	
	#this is where we define the time for the moving average models (slow and fast)
	movingAverageStrategy = MovingAverageStrategy(feed,instrument,fastPeriod,slowPeriod)
	
	#we can define the cost of trading (cost pre trade)
	movingAverageStrategy.getBroker().setCommission(backtesting.FixedPerTrade(cost_per_trade))
	
	#we want to plot the stock (instrument) with the buy/sell orders
	plot = plotter.StrategyPlotter(movingAverageStrategy,plotAllInstruments=True,plotBuySell=True,plotPortfolio=True)
	plot.getInstrumentSubplot('S&P500').addDataSeries('Fast SMA',movingAverageStrategy.getFastMA())
	plot.getInstrumentSubplot('S&P500').addDataSeries('Slow SMA',movingAverageStrategy.getSlowMA())
	
	#we can analyze the returns during the backtest
	returnAnalyzer = ret.Returns()
	movingAverageStrategy.attachAnalyzer(returnAnalyzer)
	
	#we can analyze the Sharpe ratio during backtest
	sharpeRatioAnalyzer = sharpe.SharpeRatio()
	movingAverageStrategy.attachAnalyzer(sharpeRatioAnalyzer)
	
	#we can analyze the trades (maximum profit or loss etc.)
示例#17
0

# Load the yahoo feed from CSV files.
feed = yahoofeed.Feed()
feed.addBarsFromCSV("aeti", "aeti-2009-yahoofinance.csv")
feed.addBarsFromCSV("egan", "egan-2009-yahoofinance.csv")
feed.addBarsFromCSV("glng", "glng-2009-yahoofinance.csv")
feed.addBarsFromCSV("simo", "simo-2009-yahoofinance.csv")

# Evaluate the strategy with the feed's bars.
myStrategy = MyStrategy(feed)

# Set commission
# https://github.com/gbeced/pyalgotrade/blob/master/testcases/sharpe_analyzer_test.py
myStrategy.getBroker().setCommission(
    backtesting.FixedPerTrade(10))  # $10 commission per trade
myStrategy.getBroker().setCommission(
    backtesting.TradePercentage(.10))  # 10.% commission per trade

# Attach returns and sharpe ratio analyzers.
retAnalyzer = returns.Returns()
myStrategy.attachAnalyzer(retAnalyzer)
sharpeRatioAnalyzer = sharpe.SharpeRatio()
myStrategy.attachAnalyzer(sharpeRatioAnalyzer)

# Run the strategy
myStrategy.run()

# Print the results.
print "Final portfolio value: $%.2f" % myStrategy.getResult()
print "Anual return: %.2f %%" % (retAnalyzer.getCumulativeReturns()[-1] * 100)