Last active
January 27, 2017 20:11
-
-
Save sumituk1/08addcc88d8c9d356c83b2fd69f6bff0 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import numpy as np | |
import pandas as pd | |
from pandas_datareader import data as web | |
import seaborn as sns | |
import matplotlib.pyplot as plt | |
import datetime as dt | |
sns.set() | |
class RegPred(object): | |
def __init__(self, symbol): | |
self.symbol = symbol | |
self.get_data() | |
def get_data(self): | |
self.data = pd.DataFrame(web.DataReader(self.symbol, data_source='yahoo',start= dt.datetime(2015,1,1),end= dt.datetime(2017,1,26))['Adj Close']) | |
self.data.sort_index(ascending=False,inplace=True) | |
self.data.columns = ['prices'] | |
self.data['returns'] = np.log(self.data / self.data.shift(-1)) | |
self.data.dropna(inplace=True) | |
def generate_matrix(self, lags): | |
self.matrix = np.zeros((lags + 1, len(self.data) - lags)) | |
for i in range(lags + 1): | |
if i == lags: | |
self.matrix[i] = self.data.returns.values[i:] | |
else: | |
self.matrix[i] = self.data.returns.values[i: i - lags] | |
def predict_returns(self, lags): | |
self.lags = lags | |
self.generate_matrix(lags) | |
# reg = np.linalg.lstsq(self.matrix[:lags].T, np.sign(self.matrix[lags]))[0] | |
reg = np.linalg.lstsq(self.matrix[1:].T, self.matrix[0])[0] | |
self.pred = np.dot(self.matrix[:lags].T, reg) | |
def get_performance(self): | |
self.perf = self.data.ix[:-(self.lags+1)].copy() | |
self.perf['positions'] = np.sign(self.pred[1:]) # 0th record is the next day prediction prediction where we havent got the data yet | |
self.perf['strategy'] = self.perf.positions * self.perf.returns | |
self.perf[['returns', 'strategy']].cumsum().apply(np.exp).plot() | |
# class NNPred(object): | |
if __name__ == "__main__": | |
lag = 6 #<-- keep changing the lags!! | |
regClass = RegPred("MSFT") | |
regClass.generate_matrix(lag) | |
regClass.predict_returns(lag) | |
regClass.get_performance() | |
plt.show() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment