Getting our Indicators
Now, we want to get indicators. We will be using data-reader for all of that as well. What we want is the market index (SPY) which represents the SP 500, coupled with commodities.
We can get the SPY value just like a regular stock.
index = pdr.get_data_yahoo("SPY", startDate, endDate)
print(index)
Now, to get oil prices, we need to change from yahoo finance to FRED. It’s a federal reserve database that let’s us get lots of different indicators. To get oil, we do this.
oil = pdr.fred.FredReader("DCOILWTICO", startDate, endDate).read()
print(oil)
To get gold:
gold = pdr.fred.FredReader("GOLDAMGBD228NLBM", startDate, endDate).read()
print(gold)
To get natural gas:
naturalGas = pdr.fred.FredReader("DHHNGSP", startDate, endDate).read()
print(naturalGas)
And let’s get the percent change for all of these.
index = index["Adj Close"].pct_change()
oil = oil.pct_change()
gold = gold.pct_change()
naturalGas = naturalGas.pct_change()
Now, let’s import pandas so we can use the full library. What we are going to do is put these indicators together. Pandas has a function concat that takes an array of dataframes and stitches them together. We also need to specify axis=1 or else pandas will drop to put them together one after another, rather than side by side.
import pandas as pd
df = pd.concat([index, oil,gold,naturalGas], axis=1)
df.dropna(inplace=True)
print(df)
Finally, we will save the dataframe. We give a file name, and then set encoding to UTF-8. Feel free to check out the csv!
df.to_csv("Variables.csv", encoding="UTF-8")
Source Code