Пример #1
0
    def testCliDonchianAlgorithm2014(self):
        api = PytradeApi(dbfilepah=self.db)
        api.reinitializeUser(username=self.username, cash=self.initialCash)
        tradingAlgorithmGenerator = lambda feed, broker: DonchianTradingAlgorithm(feed, broker, 9, 26, 0.05)

        feed = DynamicFeed(self.db, self.codes, maxLen=self.maxLen)
        days = feed.getAllDays()
        for i in range(len(days)):
            day = days[i]
            cli = PytradeCli(dbfilepah=self.db, date=day, maxlen=self.maxLen, codes=self.codes, tradingAlgorithmGenerator=tradingAlgorithmGenerator)
            orders = cli.executeAnalysis()

            if i == (len(days) - 1):
                continue

            nextDay = days[i+1]
            for order in orders:
                open = cli.getLastValuesForInstrument(order.getInstrument(), nextDay)[1]

                if not cli.confirmOrder(orderId=order.getId(), quantity=order.getQuantity(), price=open, commission=10,
                                        date=nextDay):
                    cli.cancelOrder(order.getId())
            cli.save()

        maxlen=(datetime.datetime.now() - datetime.datetime(2014, 12, 1)).days
        cli = PytradeCli(dbfilepah=self.db, maxlen=maxlen)
        self.assertEqual(cli.getAccountInfo()[1], 36922.16)
Пример #2
0
    def testCliDonchianAlgorithmWithSpecificDates(self):
        api = PytradeApi(dbfilepah=self.db)
        api.reinitializeUser(username=self.username, cash=self.initialCash)
        tradingAlgorithmGenerator = lambda feed, broker: DonchianTradingAlgorithm(feed, broker, 9, 26, 0.05)

        utc = pytz.utc
        specificdays = [
            utc.localize(datetime.datetime(2014, 2, 7)),
            utc.localize(datetime.datetime(2014, 2, 11)),
            utc.localize(datetime.datetime(2014, 9, 18)),
            utc.localize(datetime.datetime(2014, 10, 23)),
            utc.localize(datetime.datetime(2014, 10, 28)),
            utc.localize(datetime.datetime(2014, 12, 29))]
        feed = DynamicFeed(self.db, self.codes, maxLen=self.maxLen)
        alldays = feed.getAllDays()
        for day in specificdays:
            cli = PytradeCli(dbfilepah=self.db, date=day, maxlen=self.maxLen, codes=self.codes,
                             tradingAlgorithmGenerator=tradingAlgorithmGenerator)
            orders = cli.executeAnalysis()

            nextDay = alldays[alldays.index(day) + 1]
            for order in orders:
                open = cli.getLastValuesForInstrument(order.getInstrument(), nextDay)[1]

                if not cli.confirmOrder(orderId=order.getId(), quantity=order.getQuantity(), price=open, commission=10,
                                        date=nextDay):
                    cli.cancelOrder(order.getId())
            cli.save()

        maxlen = (datetime.datetime.now() - datetime.datetime(2014, 12, 1)).days
        cli = PytradeCli(dbfilepah=self.db, maxlen=maxlen)
        self.assertEqual(cli.getAccountInfo()[1], 36922.16)
Пример #3
0
    def testApiDonchianAlgorithm2014WithSQLiteDataProvider(self):
        feed = DynamicFeed(self.db, self.codes, maxLen=self.maxLen)
        days = feed.getAllDays()

        api = PytradeApi(dbfilepah=self.db)
        api.reinitializeUser(username=self.username, cash=self.initialCash)
        tradingAlgorithmGenerator = lambda feed, broker: DonchianTradingAlgorithm(feed, broker, self.donchianEntry, self.donchianExit, self.riskFactor)

        for i in range(len(days)):
            day = days[i]
            api = PytradeApi(dbfilepah=self.db, username=self.username, tradingAlgorithmGenerator=tradingAlgorithmGenerator, codes=None, date=day, maxlen=self.maxLen, debugmode=False)
            api.executeAnalysis()
            api.persistData()

            if i == (len(days) - 1):
                continue

            day = days[i + 1]
            api = PytradeApi(dbfilepah=self.db, username=self.username, tradingAlgorithmGenerator=tradingAlgorithmGenerator, codes=None, date=day, maxlen=self.maxLen, debugmode=False)

            for order in api.getActiveMarketOrders() + api.getStopOrdersToConfirm():
                bar = api.getCurrentBarForInstrument(order.getInstrument())
                if bar is None:
                    continue

                if not api.confirmOrder(order, bar.getDateTime(), order.getQuantity(), bar.getOpen(), 10):
                    api.cancelOrder(order)

            api.persistData()

        self.assertEqual(api.getEquity(), 36922.16)
