コード例 #1
0
    def selectStocksToBuy(self,
                          maxNumberOfStocks,
                          date=False,
                          customTickerList=False,
                          genricParameters=[]):
        '''
        Selects which stocks to buy, and the proportion of funds to be allocated to each.
        maximumNumberOfStocks is the highest number of stocks the caller wants to select.
        Passing a date parameter will select stocks for the given date. Ommitting it will
        select stocks based on realtime data.
        Passing a customTickerList will only analyze tickers included in that list.

        Returns a list of in the following format: [ [Ticker1, RatioOfFundAllocation1], [Ticker2, RatioOfFundAllocation2], ... ] .
        All ratios will add up to 1.
        '''

        if (not date):
            raise ValueError(
                "Real time selection not availible for this selector")
        else:
            if (customTickerList):
                tickerList = customTickerList
            else:
                tickerList = database.getTickerList()

            stocksToConsider = self.filterStocksToConsider(tickerList, date)

            if (len(stocksToConsider) > maxNumberOfStocks):
                stocksToConsider = stocksToConsider[0:maxNumberOfStocks]
            else:
                pass

            numberOfStocks = len(stocksToConsider)
            stocksToBuy = [(i, 1 / numberOfStocks) for i in stocksToConsider]

            return stocksToBuy
コード例 #2
0
def runSimulation(account, dateRange, startingDeposit, selector, sampleSize=False, customTickerList=False, preloadToMemory=False, depositAmount=False, depositFrequency=False, comission=10, PrintToTerminal=True):
    '''
    Runs a single simulation. Saves results to a csv file.

    -Daterange must be a 2 element list, in the following format: [[<start date>], [<end date>]], date format = string "YYYY-MM-DD".
    -depositFrequency is how often (in days) to deposit funds into your trading account.
    -selector is a StockSelectionInterface object.
    -Passing a customTickerList will run the simulation using only the tickers included in the list.
    '''
    #Check for valid parameters
    if ((depositFrequency) and (not depositAmount)):
        raise ValueError("Deposit frequency set without deposit amount.")
    if ((depositAmount) and (not depositFrequency)):
        raise ValueError("Deposit amount set without deposit frequency.")

    #Instaniate objects
    if (PrintToTerminal):
        print("\nGetting tickers...")

    if (customTickerList):
        tickerList = customTickerList
    elif (sampleSize):
        tickerList = database.getTickerList(randomize=True, numberOfShuffles=2)[:sampleSize]
    else:
        tickerList = database.getTickerList()

    if (preloadToMemory):
        print("Preloading stock data to memory...")
        database.loadDatabaseToMemory(tickerList)

    #Set starting balance and comission
    account.depositFunds(startingDeposit)
    account.setCommision(comission)

    #Extract daterange
    startDate = dateRange[0]
    endDate = dateRange[1]

    #Progress bar header
    if (PrintToTerminal):
        print ("\nRuning Simulation...\n")
        print ("Selector: " + selector.getName())  #NOTE Don't forget to set your self.name property in you selector constructor
        print ("Daterange: "+startDate+" to "+endDate)
        print ("-------------------------------------------\n")
        sys.stdout.write("\r")
        sys.stdout.write("0.0%")
        sys.stdout.flush()

    daysSinceLastDeposit = 0

    #Begin simulation
    for date in utils.daterange(startDate, endDate):
        #Check if market is open
        if (utils.isWeekday(date)):
            #Selects which stocks to sell
            ownedStocks = account.getOwnedStocks()
            ownedTickers = []
            for ticker in ownedStocks:
                ownedTickers.append(ticker)

            stocksToSell = selector.selectStocksToSell(ownedTickers, date=date)
            #Sells stocks
            account.placeSellOrders(stocksToSell, date)

            #Selects which stocks to buy
            availibleFunds = account.getBalance()
            numberOfStocksToBuy = selector.numberOfStocksToBuy(availibleFunds)

            stocksToBuy = selector.selectStocksToBuy(numberOfStocksToBuy, date=date, customTickerList=tickerList)
            
            buyOrders = []

            for stock in stocksToBuy:
                ticker = stock[0]
                price = database.getDataframe(ticker, [date,date], ["Open"]).loc[date, "Open"]
                quantity = int((stock[1]*(availibleFunds-(len(stocksToBuy)*comission))) / price)
                if quantity>0:
                    buyOrders.append([ticker, quantity])

            #Buys stocks
            account.placeBuyOrders(buyOrders, date)

        if (depositFrequency):
            daysSinceLastDeposit += 1
            if (daysSinceLastDeposit == depositFrequency):
                account.depositFunds(depositAmount)
                daysSinceLastDeposit = 0

        #Progress bar
        if (PrintToTerminal):
            completed = utils.getDayDifference(startDate, date)
            totalToDo = utils.getDayDifference(startDate, endDate)
            percentage = int(float(completed*1000)/(totalToDo-1))/10.0
            sys.stdout.write("\r")
            sys.stdout.write(str(percentage)+"%")
            sys.stdout.flush()

    if (PrintToTerminal):
        print("\n")    
    #Save logs        
    account.saveHistory(selector.getName())
