Exemple #1
0
 def __init__(self, barFeed, cash=1000000):
     broker_ = BacktestingFuturesBroker(cash, barFeed)
     Strategy.__init__(self, barFeed, cash, broker_)
     self._position = None
     self._started = False
     self._db = InstrumentDb.Instance()
     self._riskfactor = 0.002
Exemple #2
0
    def __init__(self,
                 sectorMap,
                 modelType=None,
                 cash=1000000,
                 tradeStart=None,
                 compounding=True,
                 positionsFile=None,
                 equityFile=None,
                 returnsFile=None,
                 summaryFile=None,
                 parms=None):

        self._runGroups = {}
        self._startingCash = cash

        self._db = InstrumentDb.Instance()
        self._feed = MultiFeed()
        self._broker = BacktestingFuturesBroker(
            cash, self._feed, commission=FuturesCommission(2.50))
        show = True
        for sec in sectorMap:
            for sym in sectorMap[sec]:
                self._feed.register_feed(Feed(self._db.get(sym)))

            # if desired can instantiate a strategy per symbol - may actually
            # want to think about this as a default behavior.  The only thing
            # impacted is reporting of sector results
            # strategySymbols = { sym }
            # rgkey = '%s-%s' % (sec, sym)
            strategySymbols = sectorMap[sec]
            rgkey = sec
            if not modelType:
                modelType = 'breakout'

            strategy = StrategyFactory.create(modelType,
                                              self._feed,
                                              symbols=strategySymbols,
                                              broker=self._broker,
                                              cash=cash,
                                              compounding=compounding,
                                              parms=parms)

            self._runGroups[rgkey] = InstrumentedStrategy(strategy)
            if show:
                show = False
                strategy.showParms()

        self._trading = False
        self._posfile = self.__openFileorNull(positionsFile)
        self._equityfile = self.__openFileorNull(equityFile)
        self._returnsfile = self.__openFileorNull(returnsFile)
        self._summaryfile = self.__openFileorNull(summaryFile)

        self._dd = DrawDown()
        self._dd.attached(self)
        self._positionAlerts = []
Exemple #3
0
 def setUp(self):
     manifest = '%s/data/manifest1.csv' % os.path.dirname(__file__)
     self._db = InstrumentDb.Instance()
     self._db.load(manifest)
     self._feed = Feed(self._db.get('AC'))
     self._feed.insert(talibfunc.SMA('SMA50', self._feed, 50))
     self._feed.insert(talibfunc.SMA('SMA100', self._feed, 100))
     self._feed.insert(talibfunc.MAX('MAX50', self._feed, 50))
     self._feed.insert(talibfunc.MIN('MIN50', self._feed, 50))
     self._feed.insert(talibfunc.ATR('ATR10', self._feed, 10))
Exemple #4
0
 def testMarketOrder(self):
     self._placed_markorder = False
     mf = MultiFeed()
     mf.register_feed(Feed(InstrumentDb.Instance().get('AC')))
     self._broker = BacktestingFuturesBroker(1000000, mf)
     mf.subscribe(self.on_bars_1)
     self._broker.getOrderUpdatedEvent().subscribe(self.on_order_update_1)
     mf.start()
     self.assertEqual(self._broker.getCash(), 1000015.0)
     self.assertEqual(self._broker.calc_margin(), 160000.0)
Exemple #5
0
 def testShortEntry(self):
     self._placed_markorder = False
     mf = MultiFeed()
     mf.register_feed(Feed(InstrumentDb.Instance().get('CT')))
     self._broker = BacktestingFuturesBroker(1000000, mf)
     mf.subscribe(self.on_bars_3)
     self._broker.getOrderUpdatedEvent().subscribe(self.on_order_update_3)
     mf.start()
     self.assertAlmostEqual(self._broker.getCash(), 1119750.0, places=2)
     self.assertEqual(self._broker.calc_margin(), 800000.0)
