Beispiel #1
0
    def attribution_one_fund(self):
        """ 测试单个基金归因 """

        # fund_name = '建行中国人寿多策略管理计划'
        # beg_date = '20190101'
        # end_date = '20190312'
        # period_name = "2019年至今(20190312)"

        fund_name = '泰达宏利启富'
        beg_date = '20180625'
        end_date = '20190411'
        period_name = "20180625至20190411"

        param = MfcData().get_mfc_fund_info()
        param.index = param.Name
        param = param.dropna(subset=['Index'])

        index_code_ratio = param.loc[fund_name, "Index_Ratio"]
        fund_code = param.loc[fund_name, "Code"]
        index_code = param.loc[fund_name, "Index"]
        type = param.loc[fund_name, "Type"]
        trust_fee = param.loc[fund_name, "TrusteeShipFeeRatio"]
        mg_fee = param.loc[fund_name, "MgFeeRatio"]
        mg_fee_ratio = trust_fee + mg_fee

        self.get_info(index_code_ratio, index_code, fund_code, fund_name, type,
                      beg_date, end_date, period_name, mg_fee_ratio)
        self.attribution_fund()
    def get_input_data(self, fund_code, fund_name, inside_fund_name,
                       fund_strategy, asset_allocation_strategy,
                       comparsion_bench_list, date, fund_manager):
        """
        输入基金名称 基金代码 当日日期
        得到最近的交易日、季报日、半年报年报日
        得到基金净值数据、季报和半年报持仓数据
        """

        self.fund_code = fund_code
        self.fund_name = fund_name
        self.date = date
        self.fund_strategy = fund_strategy
        self.inside_fund_name = inside_fund_name
        self.asset_allocation_strategy = asset_allocation_strategy
        self.last_trade_date = Date().get_trade_date_offset(date, 0)
        print("参数时间", self.last_trade_date)
        if fund_code == fund_name:
            self.fund_nav = MfcData().get_mfc_private_fund_nav(fund_name)
            self.fund_nav = pd.DataFrame(self.fund_nav['累计复权净值'])
            self.fund_nav.columns = ['NAV_ADJ']
        else:
            self.fund_nav = MfcData().get_mfc_public_fund_nav(self.fund_code)
        fund_hold_stock = MfcData().get_fund_security(self.last_trade_date)
        fund_hold_stock = fund_hold_stock[fund_hold_stock['基金名称'] ==
                                          self.inside_fund_name]
        fund_hold_stock = pd.DataFrame(fund_hold_stock['市值比净值(%)'].values,
                                       index=fund_hold_stock['证券代码'],
                                       columns=['Weight'])
        fund_hold_stock.index = fund_hold_stock.index.map(
            CodeFormat().stock_code_add_postfix)
        fund_hold_stock['Weight'] /= 100.0
        self.fund_hold_stock = fund_hold_stock
        self.comparsion_bench_list = comparsion_bench_list
        self.fund_manager = fund_manager
Beispiel #3
0
    def attribution_all_fund(self, date_list):
        """ 归因所有基准不为空的基金 给定所有时间段 """

        param = MfcData().get_mfc_fund_info()
        param.index = param.Name
        param = param.dropna(subset=['Index'])
        print(param.index)

        for i_date in range(len(date_list)):

            beg_date = date_list[i_date][0]
            end_date = date_list[i_date][1]
            period_name = date_list[i_date][2]

            for i_fund in range(0, len(param)):

                fund_name = param.index[i_fund]
                index_code_ratio = param.loc[fund_name, "Index_Ratio"]
                fund_code = param.loc[fund_name, "Code"]
                index_code = param.loc[fund_name, "Index"]
                type = param.loc[fund_name, "Type"]
                trust_fee = param.loc[fund_name, "TrusteeShipFeeRatio"]
                mg_fee = param.loc[fund_name, "MgFeeRatio"]
                mg_fee_ratio = trust_fee + mg_fee

                self.get_info(index_code_ratio, index_code, fund_code,
                              fund_name, type, beg_date, end_date, period_name,
                              mg_fee_ratio)
                self.attribution_fund()
    def mfcteda_fund_excess_return(self, end_date, fund_type, fund_code,
                                   fund_name, benchmark_code, benchmark_ratio):
        """ 计算1个基金今年所有月份超额收益 """

        date_pd = self.get_date_pd(end_date)

        if fund_type == "公募":
            fund_data = MfcData().get_mfc_public_fund_nav(fund_code)
            fund_data = fund_data['NAV_ADJ']
        else:
            fund_data = MfcData().get_mfc_private_fund_nav(fund_name)
            fund_data = fund_data['累计复权净值']

        benchmark_data = Index().get_index_factor(benchmark_code,
                                                  attr=["CLOSE"])
        return_pd = pd.DataFrame([],
                                 columns=date_pd.columns,
                                 index=[fund_name])

        for i in date_pd.columns:

            beg_date = date_pd.ix["beg_date", i]
            end_date = date_pd.ix["end_date", i]
            fs = FinancialSeries(
                pd.DataFrame(fund_data),
                pd.DataFrame(benchmark_data) * benchmark_ratio)
            try:
                return_pd.ix[fund_name, i] = fs.get_interval_excess_return(
                    beg_date, end_date)
            except Exception as e:
                pass

        return return_pd
