Quantopian's community platform is shutting down. Please read this post for more information and download your code.
Back to Community
TypeError with dict?

On Line 52 I'm getting " Runtime exception: TypeError: 'type' object has no attribute '__getitem__' "
and I have no Idea why.

import talib

def initialize(context):  
    set_symbol_lookup_date('2013-01-14')  
    context.stocks = symbols('aapl', 'amzn', 'armh', 'atvi', 'csco', 'crm', 'ebay', 'ea', 'fb', 'hpq', 'ibm', 'intc', 'lnkd', 'msft', 'nflx', 'nvda', 'orcl', 'pcln', 'qcom', 'bbry', 'sap', 't', 'symc', 'vz', 'yhoo')  
    set_benchmark(symbol('qqq'))  
    set_commission(commission.PerTrade(cost=4.75))  
    context.date = None  
    context.freeCash = 100000  
    context.startCount = 25  
    context.stockCount = 0  
    context.bottomed = None  
    context.rising = None  
    context.peaked = None  
    context.falling = None  
    dict = {'AAPL': 'falling', 'AMZN': 'falling', 'ARMH': 'falling', 'ATVI': 'falling', 'BBRY': 'falling', 'CSCO': 'falling', 'CRM': 'falling', 'EBAY': 'falling', 'EA': 'falling', 'FB': 'falling', 'HPQ': 'falling', 'IBM': 'falling', 'INTC': 'falling', 'LNKD': 'falling', 'MSFT': 'falling', 'NFLX': 'falling', 'NVDA': 'falling', 'ORCL': 'falling', 'PCLN': 'falling', 'QCOM': 'falling', 'SAP': 'falling', 'T': 'falling', 'SYMC': 'falling', 'VZ': 'falling', 'YHOO': 'falling'}  
def handle_data(context, data):  #Line 20  
    todays_date = get_datetime().date()  
    if todays_date==context.date:  
        return  
    for stock in context.stocks:  
        hist100 = history(bar_count=100, frequency='1d', field='price')  
        series100 = hist100[stock]  
        ema_result100 = talib.EMA(series100, timeperiod=100)  
        ema_result20 = talib.EMA(series100, timeperiod=20)  
        ema_result5 = talib.EMA(series100, timeperiod=5)  
        ema100 = ema_result100[-1]  
        ema20 = ema_result20[-1]  
        ema5 = ema_result5[-1]  
        lowerLimit = 0  
        upperLimit = 0  
        getCash(context,data) #Line40  
        if ema20 > ema100:  
            upperLimit = ema20  
            lowerLimit = ema100  
        else:  
            upperLimit = ema100  
            lowerLimit = ema20  
        if ema5 < lowerLimit and dict[str(stock.symbol)] == 'falling':  
            dict[str(stock.symbol)] = 'bottomed'  
        if ema5 > lowerLimit and ema5 < upperLimit and dict[str(stock.symbol)] == 'bottomed':                 #Line 52  
            dict[str(stock.symbol)] = 'rising'  
            order_value(stock, (context.freeCash/(context.stockCount-context.startCount)), style=LimitOrder(ema5*1.03))  
            context.stockCount += 1  
        if ema5 > upperLimit and dict[str(stock.symbol)] == 'rising':  
            dict[str(stock.symbol)] = 'peaked'  
        if ema5 > lowerLimit and ema5 < upperLimit and dict[str(stock.symbol)] == 'peaked': #Line 52  
            dict[str(stock.symbol)] = 'falling'  
            order_target(stock, 0, style=LimitOrder(ema5*(-1.03)))  
            context.stockCount += (-1)  
        getCash(context,data)  
        if context.portfolio.positions[stock].amount < 0:  
            context.shorts+=1  
    getCash(context,data)  
    record(Cash=context.freeCash)  
    record(Shorts=context.shorts)  
    context.shorts=0  
def getCash(context,data):  
    if context.portfolio.cash < (context.portfolio.portfolio_value-context.portfolio.positions_value):  
        context.freeCash = context.portfolio.cash-5  
    else:  
        context.freeCash = (context.portfolio.portfolio_value-context.portfolio.positions_value)-5  
2 responses

You are shadowing the builtin name dict with your local variable. You are also running into a scope issue.

The shadowing issue is that dict is a builtin name that refers to the dict type (the class that dictionaries are instances of). When you say 'dict = {'a': 1, ...}', you are rebinding that name to your instance. A pythonic way to avoid this is to suffix your variable with an underscore like: 'dict_'. Alternatively, you could name the object based on what is in the dict like 'states' or something to indicate what the structure holds.

The second issue is that 'dict' (which I will refer to as 'dict_' from now on to avoid the confusion) is defined as a local variable in your initialize function. When you try to reference that object in handle_data, you get this error because the name 'dict' now refers to the builtin type object. To fix this, you can store 'dict_' in context in your initialize function like:

context.dict_ = {...} 

## or ###

context.states = {...}  

When you try to reference this object, you can just look it up off of context like:
context.dict_[str(stock.symbol)]

Hopefully this helps ^_^

Disclaimer

The material on this website is provided for informational purposes only and does not constitute an offer to sell, a solicitation to buy, or a recommendation or endorsement for any security or strategy, nor does it constitute an offer to provide investment advisory services by Quantopian. In addition, the material offers no opinion with respect to the suitability of any security or specific investment. No information contained herein should be regarded as a suggestion to engage in or refrain from any investment-related course of action as none of Quantopian nor any of its affiliates is undertaking to provide investment advice, act as an adviser to any plan or entity subject to the Employee Retirement Income Security Act of 1974, as amended, individual retirement account or individual retirement annuity, or give advice in a fiduciary capacity with respect to the materials presented herein. If you are an individual retirement or other investor, contact your financial advisor or other fiduciary unrelated to Quantopian about whether any given investment idea, strategy, product or service described herein may be appropriate for your circumstances. All investments involve risk, including loss of principal. Quantopian makes no guarantees as to the accuracy or completeness of the views expressed in the website. The views are subject to change, and may have become unreliable for various reasons, including changes in market conditions or economic circumstances.

Thank you! I typically code Java so my first instinct would be more like-

dict myDict = {key: value,...};  
if(myDict(key).equalsIgnoreCase("whatever")){  
//do stuff
}

The transition to python is a work in progress.