Exemple #6
0
 def testMarketOrderMarginCall(self):
     self._placed_markorder = False
     mf = MultiFeed()
     mf.register_feed(Feed(InstrumentDb.Instance().get('CT')))
     self._broker = BacktestingFuturesBroker(1000000, mf)
     mf.subscribe(self.on_bars_2)
     self._broker.getOrderUpdatedEvent().subscribe(self.on_order_update_2)
     with self.assertRaisesRegexp(Exception, "Margin Call"):
         mf.start()
     self.assertAlmostEqual(self._broker.getCash(), 214000.0, places=2)
     self.assertEqual(self._broker.calc_margin(), 800000.0)
Exemple #7
0
 def __init__(self, cash, barFeed, commission=None):
     '''
     Constructor.
     
     :param number cash: The initial amount of cash.
     :param MultiFeed barFeed: The bar feed that will provide the bars.
     :param Commission commission: An object responsible for calculating order commissions.
     
     :raises: AssertionError if cash is a negative number
     '''
     BacktestingBroker.__init__(self, cash, barFeed, commission)
     self._last_marktomarket = {}
     self._db = InstrumentDb.Instance()
Exemple #8
0
    def testBasic(self):
        manifest = '%s/data/manifest.csv' % os.path.dirname(__file__)

        idb = InstrumentDb.Instance()
        idb.load(manifest)
        self.assertEqual(idb.get_symbols(),
                         ['AC', 'C', 'CT', 'LB', 'LC', 'LH', 'O', 'RR'])
        self.assertEqual(idb.get('CT').point_value(), 50)
        self.assertEqual(idb.get('C').currency(), 'USD')
        self.assertEqual(idb.get('C').description(), 'Corn')
        self.assertEqual(idb.get('LB').exchange(), 'CME')
        self.assertEqual(idb.get('LC').initial_margin(), 1350.0)
        self.assertEqual(idb.get('LH').maint_margin(), 1050.0)
        self.assertEqual(idb.get('O').sector(), 'Agricultural')
Exemple #9
0
    def run_hedgeit(self):
        manifest = 'data/future.csv'
        sectormap = json.load(open('examples/clenow-best40.json'))
    
        feedStart = datetime.datetime(1999,1,1)
        tradeStart = datetime.datetime(2000,1,1)
        tradeEnd = datetime.datetime(2013,12,31)
    
        InstrumentDb.Instance().load(manifest)
            
        plog = 'positions.csv'
        elog = 'equity.csv'
        rlog = 'returns.csv'
        slog = 'summary.csv'

        parms = { 'riskFactor' : 0.004 }
        
        ctrl = Controller(sectormap, 
                          modelType = 'breakout',
                          cash = 250000,
                          tradeStart = tradeStart,
                          compounding = False,
                          positionsFile = plog, 
                          equityFile = elog, 
                          returnsFile = rlog,
                          summaryFile = slog,
                          parms = parms
                          )
        
        ctrl.run(feedStart, tradeStart, tradeEnd)
    
        ctrl.writeAllTrades('trades.csv')        
        ctrl.writeTSSBTrades('tssb')
        ctrl.writePositionAlerts('alerts.csv')
        
        self._alerts = sorted(ctrl.get_position_alerts(), key=lambda x: x.datetime, reverse=True)

        Log.info('There are %d position updates' % (len(self._alerts)))                
Exemple #10
0
    def __init__(self, barFeed, symbols = None, broker = None, cash = 1000000,\
                 compounding = True, parms = None):
        self._parms = self.defaultParms()
        if parms:
            self._parms.update(parms)

        if broker is None:
            broker = BacktestingFuturesBroker(
                cash, barFeed, commission=FuturesCommission(2.50))
        Strategy.__init__(self, barFeed, cash, broker)
        if symbols is None:
            self._symbols = barFeed.symbols()
        else:
            self._symbols = symbols
        self._barFeed = barFeed
        self._longpositions = {}
        self._shortpositions = {}
        self._started = {}
        for sym in self._symbols:
            feed = self._barFeed.get_feed(sym)
            self._started[sym] = False
            feed.insert(ATR(name='atr', period=self._parms['atrPeriod']))

        self._db = InstrumentDb.Instance()

        self._riskfactor = self._parms['riskFactor']

        self._tradeHigh = {}
        self._tradeLow = {}

        self.prep_bar_feed()
        self._startingCash = cash
        self._compounding = compounding
        self._stop = self._parms['stop']
        self._limit = self._parms['limit']
        self._intraday = self._parms['intradayStop']
        self._dynamic = self._parms['dynamicStop']