Beispiel #5
0
    def load_holding_data(self):
        """ 从网盘下载持仓文件 并修改名字 """

        lmd = MfcData()
        lmd.load_network_holding_date(date=self.today)
        lmd.load_network_stock_pool_date(date=self.today)
        lmd.change_holding_date(date=self.today)
    def get_input_data(self, fund_code, fund_name, fund_strategy,
                       asset_allocation_strategy, bench_code, date,
                       fund_manager):
        """
        输入基金名称 基金代码 当日日期
        得到最近的交易日、季报日、半年报年报日
        得到基金净值数据、季报和半年报持仓数据
        """

        self.fund_code = fund_code
        self.fund_name = fund_name
        self.date = date
        self.fund_strategy = fund_strategy
        self.asset_allocation_strategy = asset_allocation_strategy
        self.last_trade_date = Date().get_trade_date_offset(date, 0)
        self.quarter_date = Date().get_last_fund_quarter_date(date)
        self.halfyear_date = Date().get_last_fund_halfyear_date(date)
        print("参数时间", self.last_trade_date, self.quarter_date,
              self.halfyear_date)
        self.fund_nav = MfcData().get_mfc_public_fund_nav(self.fund_code)
        self.fund_top10_stock = Fund().get_fund_top10_stock_date(
            self.fund_code, self.quarter_date)
        self.fund_top10_stock /= 100.0
        self.fund_all_stock = Fund().get_fund_all_stock_date(
            self.fund_code, self.halfyear_date)
        self.fund_all_stock /= 100.0
        self.bench_code = bench_code
        self.fund_manager = fund_manager
Beispiel #7
0
    def get_fund_asset(self):
        """
        得到某只基金资产、指数涨跌幅、基金涨跌幅
        总资产包括 净值、基金份额、单位净值;股票、债券、现金、回购资产;买卖金额;股票债券浮动金额、总盈亏金额
        """

        fund_asset = MfcData().get_fund_asset_period(self.fund_name,
                                                     self.beg_date_pre,
                                                     self.end_date)
        fund_pct = self.get_fund_pct()
        index_pct = self.get_index_pct()

        # 数据合并
        data = pd.concat([fund_pct, index_pct, fund_asset], axis=1)
        data = data.dropna(subset=['基金涨跌幅', '指数涨跌幅'])
        print(data.head())

        if len(data) <= 0:
            data = None
        else:
            data['单位净值'] = data['净值'] / data['基金份额']
            data['昨日净值'] = data['净值'].shift(1)
            data['昨日基金份额'] = data['基金份额'].shift(1)
            data['昨日单位净值'] = data['单位净值'].shift(1)
        return data
    def get_mfcteda_all_rank(self, end_date):
        """ 计算所有基金今年所有月份排名 """

        path = MfcData().data_path
        file = os.path.join(path, "static_data", "Fund_Info_For_Month.xlsx")
        params = pd.read_excel(file, encoding='gbk')
        params = params.dropna(subset=['Rank'])
        params = params.reset_index(drop=True)

        for i in range(len(params)):

            fund_name = params.ix[i, 'Name']
            fund_code = params.ix[i, 'Code']
            rank_pool = params.ix[i, 'Fund_Pool']
            excess = params.ix[i, 'Rank']
            print(fund_name)

            if i == 0:
                return_pd = self.mfcteda_fund_rank(end_date, fund_code,
                                                   fund_name, rank_pool,
                                                   excess)
            else:
                return_pd_add = self.mfcteda_fund_rank(end_date, fund_code,
                                                       fund_name, rank_pool,
                                                       excess)
                return_pd = pd.concat([return_pd, return_pd_add], axis=0)

        return return_pd
    def get_mfcteda_all_excess_return(self, end_date):
        """ 计算所有基金今年所有月份超额收益 """

        path = MfcData().data_path
        file = os.path.join(path, "static_data", "Fund_Info_For_Month.xlsx")
        params = pd.read_excel(file, encoding='gbk')
        params = params.dropna(subset=['Index_Ratio'])
        params = params.reset_index(drop=True)

        for i in range(len(params)):

            fund_type = params.ix[i, 'Type']
            fund_name = params.ix[i, 'Name']
            fund_code = params.ix[i, 'Code']
            benchmark_code = params.ix[i, 'Index']
            benchmark_ratio = params.ix[i, 'Index_Ratio']
            print(fund_name)

            if i == 0:
                return_pd = self.mfcteda_fund_excess_return(
                    end_date, fund_type, fund_code, fund_name, benchmark_code,
                    benchmark_ratio)
            else:
                return_pd_add = self.mfcteda_fund_excess_return(
                    end_date, fund_type, fund_code, fund_name, benchmark_code,
                    benchmark_ratio)
                return_pd = pd.concat([return_pd, return_pd_add], axis=0)

        return return_pd
