0

I'm using pyalgotrade to create a trading strategy. I'm going through a list of tickers(testlist) and adding them to a dictionary(list_large{}) alongside their score which I'm getting using a get_score function. My latest problem is that each ticker in the dictionary(list_large{}) is getting the same score. Any idea why?

Code:

from pyalgotrade import strategy
from pyalgotrade.tools import yahoofinance
import numpy as np
import pandas as pd
from collections import OrderedDict

from pyalgotrade.technical import ma
from talib import MA_Type
import talib

smaPeriod = 10
testlist = ['aapl','ddd','gg','z']

class MyStrategy(strategy.BacktestingStrategy):
    def __init__(self, feed, instrument):
        super(MyStrategy, self).__init__(feed, 1000)
        self.__position = [] 
        self.__instrument = instrument
        self.setUseAdjustedValues(True)
        self.__prices = feed[instrument].getPriceDataSeries()
        self.__sma = ma.SMA(feed[instrument].getPriceDataSeries(), smaPeriod)

    def get_score(self,slope):
        MA_Score = self.__sma[-1] * slope
        return MA_Score

    def onBars(self, bars): 

        global bar 
        bar = bars[self.__instrument]

        slope = 8

        for instrument in bars.getInstruments():

            list_large = {}
            for tickers in testlist: #replace with real list when ready
                list_large.update({tickers : self.get_score(slope)}) 

            organized_list = OrderedDict(sorted(list_large.items(), key=lambda t: -t[1]))#organize the list from highest to lowest score

         print list_large


def run_strategy(inst):
    # Load the yahoo feed from the CSV file

    feed = yahoofinance.build_feed([inst],2015,2016, ".") # feed = yahoofinance.build_feed([inst],2015,2016, ".")

    # Evaluate the strategy with the feed.
    myStrategy = MyStrategy(feed, inst)
    myStrategy.run()
    print "Final portfolio value: $%.2f" % myStrategy.getBroker().getEquity()


def main():
    instruments = ['ddd','msft']
    for inst in instruments:
            run_strategy(inst)


if __name__ == '__main__':
        main()
RageAgainstheMachine
  • 901
  • 2
  • 11
  • 28

1 Answers1

0

Check this code of the onBars() function:

slope = 8    # <---- value of slope = 8 

for instrument in bars.getInstruments():
    list_large = {}
    for tickers in testlist: #replace with real list when ready
        list_large.update({tickers : self.get_score(slope)}) 
        #       Updating dict of each ticker based on ^

Each time self.get_score(slope) is called, it returns the same value and hence, all the value of tickers hold the same value in dict

I do not know how you want to deal with slope and how you want to update it's value. But this logic can be simplified without using .update as:

list_large = {}
for tickers in testlist: 
    list_large[tickers] = self.get_score(slope)
     #           ^ Update value of `tickers` key
Moinuddin Quadri
  • 46,825
  • 13
  • 96
  • 126
  • Everytime self.get_score is called it should not return the same value. The function takes the self.__sma[-1] and multiplies it by the slope...If each ticker has a different moving average, shouldn't the values put in the dictionary be different? I'm a bit confused... – RageAgainstheMachine Nov 26 '16 at 19:59
  • @RageAgainstheMachine: What is your understanding of `self.__sma[-1] * slope`? It takes the last entry from `self.__sma` and multiply it with `slope`. Won't it be same everytime? – Moinuddin Quadri Nov 26 '16 at 20:02
  • I was under the impression that it would take the most recent sma but I thought I had written the code in a way that it would take the most recent sma for each individual ticker in the list. How would I make this work? – RageAgainstheMachine Nov 26 '16 at 20:10