Ejemplo n.º 1
0
    def back_test(self,horizon,istech,large,freq,model_name,address,roll=-1,threshold=0.1):
        # initial setting
        df = self.context_dict['close'].copy()
        symbols = self.context_dict['close'].columns[1:]
        cols = self.context_dict['close'].columns.values
        cols[0]='ben'
        df.columns = cols# set zz500 as benchmark
        stock_num = len(symbols)
        back_testing = df.index[pd.to_datetime(df.index) >= pd.to_datetime(self.start_day)]
        df = df.loc[back_testing.values, :]
        unit = np.full((len(df.index), 1), 1)[:, 0]

        df['rebalancing'] = pd.Series()
        df['stoploss'] = pd.Series()
        df['nav'] = pd.Series(unit, index=df.index)
        df['Interest_rate'] = pd.Series(np.full((len(df.index),), 2.5),index=df.index) # 2.5% interest_rate
        weight_new = []
        # max_new = []  # for computing max_drawdown
        unit = np.full((len(df.index), stock_num), 0)
        weights = pd.DataFrame(unit, index=df.index, columns=symbols)
        reb_index = 0
        s = 0  # counting date
        # ============================= Enter Back-testing ===================================
        for cur_date in back_testing.values:

            cur_date = pd.to_datetime(cur_date)

            # rebalance in a fixed frequency in freq rate
            if s>0:# begin to rebalance at least after the second recordings
                if np.mod(s, freq) == 0:
                    # print(s)
                    if self.extract_train(cur_date, istech,horizon,large =large,roll=roll,):
                        if np.shape(self.x_test)[0]>0:
                            test_y = strats.model(model_name, self.x_train, self.y_train, self.x_test)
                            weight_new = strats.fix_stock_order(test_y, threshold)

                            print(df.index[s - 1])
                            print(weight_new[weight_new != 0].head())
                            weights.loc[df.index[s - 1], weight_new.index] = weight_new.values
                            print('*' * 50)
                            df['rebalancing'].iloc[s - 1] = 1
                            reb_index = s - 1

                if len(weight_new) != 0:
                    df = ut.record_return(df, s, reb_index, weight_new, self.leverage, self.trading_days)
                    weights = ut.record_weights(df, s, weights)

            s += 1 # counting date
        compute_indicators(df, 'perf_'+address,self.trading_days)
        weights.to_csv('weights_' + address)
        print('back_test completed!')
Ejemplo n.º 2
0
            max_new = pd.Series(temp_max, index=df.columns[:stock_num])

        # rebalance in fixed frequency
        if np.mod(i - return_period, freq) == 0:
            # The price data of etf uis from the second df.column
            weight_new = ut.mk_drawdown(df.iloc[:i, :stock_num], back_max,
                                        back_holding_period, return_period,
                                        cov_period)
            # weight_new = fix_fund_order(weight_new)
            # TODO:how to record weights?
            print(df.index[i - 1])
            print(weight_new)
            print('*' * 50)
            df['rebalancing'].ix[i - 1] = 1
            reb_index = i - 1

        # stoploss
        if len(max_new) != 0:
            weight_new, flag = stoploss(df, stop_loss, i, max_new, weight_new)
            if flag == 1:
                print(df.index[i - 1])
                print('stoploss!: ')
                print(weight_new)
                print('-' * 50)
                df['stoploss'].ix[i - 1] = 1
                reb_index = i - 1
        if len(weight_new) != 0:
            df = ut.record_return(df, stock_num, i, reb_index, weight_new,
                                  leverage, trading_days)
    perf = ut.comput_idicators(df, trading_days, required_return_real,
                               save_file, save_address + '.csv')