Skip to content

Instantly share code, notes, and snippets.

@okomarov
Last active December 26, 2018 13:29
Show Gist options
  • Save okomarov/9709976f3a7edfb211b1df5947506c8f to your computer and use it in GitHub Desktop.
Save okomarov/9709976f3a7edfb211b1df5947506c8f to your computer and use it in GitHub Desktop.
%matplotlib notebook
import pandas_datareader as pdr
from sklearn.linear_model import LinearRegression
from sklearn.metrics import mean_squared_error
# Download gold data (ETF)
gld = pdr.get_data_yahoo('GLD',start='1984-01-01')
# Use AR(1), i.e. previous price predicts next
gld['Prev'] = gld['Adj Close'].shift(1)
X = gld['Prev']
y = gld['Adj Close']
# 80% train, 20% test
t = int(0.8*len(gld))
X_train = X[1:t]
y_train = y[1:t]
X_test = X[t:]
y_test = y[t:]
# Fit and predict
linear = LinearRegression().fit(X_train.values[:,None],y_train.values[:,None])
predicted_price = linear.predict(X_test.values[:,None])
print(mean_squared_error(y_test.values[:,None], predicted_price))
y.plot()
plt.plot(X_test.index, predicted_price)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment