Making the Beta Dataframe
Solution
def regress(stock):
result = sm.ols(formula=stock+" ~ Index + Oil + Gold + NaturalGas", data=df).fit()
return pd.DataFrame(result.params[result.pvalues<.05],columns=[stock])
regress("PXD")
Before we can move on we need to address an issue you would eventually find if you tried to create the dataframe. Run this code for the stock that has a symbol BRK.B.
regress("BRK.B")
You get an error, because it messes with the formula. So we are going to need to change this column name to accommodate.
Let’s get rid of anything that is not a letter, and assign these names to the df columns.
cols = []
for x in df.columns:
if "." in x:
x = x.replace(".","")
if ":" in x:
x = x.replace(":","")
cols.append(x)
df.columns = cols
Challenge
Create a dataframe which features all the stocks and their resepective betas.
Hint: Try running a for loop over df.columns
Hint: Try running a for loop over df.columns