Beispiel #10
0
    def cal_summary_table_enhanced_fund(fund_name,
                                        fund_code,
                                        fund_type,
                                        date_array,
                                        benchmark_code,
                                        benchmark_name,
                                        benchmark_ratio=1.0):
        """
        指数型基金表现总结
        分区间计算 基金和基准表现(累计收益 年化收益 超额收益 跟踪误差 信息比率 超额收益最大回撤等)
        """

        # 分类读取基金数据
        fund_data = MfcData().get_mfc_nav(fund_code, fund_name, fund_type)
        benchmark_data = Index().get_index_factor(benchmark_code,
                                                  attr=["CLOSE"])

        enhanced_table = pd.DataFrame([], columns=date_array[:, 0])
        fs = FinancialSeries(pd.DataFrame(fund_data),
                             pd.DataFrame(benchmark_data), benchmark_ratio)

        for i_date in range(date_array.shape[0]):
            label = date_array[i_date, 0]
            bd = Date().change_to_str(date_array[i_date, 1])
            ed = Date().change_to_str(date_array[i_date, 2])

            enhanced_table.loc[fund_name + "累计收益",
                               label] = fs.get_interval_return(bd, ed)
            enhanced_table.loc[benchmark_name + "累计收益",
                               label] = fs.get_interval_return_benchmark(
                                   bd, ed)
            bench_return = fs.get_interval_return_benchmark_ratio(bd, ed)
            enhanced_table.loc[benchmark_name + "*%s累计收益" % benchmark_ratio,
                               label] = bench_return
            enhanced_table.loc[fund_name + "超额收益",
                               label] = fs.get_interval_excess_return(bd, ed)
            enhanced_table.loc[fund_name + "超额年化收益",
                               label] = fs.get_interval_excess_return_annual(
                                   bd, ed)
            enhanced_table.loc[fund_name + "跟踪误差",
                               label] = fs.get_interval_tracking_error(bd, ed)
            enhanced_table.loc[fund_name + "信息比率",
                               label] = fs.get_interval_mean_ir(bd, ed)
            enhanced_table.loc[
                fund_name + "超额收益最大回撤",
                label] = fs.get_interval_excess_return_max_drawdown(bd, ed)
            enhanced_table.loc[fund_name + "标准差",
                               label] = fs.get_interval_std_annual(bd, ed)
            enhanced_table.loc[fund_name + "夏普比率",
                               label] = fs.get_interval_shape_ratio(
                                   bd, ed, 0.03)
            enhanced_table.loc[fund_name + "最大回撤",
                               label] = fs.get_interval_max_drawdown(bd, ed)
            enhanced_table.loc[fund_name + "年化收益",
                               label] = fs.get_interval_return_annual(bd, ed)
            enhanced_table.loc[
                benchmark_name + "年化收益",
                label] = fs.get_interval_return_annual_benchmark(bd, ed)

        return enhanced_table
