def test_SP500_strat( ):
        
        #Already pickled DJIA_AdjClose
        dataObj = pickle.load(open('pickle_jar/SP500_AdjClose.pkl'))
        dataObj.to_csv('Results/tmptmp.csv')
        
        ####THIS IS WEIRD THAT DB HAS ADJ CLOSE AS VALUE
        ###NEED TO ADD TO PARSING IN READ DATA
        dataObj = dataObj.replace('Adj Close',np.nan).astype('float64')

        
        #Read DJIA index
        dbr = DBReader()
        ref_series = dbr.readSeries(seriesName = 'SP500')
        ref_series = ref_series['Adj_Close']
        ref_series = pd.DataFrame(ref_series)#,columns=['DJIA'])
        ref_series.columns = ['SP500']
        
        series_list = dataObj.columns.values
        
        #setup train/test ranges
        period_length_1 = 90
        period_length_2 = 180 
        start_date = dataObj.index[0]
        end_date = dataObj.index[-1]
#         start_date = datetime.datetime(2009,1,1)
#         end_date = datetime.datetime(2010,1,1)
        periods_dates = pd.date_range(start_date,end_date,freq = '3BMS')
        
        
        #Do example
        
        #Setup strat
        
        #parameters
        top_scores_num = 10
        ema_par = 100
        lag = 3
        lookback = 40
        
        #Initialise strat
        strat = StrategyMSeriesMomentum(periods_dates,
                                        ema_par,
                                        lookback,
                                        lag,
                                        top_scores_num)
         
        #Train - ie pick top X momentum and weights
        #want generate weight matrix of constant weights between rebalance dates
        strat.fit(dataObj)
        
        
        sumweight =strat.weights_matrix.sum(axis=1,skipna=True)
#         sumweight.plot()
        strat.run_strategy(data=dataObj)
        res = strat.result
        
        ref_seriesindex = (ref_series/(ref_series.iloc[0]))
        
        pltData = pd.merge(res,ref_seriesindex,how='inner',left_index=True,right_index=True)
        pltData.plot()
        plt.show()
        
        from ResultsAnalyser import ResultsAnalyser
        ra = ResultsAnalyser(pltData,valueIndex='Value',referenceIndex='SP500')
        tstart = datetime.datetime(2010,6,1)
        tend = datetime.datetime(2013,6,1)
        ra.set_results_range(tstart, tend)
        print "sa sharpe ratio", ra.sharpe_ratio()
        print "to ref sharpe ratio", ra.sharpe_ratio(useMarketRef=True)
Exemplo n.º 2
0
    def test_strat():
        
        #Already pickled DJIA_AdjClose
        dataObj = pickle.load(open('pickle_jar/DJIA_AdjClose.pkl'))
        #Read DJIA index
        dbr = DBReader()
        DJIA = dbr.readSeries(seriesName = 'DJIA')
        #dataObj['DJIA'] = DJIA
        DJIA = pd.DataFrame(DJIA)#,columns=['DJIA'])
        DJIA.columns = ['DJIA']
        
        series_list = dataObj.columns.values
        
        #setup train/test ranges
        period_length_1 = 90
        period_length_2 = 180 
        start_date = dataObj.index[0]
        end_date = dataObj.index[-1]
        periods_dates = pd.date_range(start_date,end_date,freq = '3BMS')
        periods = [ [periods_dates[i], periods_dates[i+1] ] for i in range(0, len(periods_dates)-1)]
        train_periods = periods[0:-1]
        test_periods = periods[1:]
 
        #Do example
        #setup data
        print len(train_periods)
        period_num = 32
        train_data = dataObj.loc[train_periods[period_num][0]:train_periods[period_num][1]]
        test_data = dataObj.loc[test_periods[period_num][0]:test_periods[period_num][1]]
        
        #Setup strat
        
        #parameters
        top_scores_num = 10 
        ema_par = 50
        lag = 1
        lookback = 10
        
        #Initialise strat
        strat = StrategyMSeriesMomentum( ema_par, lookback, lag, top_scores_num)
        
        #Train - ie pick top X momentum and weights
        strat.fit(train_data)
        
        #Setup portfolio
        series_list = strat.top_series_weights.index.values
        portfolio = strat.setup_portfolio( series_list )
        portfolio_train = portfolio.copy()
        
        #Check result on training
        strat.run_strategy(market_data=train_data,
                           portfolio = portfolio_train)
        
        train_result = strat.result
        
        #Check results on test
        portfolio_test = portfolio.copy()
        strat.run_strategy(market_data=test_data,
                           portfolio = portfolio_test)
        
        test_result =strat.result
        
        
        #Analyse results
        from ResultsAnalyser import ResultsAnalyser
        train_result = pd.merge(train_result,DJIA,how='inner',left_index=True, right_index=True)
        
        ra_train = ResultsAnalyser(data = train_result,
                                   valueIndex = 'Value',
                                   referenceIndex = 'DJIA' )
        
        rets = ra_train.get_returns(annualing_factor=1, useReference=True)
        rets += 1
        cumrets = rets.cumprod(axis=0)
