I am very new to Python and want to build a black box stock trading program that finds various correlations between stock’s rates of return and gives me a response such as buy, sell, hold, etc. I found a neat little easy to use Python module for retrieving stock data called ystockquote that pulls information from Yahoo! Finance. The module can be found at http://www.goldb.org/ystockquote.html.
One of its abilities is to output historical prices for a stock in the form ['Date', 'Open', 'High', 'Low', 'Close', 'Volume', 'Adj Clos']. I can give it a date range to do this and it gives me a nested list containing a single list with the above information this for each day.
My question is how to organize each of these separate data points (Date, Open, High, Low, etc.) into a structure that I can call upon later in my script and sort. I need this process to be easy to automate. What sorts of algorithms or data structures might I find useful?
You might be looking for a dictionary structure rather than a list:
Here I’ve nested a dictionary within each entry of the main “prices” dictionary. The first level of the dictionary takes the date as its key, and maps to a dictionary containing the price information for that date.
The second level of the dictionary uses the attribute names as keys, and maps to the attribute values themselves.
It seems that, for the
get_historical_pricesfunction you refer to, each day is output as an entry of the form[Date, Open, High, Low, Close, Volume, Adj_Clos]. If you want to construct a dictionary for a list of these entries, you’re gonna need to do three things:First, you’ll need to index each entry to separate out the
Datefrom the other elements, since that is what you’ll be using to index the first dimension of your dict. You can get the first element withentry[0]and the remaining elements withentry[1:].Second since you want to associate each of the other elements with a specific key, you should make a list of those keys in the same order as the data elements are given to you. Using the
zip()function you can combine two listspandq, taking the ith element from each and makingzip(p,q)[i] == (p[i], q[i]). In such a way you create a list of (key, value) pairs that you can pass to a dictionary constructor:Finally you want to construct your dictionary, and index it into its appropriate date in the overall history:
You can iterate through your nested
historylist to construct your dictionary in two ways, the first is using a traditionalforloop:Or if you want to play around with a slightly more advanced Python technique, try a nested dict generator statement:
That last one’s a doozy if you’re new to programming, but I encourage you to read up in that link; remember, when programming in Python, Google is your friend. I hope I’ve given you sufficient keywords and ideas here to get started learning, and I’ll leave the rest up to you.