Beispiel #11
0
    def update_data(date):
        """更新数据"""

        # 更新日期
        beg_date = Date().get_trade_date_offset(date, -5)
        end_date = date

        # 更新因子数据(原始和alpha)
        Stock().load_h5_primary_factor()

        AlphaBP().cal_factor_exposure(beg_date, end_date)
        AlphaROE().cal_factor_exposure(beg_date, end_date)
        AlphaProfitYoY().cal_factor_exposure(beg_date, end_date)
        AlphaIncomeYoY().cal_factor_exposure(beg_date, end_date)

        # 更新基金净值 和 持仓数据 指数价格数据
        # Fund().load_fund_holding_all("19991231", datetime.today())
        MfcData().load_mfc_public_fund_nav()
        update_end_date = datetime.today().strftime("%Y%m%d")
        update_beg_date = Date().get_trade_date_offset(update_end_date, -5)

        Index().load_index_factor(index_code='H00985.CSI',
                                  beg_date=update_beg_date,
                                  end_date=update_end_date)
        Index().load_index_factor(index_code="885001.WI",
                                  beg_date=update_beg_date,
                                  end_date=update_end_date)
        Index().load_index_factor(index_code="000300.SH",
                                  beg_date=update_beg_date,
                                  end_date=update_end_date)
        Index().load_index_factor(index_code="000905.SH",
                                  beg_date=update_beg_date,
                                  end_date=update_end_date)
    def get_fund_basic_info(self):
        """ wind 得到基金的基本信息 类型 成立日期 最新规模等等 """

        data = w.wss(self.fund_code, "fund_setupdate,fund_investtype",
                     "unit=1;tradeDate=%s" % self.last_trade_date)
        data_pd = pd.DataFrame(data.Data,
                               index=data.Fields,
                               columns=data.Codes).T
        data_pd.columns = ['成立日期', '基金类型']
        data_pd['成立日期'] = data_pd['成立日期'].map(lambda x: x.strftime("%Y%m%d"))

        fund_asset_data = MfcData().get_fund_asset(self.last_trade_date)
        fund_asset_data = fund_asset_data[fund_asset_data['基金名称'] ==
                                          self.inside_fund_name]
        fund_asset = fund_asset_data['净值'].values[0] / 100000000.0

        data_pd['基金规模(亿)'] = np.round(fund_asset, 2)
        data_pd = data_pd.T
        data_info = pd.DataFrame([self.fund_code, self.fund_name],
                                 columns=[self.fund_code],
                                 index=['基金代码', '基金名称'])
        data_concat = pd.concat([data_info, data_pd], axis=0)
        data_concat.columns = ['内容']
        data_concat['基本信息'] = data_concat.index
        data_concat = data_concat[['基本信息', '内容']]
        return data_concat
Beispiel #13
0
    def cal_stock_fee(self, date):
        """
        计算股票的 管理托管费(当日净值*管理费率)
        交易佣金(当日股票成交额*交易费率,包括新股)
        """

        date_pre = Date().get_trade_date_offset(date, -1)
        try:
            total_asset_pre = MfcData().get_fund_asset(date_pre)
            trade = self.get_stock_trading(date)
        except Exception as e:
            print(e)
            return np.nan, np.nan

        total_asset_fund = total_asset_pre[total_asset_pre['基金名称'] ==
                                           self.fund_name]
        try:
            mg_fee = -total_asset_fund['净值'].values[0] * self.mg_fee_ratio
        except Exception as e:
            print(e)
            mg_fee = np.nan

        trade_asset = (trade['TradePrice'] * trade['TradeVol'].abs()).sum()
        trade_fee = -trade_asset * self.double_fee_ratio / 2.0
        return mg_fee, trade_fee
Beispiel #14
0
    def get_stock_trading(self, date):
        """ 读取股票交易数据 """

        try:
            trade = MfcData().get_trade_statement(date)
            trade_data = trade[trade['基金名称'] == self.fund_name]
            trade_data = trade_data[trade_data['资产类别'] == '股票资产']
            trade_data = trade_data[[
                '基金名称', '证券名称', '成交数量', '市场成交均价', '委托方向', '证券代码'
            ]]
            trade_data['证券代码'] = trade_data['证券代码'].map(
                CodeFormat().stock_code_add_postfix)
            trade_data.index = trade_data['证券代码'].values
            trade_data = trade_data[['成交数量', '市场成交均价', '委托方向']]
            trade_data.columns = ['TradeVol', 'TradePrice', 'SellOrBuy']
            trade_data = trade_data[~trade_data.index.duplicated()]
            sell_code_list = list(
                trade_data[trade_data['SellOrBuy'] == "卖出"].index)
            trade_data.loc[sell_code_list,
                           'TradeVol'] = -trade_data.loc[sell_code_list,
                                                         'TradeVol']
            return trade_data
        except Exception as e:
            print(e)
            return None
Beispiel #15
0
def load_mfc_holding_data(today):

    lmd = MfcData()
    # today = datetime.today()
    # today = datetime(2018, 6, 27).strftime("%Y%m%d")

    lmd.load_holding_date(date=today)
    lmd.load_stock_pool_date(date=today)
    lmd.change_holding_date(date=today)
Beispiel #16
0
    def cal_summary_table(fund_name, fund_code, fund_type, date_array,
                          benchmark_array):
        """
        主动股票型基金表现总结
        分区间计算 基金表现(累计收益 年化收益 年化波动 最大回撤 收益波动比)
        分区间计算 分基准 计算基准表现(累计收益 年化收益 年化波动 最大回撤 收益波动比)
        """

        # 分类读取基金数据
        fund_data = MfcData().get_mfc_nav(fund_code, fund_name, fund_type)
        performance_table = pd.DataFrame([], columns=date_array[:, 0])
        fs = FinancialSeries(pd.DataFrame(fund_data),
                             pd.DataFrame([], columns=['nav']))

        for i_date in range(date_array.shape[0]):

            label = date_array[i_date, 0]
            bd = Date().change_to_str(date_array[i_date, 1])
            ed = Date().change_to_str(date_array[i_date, 2])
            performance_table.ix[fund_name + "累计收益",
                                 label] = fs.get_interval_return(bd, ed)
            performance_table.ix[fund_name + "年化收益",
                                 label] = fs.get_interval_return_annual(
                                     bd, ed)
            performance_table.ix[fund_name + "年化波动",
                                 label] = fs.get_interval_std_annual(bd, ed)
            performance_table.ix[fund_name + "最大回撤",
                                 label] = fs.get_interval_max_drawdown(bd, ed)
            performance_table.ix[fund_name + "收益波动比",
                                 label] = fs.get_interval_return_std_ratio(
                                     bd, ed)

        for i_benchmark in range(benchmark_array.shape[0]):

            benchmark_name = benchmark_array[i_benchmark, 0]
            benchmark_code = benchmark_array[i_benchmark, 1]
            benchmark_data = Index().get_index_factor(benchmark_code,
                                                      attr=["CLOSE"])
            fs = FinancialSeries(pd.DataFrame(benchmark_data),
                                 pd.DataFrame([], columns=['nav']))

            for i_date in range(date_array.shape[0]):
                label = date_array[i_date, 0]
                bd = Date().change_to_str(date_array[i_date, 1])
                ed = Date().change_to_str(date_array[i_date, 2])

                performance_table.loc[benchmark_name + "累计收益",
                                      label] = fs.get_interval_return(bd, ed)
                performance_table.loc[benchmark_name + "年化收益",
                                      label] = fs.get_interval_return_annual(
                                          bd, ed)
                performance_table.loc[benchmark_name + "年化波动",
                                      label] = fs.get_interval_std_annual(
                                          bd, ed)
                performance_table.loc[benchmark_name + "最大回撤",
                                      label] = fs.get_interval_max_drawdown(
                                          bd, ed)

        return performance_table
Beispiel #17
0
    def update_data(self):

        """ 下载数据 需要更新 富时指数的数据 """

        today = datetime.today()
        beg_date = Date().get_trade_date_offset(today, -120)
        Index().load_index_factor("000907.CSI", beg_date, today)
        MfcData().load_mfc_public_fund_nav(beg_date, today)
def Cal_MfcFund_LastDate_Holding_Exposure(path, report_date, today):
    """
    计算部门基金最近一个半年报 的持仓风格暴露
    """
    # 参数举例
    #####################################################################
    # path = 'E:\\3_Data\\4_fund_data\\8_fund_index_exposure_weekly\\'
    # report_date = '20171231'
    # today = datetime.today().strftime("%Y%m%d")

    # 基金池
    #####################################################################
    fund_pool_file = os.path.join(path, "fund_pool", '重点基金信息.csv')
    fund_pool = pd.read_csv(fund_pool_file, index_col=[0], encoding='gbk')
    fund_pool = fund_pool[fund_pool['种类'].map(
        lambda x: x in ["1部门量化", '1专户量化'])]
    date = Date().get_trade_date_offset(report_date, 0)
    beg_date = Date().get_trade_date_offset(report_date, -10)
    end_date = today

    # 计算部门基金  基金最近交易日 的持仓风格暴露
    #####################################################################
    for i_fund in range(len(fund_pool)):

        fund_code = fund_pool.index[i_fund]
        fund_type = fund_pool.loc[fund_code, '种类']
        if fund_type == '1专户量化':
            fund_name = fund_code
        else:
            fund_name = MfcData().get_mfc_fund_name(fund_code)
        MfcData().cal_mfc_holding_barra_exposure_period(
            fund_name, beg_date, end_date)

        if i_fund == 0:
            exposure = MfcData().get_mfc_holding_barra_exposure_date(
                fund_name, date)
            exposure['CTY'] = MfcData().get_mfc_stock_ratio(fund_name, date)
        else:
            exposure_add = MfcData().get_mfc_holding_barra_exposure_date(
                fund_name, date)
            exposure_add['CTY'] = MfcData().get_mfc_stock_ratio(
                fund_name, date)
            exposure = pd.concat([exposure, exposure_add], axis=0)

    #####################################################################
    exposure_file = os.path.join(path, "lastyear_holding_exposure",
                                 'FundLastDateExposure_' + date + '.csv')
    exposure.to_csv(exposure_file)
    def update_data(self):
        """ 更新基金净值 和 持仓数据 指数价格数据"""

        Fund().update_fund_holding()
        MfcData().load_mfc_public_fund_nav()
        Index().load_index_factor(index_code='H00985.CSI',
                                  beg_date="20040101",
                                  end_date=datetime.today())
        Index().load_index_factor(index_code="885001.WI",
                                  beg_date="20180101",
                                  end_date=datetime.today())
Beispiel #20
0
    def update_data(self):
        """ 更新归因需要的数据 """

        today = datetime.today().strftime("%Y%m%d")
        today = Date().get_trade_date_offset(today, -1)
        beg_date = Date().get_trade_date_offset(today, -25)

        Barra().load_barra_data()
        MfcData().cal_mfc_private_fund_nav_all()
        MfcData().load_mfc_public_fund_nav()

        param = MfcData().get_mfc_fund_info()
        param.index = param.Name

        for i_fund in range(0, len(param)):
            fund_name = param.index[i_fund]
            MfcData().cal_mfc_holding_barra_exposure_period(
                fund_name, beg_date, today)

        date_series = Date().get_trade_date_series(beg_date, today)
        for date in date_series:
            Index().make_weight_mixed(date)
            Index().load_index_factor_all(beg_date, today)

        Index().cal_index_exposure("000300.SH", beg_date, today)
        Index().cal_index_exposure("000905.SH", beg_date, today)
        Index().cal_index_exposure("881001.WI", beg_date, today)
        Index().cal_index_exposure("中证500+创业板综+中小板综", beg_date, today)
    def update_data(self):

        """ 更新基金净值 和 持仓数据 指数价格数据"""

        Fund().update_fund_holding()
        MfcData().load_mfc_public_fund_nav()
        update_end_date = datetime.today().strftime("%Y%m%d")
        update_beg_date = Date().get_trade_date_offset(update_end_date, -40)

        Index().load_index_factor(index_code='H00985.CSI', beg_date=update_beg_date, end_date=update_end_date)
        Index().load_index_factor(index_code="885001.WI", beg_date=update_beg_date, end_date=update_end_date)
        Index().load_index_factor(index_code="000300.SH", beg_date=update_beg_date, end_date=update_end_date)
        Index().load_index_factor(index_code="000905.SH", beg_date=update_beg_date, end_date=update_end_date)
Beispiel #22
0
    def get_stock_holding(self, date):
        """ 读取股票持仓数据"""

        try:
            security = MfcData().get_fund_security(date)
            security_data = security[security['基金名称'] == self.fund_name]
            security_data = security_data[security_data['证券类别'] == '股票']
            security_data = security_data[['基金名称', '证券名称', '持仓', '证券代码']]
            security_data['证券代码'] = security_data['证券代码'].map(
                CodeFormat().stock_code_add_postfix)
            security_data.index = security_data['证券代码'].values
            security_data = security_data[['证券名称', '持仓']]
            return security_data
        except Exception as e:
            print(e)
            return None
Beispiel #23
0
def return_fund(end_date, fund_code, fund_name, mage_date):

    """ 某个基金收益率 """

    today = datetime.strptime(end_date, "%Y%m%d")
    before_1y = datetime(year=today.year - 1, month=today.month, day=today.day).strftime("%Y%m%d")
    before_2y = datetime(year=today.year - 2, month=today.month, day=today.day).strftime("%Y%m%d")
    before_3y = datetime(year=today.year - 3, month=today.month, day=today.day).strftime("%Y%m%d")
    before_5y = datetime(year=today.year - 5, month=today.month, day=today.day).strftime("%Y%m%d")
    before_10y = datetime(year=today.year - 10, month=today.month, day=today.day).strftime("%Y%m%d")

    date_array = np.array([
        ["2019年", "20190101", end_date, '20180930'],
        ["2018年", '20180101', "20181231", '20170930'],
        ["2017年", "20170101", '20171231', "20160930"],
        ["2016年", "20160101", '20161231', "20150930"],
        ["2015年", "20150101", '20151231', "20140930"],
        ["2014年", "20140101", '20141231', "20130930"],
        ["2013年", "20130101", '20131231', "20120930"],
        ["2012年", "20120101", '20121231', "20110930"],
        ["2011年", "20110101", '20111231', "20100930"],
        ["2010年", "20100101", '20101231', "20090930"],
        ["2009年", "20090101", '20091231', "20080930"],
        ["2008年", "20080101", '20081231', "20070930"],
        ["2007年", "20070101", '20071231', "20060930"],
        ["成立以来", mage_date, end_date, mage_date],
        ["过去1年", before_1y, end_date, before_1y],
        ["过去2年", before_2y, end_date, before_2y],
        ["过去3年", before_3y, end_date, before_3y],
        ["过去5年", before_5y, end_date, before_5y],
        ["过去10年", before_10y, end_date, before_10y],
    ])


    performance_table = pd.DataFrame([], index=[fund_name])
    for i_date in range(len(date_array)):
        label = date_array[i_date, 0]
        beg_date = date_array[i_date, 1]
        end_date = date_array[i_date, 2]
        if beg_date >= str(int(mage_date)):
            fund_nav = MfcData().get_mfc_public_fund_nav(fund_code)
            fs = FinancialSeries(pd.DataFrame(fund_nav['NAV_ADJ']))
            performance_table.ix[fund_name, label] = fs.get_interval_return(beg_date, end_date)
        else:
            performance_table.ix[fund_name, label] = "NAN"
    print(performance_table)
    return performance_table
