Beispiel #1
0
import os, sys, random

import numpy as np
import getStocks as gs
import utils as u
import indicators as ind
import tradeReport as tr

#symbol = "WMT"
symbol = "NFLX"
# symbol = "F"
stock = gs.getStock(symbol, (2011, 6, 1), (2015, 6, 1)) # for calculating
quotes = u.dictToList(stock) # [day,o,h,l,c]

timesclose = quotes[:,[0,4]]
emas = []
for i in [1,2]: emas.append( ind.ematimes(timesclose,10*i) )

crossovertimes = ind.crossovertimes(emas)
dCrossovers = {} # turn into dict for fast lookup
for time,rising in crossovertimes: dCrossovers[time] = rising


# CROSSOVER STRATEGY
price = 0
ledger = tr.Ledger(1000)
for quote in quotes:
    day,price,h,l,c = quote
    if(day in dCrossovers): 
        rising = dCrossovers[day]
Beispiel #2
0
    def doBenchmark(self, params={}, progressBar=True, userOnly=False, debug=False):
        self.cleanVars()

        if self.performChecks():
            print "[BT] Can't benchmark"
            return

        for isymbol, symbol in enumerate(self.symbols):
            self.isymbol = isymbol
            if progressBar:
                self.drawProgressBar()

            stock = gs.getStock(symbol, self.d0, self.d2)
            quotes = u.dictToList(stock)  # [day,o,h,l,c]
            if len(quotes) < 15:
                continue

            try:
                dBuy, dSell = self.strategy(quotes, self.d1, self.d2, params)
            except Exception as e:
                print "[BT] Problem running user strategy"
                print e
                continue

            if len(dBuy.keys()) < 1:
                continue  # pointless if we don't buy
            if len(dSell.keys()) < 1:
                continue  # pointless if we don't sell -- then it's just BAH

            try:
                self.report[symbol] = {}
                self.report[symbol]["ndays"] = len(quotes)

                # USER STRATEGY
                price = 0
                ledger = tr.Ledger(self.money)
                for quote in quotes:
                    day, price, h, l, c = quote
                    if day in dSell:
                        ledger.sellStock(symbol, day, price, fraction=dSell[day])
                    elif day in dBuy:
                        ledger.buyStock(symbol, day, price)
                ledger.sellStock(symbol, day, price)  # sell outstanding shares to finish up
                self.report[symbol]["user"] = [
                    ledger.getProfit(),
                    0.0,
                    ledger.getNumTrades(),
                    ledger.getWinPercent(),
                    ledger.getAvgWinProfitPercent(),
                    ledger.getAvgLossProfitPercent(),
                ]

                if not userOnly:
                    # RANDOM STRATEGY
                    profits = []
                    for i in range(100):
                        price = 0
                        ledgerRand = tr.Ledger(self.money)
                        days = quotes[:, 0]
                        np.random.shuffle(days)
                        # want to do a random trade on avg every 3-10 days
                        # so we take the first #days/rand(3,10) random days, then sort them
                        days = sorted(days[: len(days) // random.randint(3, 10)])
                        days = days[len(days) % 2 :]  # even number of entries, so we always sell what we buy
                        buy = True  # buy initially
                        for day in days:
                            if buy:
                                ledgerRand.buyStock(symbol, day, price=stock["days"][day]["c"])
                            else:
                                ledgerRand.sellStock(symbol, day, price=stock["days"][day]["c"])
                            buy = not buy  # alternate between buy and sell
                        profits.append(ledgerRand.getProfit())
                    profits = np.array(profits)

                    # BUY AND HOLD
                    ledgerBAH = tr.Ledger(self.money)  # buy and hold
                    ledgerBAH.buyStock(symbol, quotes[0][0], quotes[0][4])
                    ledgerBAH.sellStock(symbol, quotes[-1][0], quotes[-1][4])

                    self.report[symbol]["rand"] = [
                        round(np.mean(profits), 2),
                        round(np.std(profits)),
                        ledgerRand.getNumTrades(),
                        ledgerRand.getWinPercent(),
                        ledgerRand.getAvgWinProfitPercent(),
                        ledgerRand.getAvgLossProfitPercent(),
                    ]
                    self.report[symbol]["bah"] = [
                        ledgerBAH.getProfit(),
                        0.0,
                        ledgerBAH.getNumTrades(),
                        ledgerBAH.getWinPercent(),
                        ledgerBAH.getAvgWinProfitPercent(),
                        ledgerBAH.getAvgLossProfitPercent(),
                    ]

                    if debug:
                        ledger.printLedger()

            except Exception as e:
                print "[BT] Some other error"
                print e
                continue

        self.postBenchmark()
Beispiel #3
0
    def doBenchmark(self,
                    params={},
                    progressBar=True,
                    userOnly=False,
                    debug=False):
        self.cleanVars()

        if self.performChecks():
            print "[BT] Can't benchmark"
            return

        for isymbol, symbol in enumerate(self.symbols):
            self.isymbol = isymbol
            if (progressBar): self.drawProgressBar()

            stock = gs.getStock(symbol, self.d0, self.d2)
            quotes = u.dictToList(stock)  # [day,o,h,l,c]
            if (len(quotes) < 15): continue

            try:
                dBuy, dSell = self.strategy(quotes, self.d1, self.d2, params)
            except Exception as e:
                print "[BT] Problem running user strategy"
                print e
                continue

            if (len(dBuy.keys()) < 1): continue  # pointless if we don't buy
            if (len(dSell.keys()) < 1):
                continue  # pointless if we don't sell -- then it's just BAH

            try:
                self.report[symbol] = {}
                self.report[symbol]["ndays"] = len(quotes)

                # USER STRATEGY
                price = 0
                ledger = tr.Ledger(self.money)
                for quote in quotes:
                    day, price, h, l, c = quote
                    if (day in dSell):
                        ledger.sellStock(symbol,
                                         day,
                                         price,
                                         fraction=dSell[day])
                    elif (day in dBuy):
                        ledger.buyStock(symbol, day, price)
                ledger.sellStock(symbol, day,
                                 price)  # sell outstanding shares to finish up
                self.report[symbol]["user"] = [
                    ledger.getProfit(), 0.0,
                    ledger.getNumTrades(),
                    ledger.getWinPercent(),
                    ledger.getAvgWinProfitPercent(),
                    ledger.getAvgLossProfitPercent()
                ]

                if (not userOnly):
                    # RANDOM STRATEGY
                    profits = []
                    for i in range(100):
                        price = 0
                        ledgerRand = tr.Ledger(self.money)
                        days = quotes[:, 0]
                        np.random.shuffle(days)
                        # want to do a random trade on avg every 3-10 days
                        # so we take the first #days/rand(3,10) random days, then sort them
                        days = sorted(days[:len(days) //
                                           random.randint(3, 10)])
                        days = days[
                            len(days) %
                            2:]  # even number of entries, so we always sell what we buy
                        buy = True  # buy initially
                        for day in days:
                            if (buy):
                                ledgerRand.buyStock(
                                    symbol, day, price=stock["days"][day]['c'])
                            else:
                                ledgerRand.sellStock(
                                    symbol, day, price=stock["days"][day]['c'])
                            buy = not buy  # alternate between buy and sell
                        profits.append(ledgerRand.getProfit())
                    profits = np.array(profits)

                    # BUY AND HOLD
                    ledgerBAH = tr.Ledger(self.money)  # buy and hold
                    ledgerBAH.buyStock(symbol, quotes[0][0], quotes[0][4])
                    ledgerBAH.sellStock(symbol, quotes[-1][0], quotes[-1][4])

                    self.report[symbol]["rand"] = [
                        round(np.mean(profits), 2),
                        round(np.std(profits)),
                        ledgerRand.getNumTrades(),
                        ledgerRand.getWinPercent(),
                        ledgerRand.getAvgWinProfitPercent(),
                        ledgerRand.getAvgLossProfitPercent()
                    ]
                    self.report[symbol]["bah"] = [
                        ledgerBAH.getProfit(), 0.0,
                        ledgerBAH.getNumTrades(),
                        ledgerBAH.getWinPercent(),
                        ledgerBAH.getAvgWinProfitPercent(),
                        ledgerBAH.getAvgLossProfitPercent()
                    ]

                    if debug:
                        ledger.printLedger()

            except Exception as e:
                print "[BT] Some other error"
                print e
                continue

        self.postBenchmark()