Exemple #1
0
    def run_strategy(self, market_data, portfolio):
        
        
        if (pd.isnull(market_data)).any()[0]:
            #Raise this error to make sure there's no gaps in data
            raise ValueError("Series XY = {0}, {1} do not have equal date range".format(self.series_x_label, self.series_y_label)) 
        
        reg_params = [self.intercept, self.scaling]
        
        md = pairs_md(market_data, 
                      xInd = self.series_x_label,
                      yInd = self.series_y_label)
        
        
        md.generateTradeSigs(windowLength = self.window_length,
                              entryScale= self.entry_scale, 
                              exitScale = self.exit_scale, 
#                               ewma_par= 100,
                              reg_params = reg_params
                              )
        
        
        Reversion_EntryExitTechnical.run_strategy(self, 
                                                  md,
                                                  portfolio)
        
        
        if self.plot_flag:
            md.plot_spreadAndSignals()
Exemple #2
0
 def fit(self, data):
     
     #drop na data so that can fit ols
     md = pairs_md(data.dropna(), self.series_x_label, self.series_y_label)
     md.fitOLS()
     self.scaling = md.results.params[self.series_x_label]
     self.intercept = md.results.params['const']
 def PairTradeSP500():
     
     #Setup market data
     import sqlite3
     con = sqlite3.connect("/home/phcostello/Documents/Data/FinanceData.sqlite")
     SP500 = md.read_db(con, "SP500")
     BA = md.read_db(con,"BA")
     dim = 'Adj Close'
     SP500AdCl = SP500[dim]
     BAAdCl = BA[dim]
     dataObj = pd.merge(pd.DataFrame(BAAdCl), pd.DataFrame(SP500AdCl), how='inner',left_index = True, right_index = True)
     dataObj.columns = ['y','x']
     pmd = md.pairs_md(dataOb=dataObj,xInd='x',yInd='y')
     #pmd.printSummary()
     pmd.fitOLS()
     pmd.generateTradeSigs(50, entryScale=1, exitScale=0.5)
     #pmd.plot_spreadAndSignals()
     
     #Setup portfolio
     spreadTrade = td.TradeEquity("spread", notional=0, price_series_label="spread")
     port = pf.Portfolio("portfolio", cashAmt=100)
     port.add_trade(spreadTrade)
     #No more trade types
     port.fixed_toggle()
     
     #Setup Strategy
     pairsStrat = Pairs_Trade(market_data=pmd, portfolio=port, initial_time_index=0)
     pairsStrat.run_strategy()
     
     #print pairsStrat.result['Signal']
     #print pairsStrat.result.index[1:10]
     
     #print "Sharpe Ratio", pairsStrat.sharpe_ratio()
     fig = plt.figure()
     ax1= fig.add_subplot(3,1,1)
     ax2 = fig.add_subplot(3,1,2)
     ax3= fig.add_subplot(3,1,3)
     pairsStrat.market_data.core_data[['spread','entryUpper','exitUpper','entryLower','exitLower']].plot(ax=ax1)
     pairsStrat.result['Value'].plot(ax=ax2)
     pd.DataFrame(100*SP500AdCl/SP500AdCl[0]).plot(ax=ax2)
     #pd.DataFrame(100*SP500AdCl/SP500AdCl[0]).plot(ax=ax3)
     rets = pairsStrat.get_returns(referenceIndex='x')
     rets.plot(ax=ax3)
     #plt.show()
     dd = pairsStrat.draw_downs()
     #print dd['Drawdown']
     maxDD = max(dd['Drawdown'])
     maxDDr = dd.ix[dd['Drawdown'] == maxDD]
     #print maxDDr.ix[1]
     #dd.to_csv('../dd.csv', sep='\t')
     #plt.show()
     pairsStrat.summary()
def PairTradeSP500(stdWindowLength, entryScale, exitScale):
    
    #Read in data and setup object
    dbpath = "/home/phcostello/Documents/Data/FinanceData.sqlite"
    the_data_reader = dr.DBReader(dbpath)
    SP500 = the_data_reader.readSeries("SP500")
    BA = the_data_reader.readSeries("BA")
    
    dim = 'Adj_Close' #Choose dim to analyse
    SP500AdCl = SP500[dim]
    BAAdCl = BA[dim]
#        print SP500AdCl.head()
#        print BAAdCl.head()
    dataObj = pd.merge(pd.DataFrame(BAAdCl), pd.DataFrame(SP500AdCl), how='inner',left_index = True, right_index = True)
    dataObj.columns = ['y','x']
    
    #Construct data object for pairs trading strat
    pmd = md.pairs_md(dataOb=dataObj,xInd='x',yInd='y')
    maxdate = datetime.date(2013,1,1)
    pmd.core_data = pmd.core_data[:maxdate]
    pmd.fitOLS()
    pmd.generateTradeSigs(stdWindowLength, entryScale, exitScale)
    
    #Setup portfolio
    spreadTrade = td.TradeEquity("spread", notional=0, price_series_label="spread")
    port = pf.Portfolio("portfolio", cashAmt=100)
    port.add_trade(spreadTrade)
    #No more trade types
    port.fixed_toggle()
    
    #Setup Strategy
    pairsStrat = tsc.Reversion_EntryExitTechnical(market_data=pmd, portfolio=port, initial_time_index=1)
    
    return pairsStrat

    tic = time.clock()
    pairsStrat.run_strategy()
    toc = time.clock()
    print "strategy took {} seconds to run".format(toc - tic)
    outfile = open("pickled_pairs.pkl", 'wb')
    pairs_strategy_run = pickle.dump(pairsStrat,outfile)
    outfile.close()
Exemple #5
0
from ImplementedStrategies import PairTradeSP500

#Read in data and setup object
dbpath = "/home/phcostello/Documents/Data/FinanceData.sqlite"
the_data_reader = dr.DBReader(dbpath)
SP500 = the_data_reader.readSeries("SP500")
BA = the_data_reader.readSeries("BA")

dim = 'Adj_Close' #Choose dim to analyse
SP500AdCl = SP500[dim]
BAAdCl = BA[dim]
dataObj = pd.merge(pd.DataFrame(BAAdCl), pd.DataFrame(SP500AdCl), how='inner',left_index = True, right_index = True)
dataObj.columns = ['y','x']

#Construct data object for pairs trading strat
pmd = md.pairs_md(dataOb=dataObj,xInd='x',yInd='y')
maxdate = datetime.date(2013,1,1)
pmd.core_data = pmd.core_data[:maxdate]
pmd.fitOLS()



def optimFunc(pars):
    
    stdWindowLength = pars[0]
    entryScale= pars[1]
    exitScale= pars[2]
    
#    #Read in data and setup object
#    dbpath = "/home/phcostello/Documents/Data/FinanceData.sqlite"
#    the_data_reader = dr.DBReader(dbpath)