Пример #1
0
    def __init__(self):
        """ 回测股票权重 验证backtest程序正确与否 """

        self.port_name = ""
        self.wind_port_path = WindPortUpLoad().path
        self.data_weight_path = Index().data_path_weight
        self.data_factor_path = Index().data_data_factor
Пример #2
0
    def __init__(self,
                 fund_pool_name="指数+主动股票+灵活配置60基金",
                 benchmark_name="基金持仓基准基金池",
                 alpha_len=750,
                 alpha_column="RegressAlphaIR",
                 port_name="股票型基金优选750AlphaIR",
                 style_deviate=0.10,
                 position_deviate=0.02,
                 fund_up_ratio=0.15,
                 turnover=0.30
                 ):

        Data.__init__(self)
        self.sub_data_path = r'fund_data\nice_stock_fund'
        self.port_name = port_name
        self.fund_pool_name = fund_pool_name
        self.benchmark_name = benchmark_name

        self.alpha_len = alpha_len
        self.setup_date_len = self.alpha_len + 50
        self.style_deviate = style_deviate
        self.position_deviate = position_deviate
        self.fund_up_ratio = fund_up_ratio
        self.turnover = turnover  # double
        self.alpha_column = alpha_column

        self.data_path = os.path.join(self.primary_data_path, self.sub_data_path, self.port_name)
        self.port_path = os.path.join(WindPortUpLoad().path, self.port_name)
        if not os.path.exists(self.port_path):
            os.makedirs(self.port_path)
        if not os.path.exists(self.data_path):
            os.makedirs(self.data_path)
Пример #3
0
    def __init__(self):
        """
        优化函数母类
        主要是共同的取数据函数
        """

        Data.__init__(self)

        self.port_name = ""
        self.benchmark_code = ""
        self.stock_pool_name = ""

        self.industry_deviate = ""
        self.style_deviate = ""
        self.stock_deviate = ""
        self.double_turnover = ""
        self.min_tor = 0.001  # 权重最小容忍值
        self.style_columns = []
        self.weight_sum = 0.95
        self.track_error = 0.05

        self.free_mv = None
        self.trading_status = None
        self.alpha_data = None
        self.date_series = None
        self.wind_port_path = WindPortUpLoad().path
Пример #4
0
    def __init__(self):
        """
        2、max_alpha w为主动权重 考虑基准权重

        限制条件:
        2、1 风格偏离
        2、2 行业偏离
        2、3 证券绝对权重上下限
        2、4 证券相对权重偏离
        2、5 跟踪误差 ***
        2、6 换手率
        2、7 证券数量约束 ***
        """

        OptWeight.__init__(self)

        self.port_name = ""
        self.benchmark_code = ""
        self.stock_pool_name = ""

        self.industry_deviate = ""
        self.style_deviate = ""
        self.stock_deviate = ""
        self.double_turnover = ""
        self.min_tor = 0.001  # 权重最小容忍值
        self.style_columns = []
        self.weight_sum = 0.95
        self.track_error = 0.05

        self.free_mv = None
        self.trading_status = None
        self.alpha_data = None
        self.date_series = None
        self.wind_port_path = WindPortUpLoad().path
Пример #5
0
    def generate_wind_file(self, index_name, port_name, end_date):
        """ 生成wind文件 """

        port_path = os.path.join(WindPortUpLoad().path, port_name)
        if not os.path.exists(port_path):
            os.makedirs(port_path)

        sub_path = os.path.join(self.data_path, 'score_fund', index_name)
        filename = os.path.join(
            sub_path, '基金得分_' + index_name + '_' + end_date + '.xlsx')
        data = pd.read_excel(filename, index_col=[0], encoding='gbk')
        data = data[['基金全称', '总得分']]

        data = data.dropna()
        data = data.iloc[0:min(5, len(data)), :]
        end_date = Date().get_trade_date_offset(end_date, 0)

        data.index.name = 'Code'
        data["Price"] = 0.0
        data["Direction"] = "Long"
        data["CreditTrading"] = "No"
        data['Date'] = end_date
        data['Weight'] = 1.0 / len(data)
        out_file = os.path.join(port_path, port_name + "_" + end_date + '.csv')
        data.to_csv(out_file)
