Search code examples
pythonlistfor-loopfinance

List index giving wrong value?


import stockquotes
 

symbol_name = ['SPY', 'XOM', 'GLD']
for x in symbol_name:
    ticker = stockquotes.Stock(x)
    today_price = ticker.current_price
    print(x, 'Quote: ',today_price)
    

Output:

SPY Quote:  337.13
XOM Quote:  41.96
GLD Quote:  182.24

But when I try to get XOM's quote through the list's index I get GLD's quote instead.

print(symbol_name[1], today_price)

Output:

XOM 182.24

Any thoughts on how I can access each quote manually?


Solution

  • Keep the prices in a dictionary. Then access by the symbol name.

    import stockquotes
     
    
    symbol_name = ['SPY', 'XOM', 'GLD']
    data = {}
    for x in symbol_name:
        ticker = stockquotes.Stock(x)
        today_price = ticker.current_price
        data[x] = today_price
    
    print(data['XOM'])
    

    Output:

    41.96