@@ -0,0 +1,1750 @@
+import numpy as np%0Aimport pandas as pd%0Afrom pandas_datareader import data as web%0Afrom sklearn import linear_model%0A%0Aclass ScikitBacktest(object):%0A    def __init__(self,sys):%0A        self.lags = 5%0A        self.symbol = sys%0A        self.get_data()%0A        self.lm = linear_model.LogisticRegression(C=1e3)%0A    def get_data(self):%0A        d = web.DataReader(self.sys,data_source='yahoo')%5B'Adj Close'%5D%0A        d = pd.DataFrame(d)%0A        d.columns = %5Bself.symbol%5D%0A        d%5B'returns'%5D=np.log(d/d.shift(1))%0A        self.data = d%0A    def select_data(self,start,end):%0A        d = self.data%5B(self.data.index %3E= start) & (self.data.index %3C= end)%5D.copy()%0A        return d%0A    def get_matrix(self,start,end):%0A        d = self.select_data(start,end)%0A        m = np.zeros((self.lags+1,len(d)-self.lags))%0A        for i in range(self.lags+1):%0A            if i == self.lags:%0A                m%5Bi%5D=d%5Bi:%5D%0A            else:%0A                m%5Bi%5D=d%5Bi:i-self.lags%5D%0A        self.matrix = m%0A    def fit_model(self,start,end):%0A        self.get_matrix(start,end)%0A        self.lm.fit(self.matrix%5B:self.lags%5D,np.sign(self.matrix%5Bself.lags%5D))%0A    def predict_moves(self,start,end):%0A        self.get_matrix(start,end)%0A        pred = self.lm.predict(self.matrix%5B:self.lags%5D)%0A        return pred%0A    def run_strategy(self,start_tr,end_tr,start_te,end_te,lags):%0A        self.lags =lags%0A        self.fit_model(start_tr,end_tr)%0A        pred = self.predict_moves(start_te,end_te)%0A        d = self.select_data(start_te,end_te)%0A        d%5B'pred'%5D= 0.0%0A        d%5B'pred'%5D.ix%5Bself.lags:%5D=pred%0A        d%5B'strategy'%5D = d.pred * d.returns%0A        title = '%25s to %25s for %25d lags' %25 (start_te,end_te,self.lags)%0A        d%5B%5B'returns','strategy'%5D%5D.ix%5Bself.lags:%5D.cumsum().apply(np.exp).plot(title=title)%0A

Add stock trading script