Пример #6
0
    def __init__(self, port_name):

        Data.__init__(self)
        self.wind_port_path = WindPortUpLoad().path
        self.data_weight_path = Index().data_path_weight
        self.data_factor_path = Index().data_data_factor
        self.port_name = '天风股票基金'
Пример #7
0
    def __init__(self):
        """
        1、max_alpha w为绝对权重 不考虑基准权重

        限制条件:
        1、1 控制风格偏离
        1、2 控制行业偏离
        1、3 控制股票上下限
        1、4 控制换手率
        """
        OptWeight.__init__(self)

        self.port_name = ""
        self.weight_name = ""
        self.benchmark_code = ""
        self.stock_pool_name = ""

        self.industry_deviate = ""
        self.style_deviate = ""
        self.double_turnover = ""
        self.min_tor = 0.001  # 权重最小容忍值
        self.style_columns = []
        self.weight_sum = 0.95
        self.weight_type = 'fixed'

        self.free_mv = None
        self.trading_status = None
        self.alpha_data = None
        self.date_series = None
        self.wind_port_path = WindPortUpLoad().path
Пример #8
0
    def get_data_from_out_position(self):

        file1 = r'C:\Users\doufucheng\OneDrive\Desktop\普通股票型基金.csv'
        file2 = r'C:\Users\doufucheng\OneDrive\Desktop\偏股.csv'
        port_name = '天风股票基金仓位'
        fund_index_code = "885000.WI"

        data1 = pd.read_csv(file1, encoding='gbk')
        data2 = pd.read_csv(file2, encoding='gbk')
        data = pd.concat([data1, data2], axis=0)
        data = data.reset_index(drop=True)

        date_series = list(set(data.report_period.values))
        date_series.sort()

        wind_port_path = WindPortUpLoad().path
        sub_path = os.path.join(wind_port_path, port_name)

        if not os.path.exists(sub_path):
            os.makedirs(sub_path)

        for i_date in range(len(date_series)):

            date = date_series[i_date]

            quarter_date = str(date)
            fund_pool = FundPool().get_fund_pool_code(name="基金持仓基准基金池",
                                                      date=quarter_date)
            stock_ratio = pd.DataFrame(self.stock_ratio.loc[fund_pool,
                                                            quarter_date])
            ratio = stock_ratio.median().values[0] / 100.0

            data_date = data[data.report_period == date]
            data_gb = data_date.groupby(by=['stock_code']).sum()['weight']
            data_gb = pd.DataFrame(data_gb)
            data_gb.columns = ['Weight']
            data_gb['Weight'] = data_gb['Weight'] / data_gb['Weight'].sum()

            data_date = data_gb
            publish_date = Date().get_trade_date_offset(date, 17)
            data_date.columns = ['Weight']
            data_date['Weight'] *= ratio
            data_date.loc["Cash", "Weight"] = 1 - ratio
            data_date.index.name = 'Code'
            data_date["CreditTrading"] = "No"
            data_date["Date"] = publish_date
            data_date["Price"] = 0.0
            data_date["Direction"] = "Long"
            file = os.path.join(sub_path,
                                '%s_%s.csv' % (port_name, publish_date))
            data_date.to_csv(file)

        backtest = BackTest()
        backtest.set_info(port_name, fund_index_code)
        backtest.read_weight_at_all_change_date()
        backtest.cal_weight_at_all_daily()
        backtest.cal_port_return(beg_date="20040101")
        backtest.cal_turnover(annual_number=4)
        backtest.cal_summary(all_beg_date="20040101")
Пример #9
0
 def __init__(self, index_code_list, port_name):
     """
     跟踪股票基金总指数 基金指数回归各类指数
     """
     self.index_code_list = index_code_list
     self.port_name = port_name
     self.wind_port_path = WindPortUpLoad().path
     self.fund_index_code = "885000.WI"
Пример #10
0
    def __init__(self):

        Data.__init__(self)
        self.wind_port_path = WindPortUpLoad().path
        self.data_weight_path = Index().data_path_weight
        self.data_factor_path = Index().data_data_factor
        self.port_name = '天风股票基金'
        self.fund_index_code = "885000.WI"
Пример #11
0
 def __init__(self):
     """ 数据存储位置 """
     Data.__init__(self)
     self.port_name = "ZZ500_3Factor"
     self.wind_port_path = WindPortUpLoad().path
     self.data_weight_path = Index().data_path_weight
     self.data_factor_path = Index().data_data_factor
     self.beg_date = "20170301"
Пример #12
0
    def __init__(self, fund_code):

        Data.__init__(self)

        self.port_name = "半年报%s" % fund_code
        self.fund_code = fund_code
        self.wind_port_path = WindPortUpLoad().path
        self.data_weight_path = Index().data_path_weight
        self.data_factor_path = Index().data_data_factor
Пример #13
0
    def __init__(self):

        Data.__init__(self)

        self.port_name = "主动股票基金month"
        self.wind_port_path = WindPortUpLoad().path
        self.data_weight_path = Index().data_path_weight
        self.data_factor_path = Index().data_data_factor

        self.stock_ratio = None
Пример #14
0
    def __init__(self):

        Data.__init__(self)

        self.port_name = "普通股票型基金_等权季报_报告日"
        self.wind_port_path = WindPortUpLoad().path
        self.data_weight_path = Index().data_path_weight
        self.data_factor_path = Index().data_data_factor

        self.stock_ratio = None
Пример #15
0
    def __init__(self):

        Data.__init__(self)

        self.port_name = "公募股票基金季报满仓"
        self.wind_port_path = WindPortUpLoad().path
        self.data_weight_path = Index().data_path_weight
        self.data_factor_path = Index().data_data_factor

        self.stock_ratio = None
        self.industry_citic1 = None
        self.pct = None
        self.group = list(range(1, 30))
Пример #16
0
    def __init__(self):

        Data.__init__(self)

        self.port_name = "普通股票型基金跟随"
        self.wind_port_path = WindPortUpLoad().path
        self.data_weight_path = Index().data_path_weight
        self.data_factor_path = Index().data_data_factor

        self.stock_ratio = None
        self.free_mv = None
        self.pct = None
        self.group = 5
Пример #17
0
    def __init__(self, factor_name="ROETTMDaily"):
        """ 生成Alpha因子指数 用来合成Index取回归跟踪股票基金指数 """

        self.port_name = factor_name
        self.wind_port_path = WindPortUpLoad().path
        self.data_weight_path = Index().data_path_weight
        self.data_factor_path = Index().data_data_factor
        self.alpha_data = Stock().read_factor_h5(
            factor_name,
            Stock().get_h5_path("my_alpha"))
        self.free_mv = Stock().read_factor_h5(
            "Mkt_freeshares",
            Stock().get_h5_path("mfc_primary"))
Пример #18
0
    def __init__(self):

        Data.__init__(self)
        self.sub_data_path = r'4_fund_data\stock_predict'
        self.data_path_exposure = os.path.join(self.primary_data_path, self.sub_data_path)
        self.wind_port_path = WindPortUpLoad().path

        self.stock_pct = Stock().read_factor_h5("Pct_chg").T
        self.fund_pct = Fund().get_fund_factor("Repair_Nav_Pct")
        self.bold_pct = Index().get_index_factor("885062.WI", attr=['PCT']) * 100
        self.bold_pct.columns = ['885062.WI']
        self.stock_ratio = Fund().get_fund_factor("Stock_Ratio")
        self.regression_len = 60
        self.regression_min_len = 12
Пример #19
0
    def __init__(self):

        Data.__init__(self)

        self.port_name = "主动股票基金ols"
        self.wind_port_path = WindPortUpLoad().path
        self.data_weight_path = Index().data_path_weight
        self.data_factor_path = Index().data_data_factor

        self.stock_mv = None
        self.index_return = None
        self.stock_return = None

        self.date_series = None
        self.fund_pool = None