Exemple #11
0
 def __init__(self):
     self.__posTrackers = {}
     self.reset(None)
     self._db = InstrumentDb.Instance()
Exemple #12
0
 def setUp(self):
     manifest = '%s/data/manifest.csv' % os.path.dirname(__file__)        
     InstrumentDb.Instance().load(manifest)
Exemple #13
0
 def setUp(self):
     # we are using a special data set that triggers a trade on the last bar
     manifest = '%s/data/manifest2.csv' % os.path.dirname(__file__)
     self._db = InstrumentDb.Instance()
     self._db.load(manifest)
Exemple #14
0
def main(argv=None):
    try:
        opts, args = getopt.getopt(sys.argv[1:], "hc:p:t:g",
                                   ["tssb=", "dump="])
    except getopt.GetoptError as err:
        # print help information and exit:
        print str(err)  # will print something like "option -a not recognized"
        usage()
        sys.exit(2)

    cash = 1000000
    type_ = 'breakout'
    compounding = True
    tssb = None
    parms = None
    dump = None
    for o, a in opts:
        if o == "-c":
            cash = float(a)
            Log.info('Setting initial cash position to: %0.2f' % cash)
        elif o == "-p":
            parms = parseParmString(a)
            Log.info('Using model parms: %s' % parms)
        elif o == "-t":
            type_ = a
            Log.info('Using model %s' % type_)
        elif o == "-g":
            compounding = False
            Log.info('Compounding disabled')
        elif o == "--tssb":
            tssb = a
            Log.info('Writing tssb files with base %s' % tssb)
        elif o == "--dump":
            dump = a
            Log.info('Will output data feed to %s.csv' % dump)
        else:
            usage()
            return

    if len(args) != 5:
        Log.error('Not enough arguments to backtest!')
        usage()
        sys.exit(1)

    manifest = args[0]
    sectormap = json.load(open(args[1]))

    feedStart = datetime.strptime(args[2], '%Y-%m-%d')
    tradeStart = datetime.strptime(args[3], '%Y-%m-%d')
    tradeEnd = datetime.strptime(args[4], '%Y-%m-%d')

    InstrumentDb.Instance().load(manifest)

    plog = 'positions.csv'
    elog = 'equity.csv'
    rlog = 'returns.csv'
    slog = 'summary.csv'

    ctrl = Controller(sectormap,
                      modelType=type_,
                      cash=cash,
                      tradeStart=tradeStart,
                      compounding=compounding,
                      positionsFile=plog,
                      equityFile=elog,
                      returnsFile=rlog,
                      summaryFile=slog,
                      parms=parms)
    ctrl.run(feedStart, tradeStart, tradeEnd)
    if dump:
        ctrl.dumpFeed(dump)

    tlog = 'trades.csv'
    ctrl.writeAllTrades(tlog)
    if tssb:
        ctrl.writeTSSBTrades(tssb)

    alog = 'alerts.csv'
    ctrl.writePositionAlerts(alog)

    Log.info('Net return     :  %0.1f%%' % (ctrl.net_return() * 100.0))
    Log.info('Max drawdown   : -%0.1f%%' %
             (ctrl.drawdown().getMaxDrawDown() * 100.0))
Exemple #15
0
 def setUp(self):
     manifest = '%s/data/manifest.csv' % os.path.dirname(__file__)
     self._db = InstrumentDb.Instance()
     self._db.load(manifest)
     self._feed = Feed(self._db.get('AC'))