Esempio n. 1
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()
Esempio n. 2
0
 def __init__(self, feed, instrument):
     super(MyStrategy, self).__init__(feed, 1000000)
     self.__broker = self.getBroker()
     self.__broker.setCommission(backtesting.TradePercentage(0.0005))
     self.__instrument = instrument
     self.__position = None
     # self.setUseAdjustedValues(True)
     self.__days = None
Esempio n. 3
0
 def __init__(self, barFeed, cash=1000000):
     # The broker should subscribe to barFeed events before the strategy.
     # This is to avoid executing orders placed in the current tick.
     broker = backtesting.Broker(cash, barFeed,
                                 backtesting.TradePercentage(0.002))
     strategy.BaseStrategy.__init__(self, barFeed, broker)
     self.__useAdjustedValues = False
     self.setUseEventDateTimeInLogs(True)
Esempio n. 4
0
 def __init__(self, feed, instrument):
     super(MyStrategy, self).__init__(feed, 1000000)
     self.__broker = self.getBroker()
     self.__broker.setCommission(backtesting.TradePercentage(0.0005))
     self.__instrument = instrument
     self.__position = None
     # self.setUseAdjustedValues(True)
     self.__prices = feed[instrument].getPriceDataSeries()
     self.__sma10 = ma.SMA(self.__prices, 10)
     self.__sma25 = ma.SMA(self.__prices, 25)
Esempio n. 5
0
 def __init__(self,
              initialBalances,
              barFeed,
              fee=0.005,
              instrumentTraits=livebroker.InstrumentTraits()):
     super(BacktestingBroker,
           self).__init__(initialBalances,
                          barFeed,
                          commission=backtesting.TradePercentage(fee),
                          instrumentTraits=instrumentTraits)
     self._tradeValidatorPredicate = TradeValidatorPredicate(
         instrumentTraits)
Esempio n. 6
0
 def __init__(self, feed, instruments, posMax, delay):
     myBroker = broker.Broker(1000000, feed, broker.TradePercentage(0.002))
     strategy.BacktestingStrategy.__init__(self, feed, myBroker)
     self._delay = delay
     self._liquidity = 0.05
     self._positions = {}
     self._posMax = posMax
     self._instruments = instruments
     self.setUseAdjustedValues(True)
     self.getBroker().getFillStrategy().setVolumeLimit(None)
     self.startDateTime = feed.peekDateTime()
     self.endDateTime = None
Esempio n. 7
0
    def __init__(self,
                 feed,
                 instrument,
                 bBandsPeriod,
                 cash=10,
                 comission=0.002):
        broker = backtesting.Broker(cash, feed,
                                    backtesting.TradePercentage(comission))
        strategy.BaseStrategy.__init__(self, feed, broker)

        self.__instrument = instrument
        self.__bbands = bollinger.BollingerBands(
            feed[instrument].getCloseDataSeries(), bBandsPeriod, 2)
Esempio n. 8
0
    def __init__(self, feed, instrument):
        # 起始金额100万刀
        super(MyStrategy, self).__init__(feed, 1000000)
        self.__broker = self.getBroker()
        self.__broker.setCommission(backtesting.TradePercentage(0.0005))
        self.__instrument = instrument
        self.__position = None

        # 如果想用修正后的收盘价,也就是股票数据csv文件中的Adj Close这一列的数据,那么需要使用这一行配置
        # self.setUseAdjustedValues(True)
        self.__k = 0.08
        self.__bars = feed[self.__instrument]
        self.__dual = Dual(self.__bars)
Esempio n. 9
0
    def __init__(self, feed, posMax, capital):
        myBroker = broker.Broker(capital, feed, broker.TradePercentage(0.002))
        myBroker.setAllowNegativeCash(True)
        myBroker.getFillStrategy().setVolumeLimit(None)

        super(MyBenchmark, self).__init__(feed, myBroker)

        self._feed = feed
        self._session = 0
        self._liquidity = 0.05
        self._posMax = posMax
        self._positions = {}

        self.startDateTime = None
        self.endDateTime = None

        self.setUseAdjustedValues(True)
