Пример #1
0
class TrainOptimizer:
    def __init__(self, index, stocks):
        '''
        Args:
            index (Stock)
                Index (FTSE-100) represented as a Stock
            stocks (List[Stock])
                List of stocks containing the assets in the portfolio
        '''
        # pdb.set_trace()
        self.index = index
        self.stocks = stocks

    def train(self, train_interval, validate_interval, test_interval):
        '''
        Args:
            train_interval (list[int]) # E.G. (10, 100)
                integers - specifying the range (STAR, END) of data we want to use to train the Optimizer 
        '''

        # STEPS:
        # 1. Intialize GA parameters
        # 2. Set Training/Prediction intervals
        # 3. Initialize Evaluator
        # 4. Initialize Optimizer
        # 5. Train

        # pdb.set_trace()
        portfolioSize, minWeight, transactionCost, lmbda, predictionInterval, rebalancingPeriod = get_tracker_parameters(
        )  # we set these paramaters as per the PFGA applciaiton
        probCrossover, probReplacement, probMutation, sizeTournament = get_genetics_parameters(
        )

        self.optimizer = GeneticAlgorithm(
            50,
            100,
            self.stocks,
            self.index,
            genetic_params=(probCrossover, probReplacement, probMutation,
                            sizeTournament),
            tracker_params=(portfolioSize, minWeight, rebalancingPeriod,
                            transactionCost, lmbda))
        self.optimizer.run(train_interval, validate_interval, test_interval)

    def best_portfolio(self, datatype='test'):
        return self.optimizer.best_portfolio(datatype)

    def solution(self):
        return self.optimizer.solution()
Пример #2
0
    def GA_portfolio_optimize(self,
                              selected_strategy=[
                                  "tesmom", "2nearest", "term_structure",
                                  "hedging_pressure"
                              ],
                              target="Mean_Variance",
                              loss_weight=[1, 1, 1]):
        # print(selected_strategy)
        ret = deepcopy(self.strategy_return_forward)
        for test_name_i, backtest_result_i in deepcopy(ret).items():
            for method_name_i, return_i in backtest_result_i.items():
                if method_name_i not in selected_strategy:
                    del (ret[test_name_i][method_name_i])

        for test_name_i in deepcopy(ret).keys():
            if len(ret[test_name_i]) == 0:
                del (ret[test_name_i])

        self.selected_strategy_return_forward = ret

        flag = 0
        for test_name_i, backtest_result_i in ret.items():
            for method_name_i, return_i in backtest_result_i.items():
                return_i = return_i.resample("M").sum()
                if flag == 0:
                    total_ret = pd.DataFrame(
                        return_i.values,
                        index=return_i.index,
                        columns=['{}_{}'.format(test_name_i, method_name_i)])
                    flag = 1
                elif flag == 1:
                    return_i = pd.DataFrame(
                        return_i.values,
                        index=return_i.index,
                        columns=['{}_{}'.format(test_name_i, method_name_i)])
                    total_ret = total_ret.join(return_i, how="outer")
        # print(total_ret)
        total_ret.to_csv('total_ret.csv')

        #上面的所有步骤都是为了将数据转化为合适的形式传入到优化函数中
        flag = 0
        start = time.clock()
        counter = 0
        total_len = len(total_ret) * 12 - 72
        for i in range(1, len(total_ret) + 1):
            s = {}
            counter += min(i, 12)
            ret = total_ret.iloc[max(0, i - 12):i, :]
            x = GeneticAlgorithm(ret)
            if target == 'test_':
                x.run_softmax(target=target, loss_weight=loss_weight)
            else:
                x.run(target)
            _, cleaned_weights = x.best_portfolio("None")
            s[total_ret.index[i - 1]] = cleaned_weights
            # print(s)
            df = pd.DataFrame(s, index=ret.columns)
            print(df)
            if flag == 0:
                final_weights = df
                flag = 1
            else:
                final_weights = final_weights.join(df)

            elapsed = (time.clock() - start)
            total_time = (elapsed / (counter) * (total_len))
            print('Time processed remained : {:.2f}/{:.2f}'.format(
                elapsed, total_time))

        #得到权重配比的dataframe
        final_weights = final_weights.T
        self.weights = final_weights
        return self.weights