Beispiel #24
0
    def get_report_industry_change(self, fund_name, report_date,
                                   last_report_date):
        """ 报告期之间的权重变动 """

        # report_date = "20181231"
        # last_report_date = "20180930"
        # fund_name = "泰达逆向策略"

        report_date = Date().get_trade_date_offset(report_date, 0)
        last_report_date = Date().get_trade_date_offset(last_report_date, 0)
        print(fund_name, report_date, last_report_date)

        data_report = MfcData().get_fund_stock_weight(fund_name=fund_name,
                                                      date=report_date)
        data_report.columns = ['NowHolder']
        data_report = data_report[~data_report.index.duplicated()]

        data_report_last = MfcData().get_fund_stock_weight(
            fund_name=fund_name, date=last_report_date)
        data_report_last.columns = ['LastHolder']
        data_report_last = data_report_last[~data_report_last.index.duplicated(
        )]

        industry = Stock().read_factor_h5("industry_citic1")
        industry_date = pd.DataFrame(industry[report_date])
        industry_date.columns = ['Industry']

        data_report_last_industry = pd.concat(
            [data_report_last, industry_date], axis=1)
        data_report_last_industry = data_report_last_industry.dropna()
        data_last_gb = pd.DataFrame(
            data_report_last_industry.groupby(
                by=['Industry']).sum()['LastHolder'])

        data_report_industry = pd.concat([data_report, industry_date], axis=1)
        data_report_industry = data_report_industry.dropna()
        data_gb = pd.DataFrame(
            data_report_industry.groupby(by=['Industry']).sum()['NowHolder'])

        data = pd.concat([data_last_gb, data_gb], axis=1)
        data.index = data.index.map(
            lambda x: Stock().get_industry_citic1_name_ch(x))
        data['Diff'] = data['NowHolder'] - data['LastHolder']
        data = data.sort_values(by=['Diff'], ascending=False)

        data_bigger = data.iloc[0:3, :]
        str1 = "本报告期内,本基金增加了" + "、".join(data_bigger.index) + "的配置"

        data = data.sort_values(by=['Diff'], ascending=True)
        data_smaller = data.iloc[0:3, :]

        str2 = ",减少了" + "、".join(data_smaller.index) + '的配置。'

        return str1 + str2