Esempio n. 10
0
    def __init__(self, feed, delay):
        myBroker = backtesting.Broker(1000000, feed, backtesting.TradePercentage(0.002))
        myBroker.setAllowNegativeCash(True)
        myBroker.getFillStrategy().setVolumeLimit(None)

        super(MyBenchmark, self).__init__(feed, myBroker)

        self._delay = delay
        self._feed = feed
        self._session = 0
        self._liquidity = 0.05
        self._posMax = len(feed.getRegisteredInstruments())
        self._posLong = {}
        self._posShort = {}
        self.startDateTime = None
        self.endDateTime = None

        self.setUseAdjustedValues(True)
Esempio n. 11
0
    def __init__(self, feed, instrument, parametres, cash=10, comission=0.002):
        broker = backtesting.Broker(cash, feed, backtesting.TradePercentage(comission))
        strategy.BaseStrategy.__init__(self, feed, broker)        
        
        self.numOrder = 0
        self.okOrder = 0
        self.exitOrder = 0
        self.s1 = self.s2 = self.s3 = 1
        self.p1 = self.p2 = self.p3 = 1
        self.windowTrust = parametres[3]

        # SMA
        self.__instrument = instrument
        self.__position = None
        self.__Close = feed[instrument].getCloseDataSeries()                
        self.__sma = ma.SMA(self.__Close, parametres[0])                
        
        # Bbands
        self.__instrument = instrument
        self.__bbands = bollinger.BollingerBands(feed[instrument].getCloseDataSeries(), parametres[1], 2)

        # Vwap
        self.__instrument = instrument
        self.__vwap = vwap.VWAP(feed[instrument], parametres[2])
Esempio n. 12
0
	def testTradePercentage(self):
		comm = backtesting.TradePercentage(0.1)
		self.assertEqual(comm.calculate(None, 1, 1), 0.1)
		self.assertEqual(comm.calculate(None, 2, 2), 0.4)
Esempio n. 13
0
    def __init__(self, feed, instrument, vwapWindowSize, cash=10, comission=0.002):
        broker = backtesting.Broker(cash, feed, backtesting.TradePercentage(comission))
        strategy.BaseStrategy.__init__(self, feed, broker)

        self.__instrument = instrument
        self.__vwap = vwap.VWAP(feed[instrument], vwapWindowSize)
Esempio n. 14
0
	def __init__(self, cash, barFeed, commission = None):
		if commission is None:
			commission = backtesting.TradePercentage(0.006)
		backtesting.Broker.__init__(self, cash, barFeed, commission)
Esempio n. 15
0
 def __init__(self, cash, barFeed, fee=0.001):
     commission = backtesting.TradePercentage(fee)
     backtesting.Broker.__init__(self, cash, barFeed, commission)
Esempio n. 16
0
 def __init__(self, cash, barFeed, fee=0.005):
     commission = backtesting.TradePercentage(fee)
     backtesting.Broker.__init__(self, cash, barFeed, commission)
     self.setAllowFractions(True)
Esempio n. 17
0
 def __init__(self, cash, barFeed, fee=common.DEFAULT_TAKER_FEE):
     assert common.INSTRUMENT_TOKEN and common.CASH_TOKEN
     commission = backtesting.TradePercentage(fee)
     super(BacktestingBroker, self).__init__(cash, barFeed, commission)
Esempio n. 18
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)
print "Average daily return: %.2f %%" % (stats.mean(retAnalyzer.getReturns()) *
                                         100)
Esempio n. 19
0
 def __init__(self, cash, barFeed, fee=0):
     commission = backtesting.TradePercentage(fee)
     super(BacktestingBroker, self).__init__(cash, barFeed, commission)