strategy_with_portfolio_optim.py 文件源码

python
阅读 28 收藏 0 点赞 0 评论 0

项目:strategy 作者: kanghua309 项目源码 文件源码
def BasicFactorRegress(inputs, window_length, mask, n_fwd_days, algo_mode=None, cross=True):
    class BasicFactorRegress(CustomFactor):
        # params = {'trigger_date': None, }
        init = False

        def __shift_mask_data(self, X, Y, n_fwd_days=1):
            # Shift X to match factors at t to returns at t+n_fwd_days (we want to predict future returns after all)
            shifted_X = np.roll(X, n_fwd_days, axis=0)
            # Slice off rolled elements
            X = shifted_X[n_fwd_days:]
            Y = Y[n_fwd_days:]
            n_time, n_stocks, n_factors = X.shape
            # Flatten X
            X = X.reshape((n_time * n_stocks, n_factors))
            Y = Y.reshape((n_time * n_stocks))
            return X, Y

        def __get_last_values(self, input_data):
            last_values = []
            for dataset in input_data:
                last_values.append(dataset[-1])
            return np.vstack(last_values).T

        def compute(self, today, assets, out, returns, *inputs):
            if (not self.init):
                self.clf = algo_mode
                X = np.dstack(inputs)  # (time, stocks, factors)  ??????

                Y = returns  # (time, stocks)
                X, Y = self.__shift_mask_data(X, Y, n_fwd_days)  # n????????1???- ??factor ????
                X = np.nan_to_num(X)
                Y = np.nan_to_num(Y)
                if cross == True:
                    quadratic_featurizer = PolynomialFeatures(interaction_only=True)
                    X = quadratic_featurizer.fit_transform(X)

                self.clf.fit(X, Y)
                # self.init = True
            last_factor_values = self.__get_last_values(inputs)
            last_factor_values = np.nan_to_num(last_factor_values)

            out[:] = self.clf.predict(last_factor_values)

    return BasicFactorRegress(inputs=inputs, window_length=window_length, mask=mask)
评论列表
文章目录


问题


面经


文章

微信
公众号

扫码关注公众号