def createIndicators(self):
        ##mycode
        dates = pd.date_range(self.start_date, self.end_date)
        price = ut.get_data(self.symbol, dates, addSPY=True)
        price_SPY = price['SPY']
        price = price.drop(['SPY'], axis=1)

        ##get data for all the indicators including T - 30 trading days of data (to account for creation of historical indicators)
        sma_ind = ind.get_price_sma_ind(price, 20)
        momentum_ind = ind.getMomentumInd(price, 14)
        bb_ind = ind.getBBInd(price, 14)
        macd_ind = ind.getMACDInd(price)
        vol_ind = ind.volatility(price, 14)

        #we now remove the last 30 days of data (December 2007) after creating the indicators so that we only have training period data.
        price = price.loc[price.index >= self.start_date +
                          dt.timedelta(days=30)]
        sma_ind = sma_ind.loc[sma_ind.index >= self.start_date +
                              dt.timedelta(days=30)]
        vol_ind = vol_ind.loc[vol_ind.index >= self.start_date +
                              dt.timedelta(days=30)]
        momentum_ind = momentum_ind.loc[momentum_ind.index >= self.start_date +
                                        dt.timedelta(days=30)]
        bb_ind = bb_ind.loc[bb_ind.index >= self.start_date +
                            dt.timedelta(days=30)]
        macd_ind = macd_ind.loc[macd_ind.index >= self.start_date +
                                dt.timedelta(days=30)]

        ##create cross over signals for each day
        price_sma_crossover = pd.DataFrame(0,
                                           index=sma_ind.index,
                                           columns=sma_ind.columns)
        price_sma_crossover[sma_ind > 0] = 1
        price_sma_crossover = price_sma_crossover.diff()
        price_sma_crossover[price_sma_crossover != 0] = 1

        macd_sigal_diff = ind.getMACDHistogramInd(price)

        #macd cross below signal = sell
        macd_cross_below_signal = pd.DataFrame(0,
                                               index=macd_ind.index,
                                               columns=macd_ind.columns)
        macd_cross_below_signal[macd_sigal_diff < 0] = 1
        macd_cross_below_signal[1:] = macd_cross_below_signal.diff()
        macd_cross_below_signal.ix[0] = 0
        #print(macd_cross_above_signal)

        #macd cross above signal = buy
        macd_cross_above_signal = pd.DataFrame(0,
                                               index=macd_ind.index,
                                               columns=macd_ind.columns)
        macd_cross_above_signal[macd_sigal_diff > 0] = 1
        macd_cross_above_signal[1:] = macd_cross_above_signal.diff()
        macd_cross_above_signal.ix[0] = 0
        #print(macd_cross_above_signal)

        #bollinger crossovers
        ##this is a sell signal
        bb_upper_cross_signal = ind.getBBUpperCross(price, 20)

        #this is a buy signal
        bb_lower_cross_signal = ind.getBBLowerCross(price, 20)

        ##create and discretize states for Q Learner
        #print sma_ind
        daily_rets = ((price.shift(-5) / price) - 1)
        daily_rets.ix[-1] = 0

        price['Price_Sma'] = sma_ind
        price['Volatility'] = vol_ind
        price['Momentum'] = momentum_ind
        price['BB_Ind'] = bb_ind
        #price['MACD_Ind'] = macd_ind

        #price['BB_Upper_Cross'] = bb_upper_cross_signal
        #price['BB_Lower_Cross'] = bb_lower_cross_signal
        price['MACD_Cross_Below'] = macd_cross_below_signal
        price['MACD_Cross_Above'] = macd_cross_above_signal
        #price['Price_SMA_Crossover'] = price_sma_crossover

        daily_ret_classes = pd.DataFrame(0,
                                         index=daily_rets.index,
                                         columns=daily_rets.columns,
                                         dtype=int)
        Y_buy = 0.005
        Y_sell = -0.005
        daily_ret_classes[daily_rets > Y_buy] = 1
        daily_ret_classes[daily_rets < Y_sell] = -1

        price['Action'] = daily_ret_classes
        #print price.iloc[:,1:].sum(axis=1)
        #print price
        return price
Пример #2
0
    def testPolicy(self):
        dates = pd.date_range(self.start_date, self.end_date)
        price = get_data(self.symbol, dates, addSPY=True)
        price = price.drop(['SPY'], axis=1)

        ##get data for all the indicators including T - 30 trading days of data (to account for creation of historical indicators)
        sma_ind = ind.get_price_sma_ind(price, 20)
        momentum_ind = ind.getMomentumInd(price, 14)
        bb_ind = ind.getBBInd(price, 14)
        macd_ind = ind.getMACDInd(price)
        vol_ind = ind.volatility(price, 14)

        #we now remove the last 30 days of data (December 2007) after creating the indicators so that we only have training period data.
        price = price.loc[price.index >= self.start_date +
                          dt.timedelta(days=30)]
        sma_ind = sma_ind.loc[sma_ind.index >= self.start_date +
                              dt.timedelta(days=30)]
        vol_ind = vol_ind.loc[vol_ind.index >= self.start_date +
                              dt.timedelta(days=30)]
        momentum_ind = momentum_ind.loc[momentum_ind.index >= self.start_date +
                                        dt.timedelta(days=30)]
        bb_ind = bb_ind.loc[bb_ind.index >= self.start_date +
                            dt.timedelta(days=30)]
        macd_ind = macd_ind.loc[macd_ind.index >= self.start_date +
                                dt.timedelta(days=30)]

        ##create cross over signals for each day
        price_sma_crossover = pd.DataFrame(0,
                                           index=sma_ind.index,
                                           columns=sma_ind.columns)
        price_sma_crossover[sma_ind > 0] = 1
        price_sma_crossover = price_sma_crossover.diff()
        price_sma_crossover[price_sma_crossover != 0] = 1

        macd_sigal_diff = ind.getMACDHistogramInd(price)

        #macd cross below signal = sell
        macd_cross_below_signal = pd.DataFrame(0,
                                               index=macd_ind.index,
                                               columns=macd_ind.columns)
        macd_cross_below_signal[macd_sigal_diff < 0] = 1
        macd_cross_below_signal[1:] = macd_cross_below_signal.diff()
        macd_cross_below_signal.ix[0] = 0
        #print(macd_cross_above_signal)

        #macd cross above signal = buy
        macd_cross_above_signal = pd.DataFrame(0,
                                               index=macd_ind.index,
                                               columns=macd_ind.columns)
        macd_cross_above_signal[macd_sigal_diff > 0] = 1
        macd_cross_above_signal[1:] = macd_cross_above_signal.diff()
        macd_cross_above_signal.ix[0] = 0
        #print(macd_cross_above_signal)

        #bollinger crossovers
        ##this is a sell signal
        bb_upper_cross_signal = ind.getBBUpperCross(price, 20)

        #this is a buy signal
        bb_lower_cross_signal = ind.getBBLowerCross(price, 20)

        #creaete tradings strategy
        df_trades = pd.DataFrame(0, index=price.index, columns=['Shares'])
        overbought_or_oversold = pd.DataFrame(index=price.index,
                                              columns=['Action'])

        ##entry conditions -different combinations

        #macd + price/sma + bb % + volatility = final trading strategy
        short_ind = (macd_cross_below_signal == 1) | ((sma_ind > 0.05) &
                                                      (bb_ind > 1))
        buy_ind = (macd_cross_above_signal == 1) | ((sma_ind < -0.05) &
                                                    (bb_ind < 0))
        exit_ind = (price_sma_crossover == 1) & ((vol_ind > 0.04))

        #only overbought/oversold (price/sma + bb%)
        #short_ind = ((sma_ind>0.05) & (bb_ind > 1))
        #buy_ind =  ((sma_ind< -0.05) & (bb_ind < 0))

        #either crossovers (MACD or BB)
        #buy_ind = (bb_lower_cross_signal==1) | (macd_cross_above_signal==1)
        #short_ind = (bb_upper_cross_signal==1) | (macd_cross_below_signal==1)

        #both crossovers (MACD and BB)
        #buy_ind = (bb_lower_cross_signal==1) & (macd_cross_above_signal==1)
        #short_ind = (bb_upper_cross_signal==1) & (macd_cross_below_signal==1)

        #only bollinger crossover
        #buy_ind = (bb_lower_cross_signal==1)
        #short_ind = (bb_upper_cross_signal==1)

        #only MACD signal line crossover
        #short_ind = (macd_cross_below_signal==1)
        #buy_ind = (macd_cross_above_signal==1)

        ##exit conditions
        overbought_or_oversold.iloc[exit_ind == True] = 0  #exit
        #overbought
        overbought_or_oversold.iloc[short_ind == True] = -1  #short
        #oversold
        overbought_or_oversold.iloc[buy_ind == True] = 1  #buy

        #buy or sell on above if holding constraint is met
        holdings = 0
        for index_order, row_order in overbought_or_oversold.iterrows():

            if row_order['Action'] == 1 and holdings == 0:
                df_trades.ix[index_order, 'Shares'] = 1000
                holdings = 1000

            elif row_order['Action'] == 1 and holdings == -1000:
                df_trades.ix[index_order, 'Shares'] = 2000
                holdings = 1000

            elif row_order['Action'] == -1 and holdings == 0:
                df_trades.ix[index_order, 'Shares'] = -1000
                holdings = -1000

            elif row_order['Action'] == -1 and holdings == 1000:
                df_trades.ix[index_order, 'Shares'] = -2000
                holdings = -1000

            elif row_order['Action'] == 0 and holdings == 1000:
                df_trades.ix[index_order, 'Shares'] = -1000
                holdings = 0

            elif row_order['Action'] == 0 and holdings == -1000:
                df_trades.ix[index_order, 'Shares'] = 1000
                holdings = 0

            else:
                df_trades.ix[index_order, 'Shares'] = 0

        return df_trades