コード例 #3
0
    twoDayDiscreteMomentum = float(stockData["2D Discrete Moementum"])
    fiveDayDiscreteMomentum = float(stockData["5D Discrete Moementum"])

    if ((fiveDayDiscreteMomentum < 3) and (twoDayDiscreteMomentum > 0)):
        pass
    else:
        return False

    return ticker


if __name__ == '__main__':
    selector = MehSelector()
    date = "2018-06-14"
    numberOfStocks = 4000
    tickerList = database.getTickerList(randomize=True)[0:numberOfStocks]
    #tickerList = ["TSLA"]
    selectedStocks = selector.selectStocksToBuy(10, date, tickerList)
    print(selectedStocks)
    for selection in selectedStocks:
        ticker = selection[0]
        stockData = database.getDataframe(ticker,
                                          dataFields=[
                                              "Profit Speed",
                                              "2 Day Normalized Momentum",
                                              "5 Day Normalized Momentum",
                                              "2D Discrete Moementum",
                                              "5D Discrete Moementum"
                                          ],
                                          dateRange=[date, date])
        print(stockData)
コード例 #4
0
    def selectStocksToBuy(self, maxNumberOfStocks, date=False, customTickerList=False, genricParameters=[]):
        '''
        Selects which stocks to buy, and the proportion of funds to be allocated to each.
        maximumNumberOfStocks is the highest number of stocks the caller wants to select.
        Passing a date parameter will select stocks for the given date. Ommitting it will
        select stocks based on realtime data.
        Passing a customTickerList will only analyze tickers included in that list.

        Returns a list of in the following format: [ [Ticker1, RatioOfFundAllocation1], [Ticker2, RatioOfFundAllocation2], ... ] .
        All ratios will add up to 1.
        '''

        if (not date):
            raise ValueError("Real time selection not availible for this selector")
        else:
            if (customTickerList):
                tickerList = customTickerList
            else:
                tickerList = database.getTickerList()
            argList = []
            for ticker in tickerList:
                argList.append([ticker, date])

            processCount = multiprocessing.cpu_count()-1
            processPool = Pool(processCount)
            results = list(processPool.map(self.getProfitSpeed, argList))
            processPool.close()
            processPool.join()

            for i in range(len(results)-1, -1, -1):
                if (results[i]):
                    pass
                else:
                    del results[i]

            results = sorted(results)
            #print(results)
            
            randomnessFactor = 0.85  #Used to randomize selection so that the selector isn't perfect. 0 is perfect, 1 is completely random

            lengthOfResults = len(results)
            #print(lengthOfResults)
            
            indexesOfChosenStocks = []
            for i in range(0, maxNumberOfStocks, 1):
                if (lengthOfResults-len(indexesOfChosenStocks)>0):
                    #There are still stocks left to chose from
                    while (True):                     
                        indexToUse = randint(int(randomnessFactor*(lengthOfResults-1)), lengthOfResults-1)
                        if (indexToUse in indexesOfChosenStocks):
                            pass
                        else:
                            indexesOfChosenStocks.append(indexToUse)
                            break
                else:
                    #There are no more stocks left to select
                    break

            #print(indexesOfChosenStocks)
            stocksToConsider = []
            for index in indexesOfChosenStocks:
                stocksToConsider.append(results[index])
            
            randomRatios = list(np.random.dirichlet(np.ones(maxNumberOfStocks),size=1)[0])  #https://stackoverflow.com/questions/18659858/generating-a-list-of-random-numbers-summing-to-1
        
            stocksToBuy = []
            for i in range(0, len(stocksToConsider), 1):
                stocksToBuy.append([stocksToConsider[i][1], randomRatios[i]])

            return stocksToBuy