-
Introduction 1
-
Lecture1.1
-
-
Getting the Data 3
-
Lecture2.1
-
Lecture2.2
-
Lecture2.3
-
-
SP500 Webscrape 4
-
Lecture3.1
-
Lecture3.2
-
Lecture3.3
-
Lecture3.4
-
-
Full Dataset 2
-
Lecture4.1
-
Lecture4.2
-
-
Regressions 5
-
Lecture5.1
-
Lecture5.2
-
Lecture5.3
-
Lecture5.4
-
Lecture5.5
-
-
Machine Learning 5
-
Lecture6.1
-
Lecture6.2
-
Lecture6.3
-
Lecture6.4
-
Lecture6.5
-
-
Machine Learning Function 2
-
Lecture7.1
-
Lecture7.2
-
-
Visualize Data 2
-
Lecture8.1
-
Lecture8.2
-
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
Prev
Regression