Beispiel #25
0
    def get_fund_pct(self):
        """ 产品某一段时间内的涨跌幅,专户公募分开 """

        if self.type == "专户":
            fund_pct = MfcData().get_mfc_private_fund_nav(self.fund_name)
            fund_pct['基金涨跌幅'] = fund_pct['累计复权净值'].pct_change()
            fund_pct = fund_pct[['累计复权净值', '基金涨跌幅']]
            fund_pct = fund_pct.dropna()
            fund_pct = fund_pct.loc[self.beg_date_pre:self.end_date, :]
        else:
            fund_pct = MfcData().get_mfc_public_fund_nav(self.fund_code)
            fund_pct = fund_pct[['NAV_ADJ', 'NAV_ADJ_RETURN1']]
            fund_pct['NAV_ADJ_RETURN1'] = fund_pct['NAV_ADJ'].pct_change()
            fund_pct.columns = ['累计复权净值', '基金涨跌幅']
            fund_pct = fund_pct.dropna()
            fund_pct = fund_pct.loc[self.beg_date_pre:self.end_date, :]

        return fund_pct
    def get_fund_asset_allocation(self):

        """ 资产配置(股票、债券、基金、现金占比)"""

        fund_asset_data = MfcData().get_fund_asset(self.last_trade_date)
        fund_asset_data = fund_asset_data[fund_asset_data['基金名称'] == self.inside_fund_name]
        fund_asset_data['现金'] = fund_asset_data['当前现金余额'] + fund_asset_data['回购资产'] + \
                           fund_asset_data['累计应收金额'] - fund_asset_data['累计应付金额']

        asset = fund_asset_data['净值'].values[0] / 100000000.0
        stock = fund_asset_data['股票资产'].values[0] / 100000000.0
        bond = fund_asset_data['债券资产'].values[0] / 100000000.0
        cash = fund_asset_data['现金'].values[0] / 100000000.0
        fund = fund_asset_data['基金资产'].values[0] / 100000000.0

        data_pd = pd.DataFrame([stock, bond, fund, cash], index = ['股票', '债券', '基金', '现金'],
                               columns=['占净值比'])
        data_pd /= asset
        data_pd['资产配置(%s)' % self.last_trade_date] = data_pd.index
        data_pd = data_pd[['资产配置(%s)' % self.last_trade_date, '占净值比']]
        return data_pd
    def get_mfcteda_all_return(self, end_date):
        """ 计算所有基金今年所有月份收益 """

        path = MfcData().data_path
        file = os.path.join(path, "static_data", "Fund_Info_For_Month.xlsx")
        params = pd.read_excel(file, encoding='gbk')

        for i in range(len(params)):

            fund_type = params.ix[i, 'Type']
            fund_name = params.ix[i, 'Name']
            fund_code = params.ix[i, 'Code']
            print(fund_name)
            if i == 0:
                return_pd = self.mfcteda_fund_return(end_date, fund_type,
                                                     fund_code, fund_name)
            else:
                return_pd_add = self.mfcteda_fund_return(
                    end_date, fund_type, fund_code, fund_name)
                return_pd = pd.concat([return_pd, return_pd_add], axis=0)

        return return_pd
    def mfcteda_fund_return(self, end_date, fund_type, fund_code, fund_name):
        """ 计算1个基金今年所有月份收益 """

        date_pd = self.get_date_pd(end_date)
        fund_data = MfcData().get_mfc_nav(fund_code, fund_name, fund_type)

        return_pd = pd.DataFrame([],
                                 columns=date_pd.columns,
                                 index=[fund_name])

        for i in date_pd.columns:

            beg_date = date_pd.ix["beg_date", i]
            end_date = date_pd.ix["end_date", i]

            fs = FinancialSeries(pd.DataFrame(fund_data))
            try:
                return_pd.ix[fund_name,
                             i] = fs.get_interval_return(beg_date, end_date)
            except Exception as e:
                pass
        return return_pd
Beispiel #29
0
    def cal_summary_table_sample(fund_name, fund_code, fund_type, date_array,
                                 benchmark_array):
        """
        主动股票型基金表现总结(简单版)
        分区间计算 基金表现 累计收益
        分区间计算 分基准 计算基准累计收益
        """

        fund_data = MfcData().get_mfc_nav(fund_code, fund_name, fund_type)
        performance_table = pd.DataFrame([], columns=date_array[:, 0])
        fs = FinancialSeries(pd.DataFrame(fund_data),
                             pd.DataFrame([], columns=['nav']))

        for i_date in range(date_array.shape[0]):
            label = date_array[i_date, 0]
            bd = Date().change_to_str(date_array[i_date, 1])
            ed = Date().change_to_str(date_array[i_date, 2])
            print("Cal Interval Return ", bd, ed)
            performance_table.ix[fund_name + "累计收益",
                                 label] = fs.get_interval_return(bd, ed)

        for i_benchmark in range(benchmark_array.shape[0]):

            benchmark_name = benchmark_array[i_benchmark, 0]
            benchmark_code = benchmark_array[i_benchmark, 1]
            benchmark_data = Index().get_index_factor(benchmark_code,
                                                      attr=["CLOSE"])
            fs = FinancialSeries(pd.DataFrame(benchmark_data),
                                 pd.DataFrame([], columns=['nav']))

            for i_date in range(date_array.shape[0]):
                label = date_array[i_date, 0]
                bd = Date().change_to_str(date_array[i_date, 1])
                ed = Date().change_to_str(date_array[i_date, 2])
                performance_table.ix[benchmark_name + "累计收益",
                                     label] = fs.get_interval_return(bd, ed)

        return performance_table
Beispiel #30
0
    def get_futures_holding(self, date, name):
        """ 读取期货持仓数据 """

        if name == "股指期货多头":
            state = "多仓"
        else:
            state = "空仓"

        try:
            security = MfcData().get_fund_security(date)
            security_data = security[security['基金名称'] == self.fund_name]
            security_data = security_data[security_data['证券类别'] == '股指期货']
            security_data = security_data[security_data['持仓多空标志'] == state]
            security_data = security_data[[
                '基金名称', '证券名称', '持仓', '证券代码', '最新价', '市值', '持仓多空标志'
            ]]
            security_data[
                '价格'] = security_data['市值'] / security_data['持仓'] / 200.0
            security_data.index = security_data['证券代码'].values
            security_data = security_data[['证券名称', '市值', '价格', '持仓']]
            return security_data
        except Exception as e:
            print(e)
            return None