Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I have the following code where I'm trying to get the values in an array by the name I set.

import datetime
import numpy as np
import matplotlib.finance as finance
import matplotlib.mlab as mlab

def get_pxing(my_tickers):
    dt = np.dtype([('sym', np.str_, 6), ('adj_close', np.float32)])
    close_px = []
    for ticker in my_tickers:
    # a numpy record array with fields: date, open, high, low, close, volume, adj_close)
        fh = finance.fetch_historical_yahoo(ticker, startdate, enddate)
        r = mlab.csv2rec(fh)    
        fh.close()
        prices = np.array((ticker, r.adj_close), dtype=dt)
        close_px.append(prices)
    return close_px

enddate = startdate = datetime.date.today() - datetime.timedelta(1)

my_tickers = np.genfromtxt('./stocklist.csv', delimiter = ",", dtype=None, names=True)

data = get_pxing(my_tickers["ticker"])
print data

This works fine but if I try

print data['sym'] 

I get:

Traceback (most recent call last):
  File "stockyield.py", line 26, in <module>
    print data['sym']
TypeError: list indices must be integers, not str

Perhaps I've converted my array incorretly using the close_px.append, however, but I cannot figure out how to use the np.append as I always get an array mismatch.

My input csv file looks like:

ticker, holding
T, 100
F, 200

Any suggestions on best approach?

share|improve this question
 
data['sym'] would index a dictionary for an entry with key 'sym'. The data structure you have is a list. Figure out where the data you want is (perhaps by using data.index()) –  aestrivex Apr 5 at 14:31
 
get_pxing returns a list of arrays (close_px), not a numpy array. –  Warren Weckesser Apr 5 at 14:35

1 Answer

As the comments say, it seems you are appending a numpy array to a list of arrays. You really want to make a list of tuples, then convert the list of tuples into an array.

Try something like this (the changed lines have comments)

def get_pxing(my_tickers):
    dt = np.dtype([('sym', np.str_, 6), ('adj_close', np.float32)])
    close_px = []
    for ticker in my_tickers:
    # a numpy record array with fields: date, open, high, low, close, volume, adj_close)
        fh = finance.fetch_historical_yahoo(ticker, startdate, enddate)
        r = mlab.csv2rec(fh)    
        fh.close()
        prices = (ticker, r.adj_close)   # append a tuple to your list instead of an array
        close_px.append(prices)
    return np.array(close_px, dtype=dt)  # make the list of tuples into an array with dtype dt
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.