#         print cumrets.tail()
        cumrets.plot()
        plt.show()
#       print train_result.head()
        print "Sharpe sa train", ra_train.sharpe_ratio()
        print "Sharpe reference train", ra_train.sharpe_ratio(useMarketRef=True)
        
        
        
        
        test_result = pd.merge(test_result,DJIA,how='inner',left_index=True, right_index=True)
        ra_test = ResultsAnalyser(data = test_result,
                                   valueIndex = 'Value',
                                   referenceIndex = 'DJIA' )
        
        rets = ra_test.get_returns(annualing_factor=1, useReference=True)
        rets += 1
        cumrets = rets.cumprod(axis=0)
#         print cumrets.tail()
        cumrets.plot()
        plt.show()
#       print train_result.head()
        print "Sharpe sa test", ra_test.sharpe_ratio()
        print "Sharpe reference test", ra_test.sharpe_ratio(useMarketRef=True)
    def test_DJIA_strat(plots = False):
        
        #Already pickled DJIA_AdjClose
        dataObj = pickle.load(open('pickle_jar/DJIA_AdjClose.pkl'))
        #Read DJIA index
        dbr = DBReader()
        DJIA = dbr.readSeries(seriesName = 'DJIA')
        #dataObj['DJIA'] = DJIA
        DJIA = pd.DataFrame(DJIA)#,columns=['DJIA'])
        DJIA.columns = ['DJIA']
        
        series_list = dataObj.columns.values
        
        #setup train/test ranges
        period_length_1 = 90
        period_length_2 = 180 
        start_date = dataObj.index[0]
        end_date = dataObj.index[-1]
        
        
        
        periods_dates = pd.date_range(start_date,end_date,freq = '3BMS')
        
        
        #Do example
        
        #Setup strat
        
        #parameters
        top_scores_num = 5
        ema_par = 50
        lag = 1
        lookback = 10
        
        #Initialise strat
        strat = StrategyMSeriesMomentum(periods_dates,
                                        ema_par,
                                        lookback,
                                        lag,
                                        top_scores_num)
         
        #Train - ie pick top X momentum and weights
        #want generate weight matrix of constant weights between rebalance dates
        strat.fit(dataObj)
        print strat.rebalance_dates
        
        rebalance_flag = pd.DataFrame( [True]*len(strat.rebalance_dates) , index = strat.rebalance_dates)
        rebalance_flag = rebalance_flag.resample('B')
        rebalance_flag[pd.isnull(rebalance_flag)] = False
        rebalance_flag.index.name = 'date'
        rebalance_flag.columns = ['Rebalance_Flag']
        rebalance_flag.to_csv('Results/StrategyMSeries_Momentum/rebalance_flag.csv')
        
        
#         strat.weights_matrix.to_csv('Results/StrategyMSeries_Momentum/DJIA_weight_matrix.csv')
        sumweight =strat.weights_matrix.sum(axis=1,skipna=True)
#         sumweight.plot()
        strat.run_strategy(data=dataObj)
        res = strat.result
        
        DJIAindex = (DJIA/(DJIA.iloc[0]))
        
        tstart = datetime.datetime(2012,7,2)
        tend = datetime.datetime(2013,7,4)
        
        
        pltData = pd.merge(res,DJIAindex,how='inner',left_index=True,right_index=True)
        if plots:
            pltData.loc[tstart:tend].plot()
            plt.show()
             
        from ResultsAnalyser import ResultsAnalyser
        ra = ResultsAnalyser(pltData,valueIndex='Value',referenceIndex='DJIA')
        ra.set_results_range(tstart, tend)
        
        
         
        print "sa sharpe ratio", ra.sharpe_ratio()
        print "sa returns", ra.get_cumulative_return().iloc[-1]
        print "sa vol", ra.get_volatility(annualising_scalar=1,returns = True)
        print "to ref sharpe ratio", ra.sharpe_ratio(useMarketRef=True)

        balance_matrix = strat.weights_matrix.loc[strat.rebalance_dates]#.iloc[-5:-1]
        balance_matrix.to_csv('Results/StrategyMSeries_Momentum/balance_matrix.csv')