Пример #4
0
    def __init__(self,
                 dbfilepah="/var/pytrade/sqlitedb",
                 googleFinanceDir="/var/pytrade/googlefinance",
                 date=datetime.now(),
                 maxlen=90,
                 codes=None,
                 tradingAlgorithmGenerator=None):
        if codes is None:
            codes = [
                "ABEV3", "BBAS3", "BBDC3", "BBDC4", "BBSE3", "BRAP4", "BRFS3",
                "BRKM5", "BRML3", "BVMF3", "CCRO3", "CIEL3", "CMIG4", "CPFE3",
                "CPLE6", "CSAN3", "CSNA3", "CTIP3", "CYRE3", "ECOR3", "EGIE3",
                "EMBR3", "ENBR3", "EQTL3", "ESTC3", "FIBR3", "GGBR4", "GOAU4",
                "HYPE3", "ITSA4", "ITUB4", "JBSS3", "KLBN11", "KROT3", "LAME4",
                "LREN3", "MRFG3", "MRVE3", "MULT3", "NATU3", "PCAR4", "PETR3",
                "PETR4", "QUAL3", "RADL3", "RENT3", "RUMO3", "SANB11", "SBSP3",
                "SMLE3", "SUZB5", "TIMP3", "UGPA3", "USIM5", "VALE3", "VALE5",
                "VIVT4", "WEGE3"
            ]

        if tradingAlgorithmGenerator is None:
            tradingAlgorithmGenerator = lambda feed, broker: DonchianTradingAlgorithm(
                feed, broker, 9, 26, 0.05)

        self.__date = date
        self.__username = '******'
        self.__api = PytradeApi(
            dbfilepah=dbfilepah,
            googleFinanceDir=googleFinanceDir,
            username=self.__username,
            tradingAlgorithmGenerator=tradingAlgorithmGenerator,
            codes=codes,
            date=self.__date,
            maxlen=maxlen,
            debugmode=False)
    def testBacktestingDonchianAlgorithm2014(self):
        backtest = GoogleFinanceBacktest(instruments=self.codes, initialCash=self.initialCash, year=2014, debugMode=False,
                                         csvStorage=self.csvStorage)
        backtest.attachAlgorithm(DonchianTradingAlgorithm(backtest.getFeed(), backtest.getBroker(), self.donchianEntry, self.donchianExit, self.riskFactor))
        backtest.run()

        self.assertEqual(backtest.getBroker().getEquity(), 36922.16)
Пример #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)
    def runDonchianAlgorithm(self, broker, feed, donchianEntry, donchianExit, riskFactor):
        strategy = TradingSystem(feed, broker, debugMode=False)
        strategy.setAlgorithm(DonchianTradingAlgorithm(feed, broker, donchianEntry, donchianExit, riskFactor))
        feed.dispatchWithoutIncrementingDate()
        feed.nextEvent()
        for order in broker.getActiveMarketOrders() + broker.getStopOrdersToConfirm():
            bar = broker.getCurrentBarForInstrument(order.getInstrument())
            if bar is None:
                continue

            if not broker.confirmOrder(order, bar):
                broker.cancelOrder(order)
Пример #8
0
    def testApiDonchianAlgorithmWithSpecificDatesAndSQLiteDataProvider(self):
        utc = pytz.utc
        specificdays = [
            utc.localize(datetime.datetime(2014, 2, 7)),
            utc.localize(datetime.datetime(2014, 2, 11)),
            utc.localize(datetime.datetime(2014, 9, 18)),
            utc.localize(datetime.datetime(2014, 10, 23)),
            utc.localize(datetime.datetime(2014, 10, 28)),
            utc.localize(datetime.datetime(2014, 12, 29))]

        feed = DynamicFeed(self.db, self.codes, maxLen=self.maxLen)
        alldays = feed.getAllDays()

        api = PytradeApi(dbfilepah=self.db)
        api.reinitializeUser(username=self.username, cash=self.initialCash)
        tradingAlgorithmGenerator = lambda feed, broker: DonchianTradingAlgorithm(feed, broker, self.donchianEntry,
                                                                                  self.donchianExit, self.riskFactor)
        for day in specificdays:
            api = PytradeApi(dbfilepah=self.db, username=self.username, tradingAlgorithmGenerator=tradingAlgorithmGenerator, codes=None, date=day,
                             maxlen=self.maxLen, debugmode=False)
            api.executeAnalysis()
            api.persistData()

            index = alldays.index(day)
            day = alldays[index+1]
            api = PytradeApi(dbfilepah=self.db, username=self.username, tradingAlgorithmGenerator=tradingAlgorithmGenerator, codes=None, date=day,
                             maxlen=self.maxLen, debugmode=False)

            for order in api.getActiveMarketOrders() + api.getStopOrdersToConfirm():
                bar = api.getCurrentBarForInstrument(order.getInstrument())
                if bar is None:
                    continue

                if not api.confirmOrder(order, bar.getDateTime(), order.getQuantity(), bar.getOpen(), 10):
                    api.cancelOrder(order)

            api.persistData()

        self.assertEqual(api.getEquity(), 36922.16)
Пример #9
0
#                         row["Volume"] == "-"
# instruments = ["PETR4", "PETR3"]
# googleFeed = googlefinance.build_feed(codes, 2014, 2014, storage="./googlefinance", skipErrors=True,
#                                       rowFilter=rowFilter)
db = "./sqliteddb"
# feed = DynamicFeed    (db, codes, maxLen=10)
# feed.getDatabase().addBarsFromFeed(googleFeed)
################################################################################################
maxLen=int(26*1.4)
feed = DynamicFeed(db, codes, maxLen=maxLen)
days =  feed.getAllDays()

username="******"
api = pytradeapi.PytradeApi(dbfilepah=db)
api.reinitializeUser(username=username, cash=10000)
tradingAlgorithmGenerator = lambda feed, broker: DonchianTradingAlgorithm(feed, broker, 9, 26, 0.05)

# utc = pytz.utc
# days = [
#             utc.localize(datetime.datetime(2014, 2, 7)),
#             utc.localize(datetime.datetime(2014, 2, 11))]


for i in range(len(days)):
    day = days[i]
    api = pytradeapi.PytradeApi(dbfilepah=db, username=username, tradingAlgorithmGenerator=tradingAlgorithmGenerator, codes=None, date=day, maxlen=maxLen, debugmode=False)
    api.executeAnalysis()
    api.persistData()

    if i == (len(days)-1):
        continue