Пример #20
0
    def get_data_from_out(self):

        file = r'C:\Users\doufucheng\OneDrive\Desktop\普通股票型基金.csv'
        port_name = '普通股票基金'
        fund_index_code = "885000.WI"

        data = pd.read_csv(file, encoding='gbk')
        date_series = list(set(data.report_period.values))
        date_series.sort()

        from quant.source.backtest import BackTest
        from quant.source.wind_portfolio import WindPortUpLoad

        wind_port_path = WindPortUpLoad().path
        sub_path = os.path.join(wind_port_path, port_name)

        if not os.path.exists(sub_path):
            os.makedirs(sub_path)

        for i_date in range(len(date_series)):
            date = date_series[i_date]
            data_date = data[data.report_period == date]

            data_gb = data_date.groupby(by=['stock_code']).sum()['weight']
            data_gb = pd.DataFrame(data_gb)
            data_gb.columns = ['Weight']
            data_gb['Weight'] = data_gb['Weight'] / data_gb['Weight'].sum()

            data_date = data_gb
            publish_date = Date().get_trade_date_offset(date, 17)
            data_date.columns = ['Weight']
            data_date.index.name = 'Code'
            data_date["CreditTrading"] = "No"
            data_date["Date"] = publish_date
            data_date["Price"] = 0.0
            data_date["Direction"] = "Long"
            file = os.path.join(sub_path,
                                '%s_%s.csv' % (port_name, publish_date))
            data_date.to_csv(file)

        backtest = BackTest()
        backtest.set_info(port_name, fund_index_code)
        backtest.read_weight_at_all_change_date()
        backtest.cal_weight_at_all_daily()
        backtest.cal_port_return(beg_date="20040101")
        backtest.cal_turnover(annual_number=4)
        backtest.cal_summary(all_beg_date="20040101")
Пример #21
0
    def __init__(self):

        Data.__init__(self)
        self.wind_data_path = WindPortUpLoad().path

        self.stock_pool_ratio = 0.60
        self.lasso_stock_pool_number = 150
        self.lasso_date_number = 60
        self.lasso_date_number_min = 40
        self.port_name = '主动股票基金Lasso'

        self.stock_mv = None
        self.index_return = None
        self.stock_return = None

        self.date_series = None
        self.fund_pool = None
Пример #22
0
    def __init__(self):

        Data.__init__(self)
        self.sub_data_path = r'4_fund_data\4_fund_holding_predict\ols_stock_weight'
        self.data_path_ols_weight = os.path.join(self.primary_data_path,
                                                 self.sub_data_path)

        self.ols_stock_pool_number = 25
        self.ols_date_number = 60
        self.ols_date_number_min = 40

        self.stock_mv = None
        self.fund_return = None
        self.stock_return = None
        self.fund_holding = None
        self.fund_stock_ratio = None

        self.date_series = None
        self.fund_pool = None
        self.wind_port_path = WindPortUpLoad().path
Пример #23
0
def get_month_wind_portfolio(file_name, date):

    project_path = r'E:\Data\portfolio\other_portfolio\exceed_expectation'
    wind_port_path = WindPortUpLoad().path
    name = "超预期30"
    stock_ratio = 0.95

    file = os.path.join(project_path, file_name)
    data = pd.read_excel(file, index_col=[0])
    data.index.name = 'Code'

    data['Weight'] = 1 / len(data)
    data['Weight'] *= stock_ratio
    data.loc['Cash', 'Weight'] = 1 - stock_ratio

    data["CreditTrading"] = "No"
    data["Date"] = date
    data["Price"] = 0.0
    data["Direction"] = "Long"

    out_sub_path = os.path.join(wind_port_path, name)
    out_file = os.path.join(out_sub_path, name + "_" + date + '.csv')
    data.to_csv(out_file)
Пример #24
0
def get_history_wind_portfolio():

    project_path = r'E:\Data\portfolio\other_portfolio\exceed_expectation'
    wind_port_path = WindPortUpLoad().path
    name = "超预期30"
    stock_ratio = 0.95

    file = os.path.join(project_path, "超预期30组合历史持仓.xlsx")
    data = pd.read_excel(file)
    data.columns = ["Date", "Code", "Weight", "Industry"]
    data["Code"] = data["Code"].map(CodeFormat().stock_code_add_postfix)
    data["Date"] = data["Date"].map(Date().change_to_str)
    data["Price"] = 0.0
    data["Direction"] = "Long"
    data["CreditTrading"] = "No"

    date_list = list(set(data["Date"]))
    date_list.sort()

    out_sub_path = os.path.join(wind_port_path, name)
    if not os.path.exists(out_sub_path):
        os.makedirs(out_sub_path)

    for i_date in range(len(date_list)):

        date = date_list[i_date]
        data_date = data[data["Date"] == date]
        data_date.index = data_date['Code']
        del data_date['Code']
        data_date['Weight'] *= stock_ratio
        data_date.loc['Cash', 'Weight'] = 1 - stock_ratio
        data_date["Price"] = 0.0
        data_date["Direction"] = "Long"
        data_date["CreditTrading"] = "No"
        data_date['Date'] = date
        out_file = os.path.join(out_sub_path, name + "_" + date + '.csv')
        data_date.to_csv(out_file)
Пример #25
0
    def upload_all_wind_port(self):

        """ 上传wind组合 """
        WindPortUpLoad().upload_weight_period(self.port_name)
Пример #26
0
 def upload_all_wind_port(self):
     """ 上传wind组合 """
     WindPortUpLoad().upload_weight_period("优选沪深300基金")
     WindPortUpLoad().upload_weight_period("优选中证500基金")
Пример #27
0
    data['Weight'] = 1 / len(data)
    data['Weight'] *= stock_ratio
    data.loc['Cash', 'Weight'] = 1 - stock_ratio

    data["CreditTrading"] = "No"
    data["Date"] = date
    data["Price"] = 0.0
    data["Direction"] = "Long"

    out_sub_path = os.path.join(wind_port_path, name)
    out_file = os.path.join(out_sub_path, name + "_" + date + '.csv')
    data.to_csv(out_file)

if __name__ == "__main__":

    #########################################################
    # get_history_wind_portfolio()
    # WindPortUpLoad().upload_weight_period("超预期30")
    #########################################################

    #########################################################
    # file_name = "超预期30组合持仓20180928.xlsx"
    # date = '20180928'
    # get_month_wind_portfolio(file_name, date)

    file_name = "超预期30组合持仓20181228.xlsx"
    date = '20181228'
    get_month_wind_portfolio(file_name, date)
    WindPortUpLoad().upload_weight_date('超预期30', date)
    #########################################################
Пример #28
0
    port_name = "行业风格平价低风险FOF"
    benchmark_code = "885002.WI"
    exposure_stock_low = 0.15
    exposure_bond_low = 0.50

    # 每期优化
    ####################################################################################################
    # date_list = Date().get_normal_date_series("20141230", "20181001", period="Q")
    # for end_date in date_list:
    #     StockFundPortfolio().opt_fund_portfolio_qp(end_date, stock_up, stock_low,
    #                                                lamb, port_path, port_name,
    #                                                exposure_stock_low, exposure_bond_low)
    #
    # 上传到wind
    ###################################################################################################
    from quant.source.wind_portfolio import WindPortUpLoad
    WindPortUpLoad().upload_weight_period(port_name)

    # 本地计算其收益
    ####################################################################################################
    from quant.source.backtest_fund import PortBackTestFund
    Index().load_index_factor(benchmark_code)
    backtest = PortBackTestFund()
    backtest.set_info(port_name, benchmark_code)
    backtest.set_weight_at_all_change_date()
    backtest.cal_turnover()
    backtest.set_weight_at_all_daily()
    backtest.cal_port_return()
    backtest.cal_summary()
    ###################################################################################################
Пример #29
0
    def wind_upload(self):

        WindPortUpLoad().upload_weight_period(self.port_name)
Пример #30
0
    style_deviate = 0.20
    position_deviate = 0.02
    fund_up_ratio = 0.15
    turnover = 0.25

    self = NiceStockFund(fund_pool_name, benchmark_name, alpha_len, alpha_column, port_name,
                         style_deviate, position_deviate, fund_up_ratio, turnover)
    # self.cal_fund_factor_alldate(beg_date, end_date)
    # self.opt_alldate(beg_date, end_date, turnover_control=True)
    # self.upload_all_wind_port()
    # self.backtest(bench_code)

    # self.cal_fund_factor_date(end_date)
    # self.opt_date(end_date, end_last_date, turnover_control=True)
    # self.generate_wind_file(end_date)
    WindPortUpLoad().upload_weight_date(port_name, end_date)

    # 2、主动股票型基金优选500AlphaIR
    fund_pool_name = "基金持仓基准基金池"
    benchmark_name = "基金持仓基准基金池"
    alpha_len = 500
    alpha_column = "RegressAlphaIR"
    port_name = "主动股票型基金优选500AlphaIR"
    beg_date = "20181201"
    end_date = "20190404"
    bench_code = "885000.WI"
    style_deviate = 0.20
    position_deviate = 0.02
    fund_up_ratio = 0.15
    turnover = 0.25