### Attribution Analysis Setup Example Source: https://github.com/joinquant/jqfactor_analyzer/blob/master/docs/API文档.md Example demonstrating how to load portfolio weights and daily returns from CSV files and initialize the AttributionAnalysis class. It specifies the style and industry types for the analysis. ```python import pandas as pd # position_weights.csv 是一个储存了组合权重信息的csv文件,index是日期,columns是股票代码 # position_daily_return.csv 是一个储存了组合日收益率的csv文件,index是日期,daily_return列是日收益 weights = pd.read_csv("position_weights.csv",index_col=0) returns = pd.read_csv("position_daily_return.csv",index_col=0)['daily_return'] An = AttributionAnalysis(weights , returns ,style_type='style_pro',industry ='sw_l1', show_data_progress=True ) ``` -------------------------------- ### Cache and Retrieve Factor Data Example Source: https://github.com/joinquant/jqfactor_analyzer/blob/master/docs/API文档.md Example demonstrating how to cache factor data for a specified date range and then retrieve it day by day. It involves fetching all growth factors, saving them under a group name, and then iterating through trade days to get cached values. ```python from jqfactor_analyzer.factor_cache import save_factor_values_by_group,get_factor_values_by_cache,get_factor_folder,get_cache_dir # import jqdatasdk as jq # jq.auth("账号",'密码') #登陆jqdatasdk来从服务端缓存数据 all_factors = jq.get_all_factors() factor_names = all_factors[all_factors.category=='growth'].factor.tolist() #将聚宽因子库中的成长类因子作为一组因子 group_name = 'growth_factors' #因子组名定义为'growth_factors' start_date = '2021-01-01' end_date = '2021-06-01' # 检查/缓存因子数据 factor_path = save_factor_values_by_group(start_date,end_date,factor_names=factor_names,group_name=group_name,overwrite=False,show_progress=True) # factor_path = os.path.join(get_cache_dir(), get_factor_folder(factor_names,group_name=group_name) #等同于save_factor_values_by_group返回的路径 # 循环获取缓存的因子数据,并拼接 trade_days = jq.get_trade_days(start_date,end_date) factor_values = {} for date in trade_days: factor_values[date] = get_factor_values_by_cache(date,codes=None,factor_names=factor_names,group_name=group_name, factor_path=factor_path)#这里实际只需要指定group_name,factor_names参数的其中一个,缓存时指定了group_name时,factor_names不生效 factor_values = pd.concat(factor_values) ``` -------------------------------- ### Install and Upgrade jqfactor_analyzer Source: https://github.com/joinquant/jqfactor_analyzer/blob/master/README.md Use pip to install or upgrade the library in your Python environment. ```bash pip install jqfactor_analyzer ``` ```bash pip install -U jqfactor_analyzer ``` -------------------------------- ### Factor Analysis with jqdatasdk Authentication Source: https://github.com/joinquant/jqfactor_analyzer/blob/master/docs/API文档.md Example demonstrating how to authenticate with jqdatasdk and perform factor analysis using analyze_factor. It includes setting up factor data, quantiles, periods, industry, weighting method, and max loss. ```python import pandas as pd import jqfactor_analyzer as ja import jqdatasdk jqdatasdk.auth('username', 'password') far = ja.analyze_factor( factor_data, # factor_data 为因子值的 pandas.DataFrame quantiles=10, periods=(1, 10), industry='jq_l1', weight_method='avg', max_loss=0.1 ) ``` -------------------------------- ### Get Factor Data using jqdatasdk Source: https://github.com/joinquant/jqfactor_analyzer/blob/master/docs/API文档.md Demonstrates how to retrieve factor data, such as 5-day average turnover (VOL5), from the JoinQuant Factor Library using the `jqdatasdk`. This data can be directly used for factor analysis. ```APIDOC ## GET /api/jqdatasdk/get_factor_values ### Description Retrieves factor data from the JoinQuant Factor Library. This example shows how to get the 5-day average turnover (VOL5) for stocks in the CSI 300 index. ### Method GET ### Endpoint /api/jqdatasdk/get_factor_values ### Parameters #### Query Parameters - **securities** (list) - Required - A list of security identifiers (e.g., stock codes). - **factors** (list) - Required - A list of factor names to retrieve (e.g., ['VOL5']). - **start_date** (string) - Required - The start date for the data in 'YYYY-MM-DD' format. - **end_date** (string) - Required - The end date for the data in 'YYYY-MM-DD' format. ### Request Example ```python import jqdatasdk jqdatasdk.auth('username', 'password') factor_data = jqdatasdk.get_factor_values( securities=jqdatasdk.get_index_stocks('000300.XSHG'), factors=['VOL5'], start_date='2018-01-01', end_date='2018-12-31' )['VOL5'] ``` ### Response #### Success Response (200) - **factor_data** (object) - A dictionary containing the requested factor data, keyed by factor name. #### Response Example ```json { "VOL5": { "000001.XSHE": [0.01, 0.012, ...], "000002.XSHE": [0.015, 0.013, ...], ... } } ``` ``` -------------------------------- ### Get Exposure to Benchmark Source: https://github.com/joinquant/jqfactor_analyzer/blob/master/docs/API文档.md Retrieves the portfolio's exposure to various benchmark factors, including style, industry, and country. The output is a DataFrame indexed by date with columns representing the exposure factors. ```python get_exposure2bench(index_symbol) **参数 :** - `index_symbol` : 基准指数, 可选`['000300.XSHG','000905.XSHG','000906.XSHG','000852.XSHG','932000.CSI','000985.XSHG']`中的一个 **返回 :** - 一个dataframe,index为日期,columns为风格因子+行业因子+county , 其中country为股票总持仓占比 ``` -------------------------------- ### Get Daily Attribution Returns vs. Benchmark Source: https://github.com/joinquant/jqfactor_analyzer/blob/master/docs/API文档.md Calculates daily attribution returns of a portfolio relative to a benchmark index. The returns are decomposed into style, industry, cash, common, specific, and total returns. Requires specifying a benchmark index symbol. ```python get_attr_daily_returns2bench(index_symbol) ``` -------------------------------- ### Get Factor Data with jqdatasdk Source: https://github.com/joinquant/jqfactor_analyzer/blob/master/README.md Use jqdatasdk to fetch factor data, such as 5-day average turnover rate, for factor analysis. Ensure you authenticate with your username and password. ```python import jqdatasdk jqdatasdk.auth('username', 'password') # 获取聚宽因子库中的VOL5数据 factor_data=jqdatasdk.get_factor_values( securities=jqdatasdk.get_index_stocks('000300.XSHG'), factors=['VOL5'], start_date='2018-01-01', end_date='2018-12-31')['VOL5'] ``` -------------------------------- ### Get Cumulative Attribution Returns vs. Benchmark Source: https://github.com/joinquant/jqfactor_analyzer/blob/master/docs/API文档.md Calculates cumulative attribution returns of a portfolio relative to a benchmark index. Similar to daily returns, it breaks down returns into style, industry, cash, common, specific, and total components. Requires specifying a benchmark index symbol. ```python get_attr_returns2bench(index_symbol) ``` -------------------------------- ### Get Cumulative Returns Relative to Benchmark Source: https://github.com/joinquant/jqfactor_analyzer/blob/master/README.md Retrieves the first 5 rows of cumulative returns relative to a benchmark index for a given security. Requires the 'An' object to be initialized. ```python An.get_attr_returns2bench('000905.XSHG').head(5) #查看相对指数的累积收益 ``` -------------------------------- ### Initialize jqdatasdk and jqfactor_analyzer Source: https://github.com/joinquant/jqfactor_analyzer/blob/master/README.md Import the necessary modules and authenticate with your JoinQuant credentials to access data services. ```python import jqdatasdk import jqfactor_analyzer as ja # 获取 jqdatasdk 授权,输入用户名、密码,申请地址:https://www.joinquant.com/default/index/sdk # 聚宽官网,使用方法参见:https://www.joinquant.com/help/api/doc?name=JQDatadoc jqdatasdk.auth("账号", "密码") ``` -------------------------------- ### Get Factor Folder Name Source: https://github.com/joinquant/jqfactor_analyzer/blob/master/docs/API文档.md Determines the folder name for a factor group within the cache directory. Generates a name based on factor names if not explicitly provided. ```python def get_factor_folder(factor_names,group_name=None): """获取因子组的文件夹名(文件夹位于get_cache_dir()获取的缓存目录下) factor_names : 因子储存时,如果未指定group_name,则根据因子列表(顺序无关)获取md5值生成因子组名(即储存的文件夹名),使用此方法可以获取生成的文件夹名称 group_name : 如果储存时指定了因子组名,则直接返回此因子组名 """ ``` -------------------------------- ### Analyze 5-day average turnover factor Source: https://github.com/joinquant/jqfactor_analyzer/blob/master/README.md Demonstrates loading sample factor data and running the analyze_factor function to compute IC values. ```python # 载入函数库 import pandas as pd import jqfactor_analyzer as ja # 获取5日平均换手率因子2018-01-01到2018-12-31之间的数据(示例用从库中直接调取) # 聚宽因子库数据获取方法在下方 from jqfactor_analyzer.sample import VOL5 factor_data = VOL5 # 对因子进行分析 far = ja.analyze_factor( factor_data, # factor_data 为因子值的 pandas.DataFrame quantiles=10, periods=(1, 10), industry='jq_l1', weight_method='avg', max_loss=0.1 ) # 获取整理后的因子的IC值 far.ic ``` -------------------------------- ### Attribution Analysis Initialization Source: https://context7.com/joinquant/jqfactor_analyzer/llms.txt Initializes the AttributionAnalysis object with portfolio weights, daily returns, and model parameters. ```APIDOC ## Attribution Analysis Initialization Attribution analysis decomposes portfolio returns into sources like style factors, industry factors, country factors, and idiosyncratic returns (alpha). ### `AttributionAnalysis` Constructor - **Description**: Initializes the AttributionAnalysis object. - **Parameters**: - **`weights`** (pandas.DataFrame) - Portfolio weights. Index should be dates, columns should be stock codes, and values should be weights. Daily weights sum should be <= 1. - **`daily_return`** (pandas.Series) - Portfolio daily returns. Index should be dates. - **`style_type`** (str) - Type of style factors: 'style' or 'style_pro'. - **`industry`** (str) - Industry classification: 'sw_l1' (Shenwan Level 1) or 'jq_l1' (JoinQuant Level 1). - **`use_cn`** (bool) - Whether to use Chinese labels in plots. - **`show_data_progress`** (bool) - Whether to display data fetching progress. ### Example Usage ```python import pandas as pd import jqdatasdk from jqfactor_analyzer import AttributionAnalysis jqdatasdk.auth('username', 'password') # Prepare portfolio weights data weights = pd.DataFrame({ '000001.XSHE': [0.1, 0.12, 0.11], '000002.XSHE': [0.15, 0.14, 0.16], '600000.XSHG': [0.2, 0.18, 0.19] }, index=pd.to_datetime(['2020-01-02', '2020-01-03', '2020-01-06'])) # Prepare portfolio daily return data daily_return = pd.Series( [0.002, 0.005, -0.003], index=pd.to_datetime(['2020-01-02', '2020-01-03', '2020-01-06']) ) # Create an AttributionAnalysis object An = AttributionAnalysis( weights=weights, daily_return=daily_return, style_type='style_pro', industry='sw_l1', use_cn=True, show_data_progress=True ) # Access attribution analysis attributes style_exp = An.style_exposure # Portfolio style factor exposure industry_exp = An.industry_exposure # Portfolio industry factor exposure all_exp = An.exposure_portfolio # Full exposure (style + industry + country) daily_attr = An.attr_daily_returns # Daily attribution returns cum_attr = An.attr_returns # Cumulative attribution returns ``` ``` -------------------------------- ### Initialize Attribution Analysis Source: https://github.com/joinquant/jqfactor_analyzer/blob/master/docs/API文档.md Initializes the AttributionAnalysis class for performing attribution analysis on portfolio returns. Requires weights, daily returns, and specifies style and industry types. ```python from jqfactor_analyzer import AttributionAnalysis AttributionAnalysis(weights,daily_return,style_type='style_pro',industry ='sw_l1',use_cn=True,show_data_progress=True) ``` -------------------------------- ### Perform Single Factor Analysis Source: https://context7.com/joinquant/jqfactor_analyzer/llms.txt Initializes the analysis process by authenticating with JoinQuant, retrieving factor data, and executing the analyze_factor function to generate a full tear sheet. ```python import pandas as pd import jqdatasdk import jqfactor_analyzer as ja # 登录聚宽数据服务 jqdatasdk.auth('username', 'password') # 获取因子数据示例:5日平均换手率 factor_data = jqdatasdk.get_factor_values( securities=jqdatasdk.get_index_stocks('000300.XSHG'), factors=['VOL5'], start_date='2018-01-01', end_date='2018-12-31' )['VOL5'] # 执行单因子分析 far = ja.analyze_factor( factor=factor_data, # 因子值 DataFrame,index为日期,columns为股票代码 industry='jq_l1', # 行业分类:jq_l1/jq_l2/sw_l1/sw_l2/sw_l3/zjw quantiles=10, # 分位数数量 periods=(1, 5, 10), # 调仓周期列表 weight_method='avg', # 加权方式:avg/mktcap/ln_mktcap/cmktcap/ln_cmktcap max_loss=0.1, # 允许丢弃的因子数据最大比例 allow_cache=True, # 是否启用本地缓存 show_data_progress=True # 是否显示数据获取进度 ) # 生成完整分析报告(包含所有图表) far.create_full_tear_sheet( demeaned=False, # 是否使用超额收益 group_adjust=False, # 是否使用行业中性收益 by_group=False, # 是否按行业展示 turnover_periods=None, # 换手率分析周期 avgretplot=(5, 15), # 因子预测天数(过去, 未来) std_bar=False # 是否显示标准差 ) ``` -------------------------------- ### Get Factor Values by Cache Source: https://github.com/joinquant/jqfactor_analyzer/blob/master/docs/API文档.md Retrieves factor data from local cache files for a specific date. Returns an empty DataFrame if the cache file does not exist. Requires group_name or factor_path if specified during saving. ```python def get_factor_values_by_cache(date,codes=None,factor_names=None,group_name=None, factor_path=None): """从缓存的文件读取因子数据,文件不存在时返回空的dataframe date : 日期 codes : 标的代码,默认为None获取当天在市的所有标的 factor_names : 因子列表(顺序无关),当指定factor_path/group_name时失效 group_name : 因子组名,如果缓存时指定了group_name,则获取时必须也指定group_name或factor_path factor_path : 可选参数,因子组的路径,一般不用指定 返回: 如果缓存文件存在,则返回当天的因子数据,index是标的代码,columns是因子名 如果缓存文件不存在,则返回空的dataframe, 建议在使用get_factor_values_by_cache前,先运行save_factor_values_by_group检查时间区间内的缓存文件是否完整 """ ``` -------------------------------- ### Generate FactorAnalyzer Visualizations Source: https://context7.com/joinquant/jqfactor_analyzer/llms.txt Produces statistical tables and charts to visualize factor characteristics, including IC analysis and turnover metrics. ```python # 打印统计表格 far.plot_quantile_statistics_table() # 各分位数统计表 far.plot_returns_table(demeaned=False, group_adjust=False) # 因子收益表 far.plot_turnover_table() # 换手率表 far.plot_information_table(group_adjust=False, method='rank') # IC统计表 # IC分析图 far.plot_ic_ts(group_adjust=False, method='rank') # IC时间序列图 far.plot_ic_hist(group_adjust=False, method='rank') # IC分布直方图 far.plot_ic_qq(group_adjust=False, method='rank', theoretical_dist='norm') # IC QQ图 far.plot_ic_by_group(group_adjust=False, method='rank') # 分行业IC图 far.plot_monthly_ic_heatmap(group_adjust=False) # 月度IC热力图 ``` -------------------------------- ### Perform Attribution Analysis Source: https://context7.com/joinquant/jqfactor_analyzer/llms.txt Initialize an attribution analysis object to decompose portfolio returns into style, industry, and specific components. ```python import pandas as pd import jqdatasdk from jqfactor_analyzer import AttributionAnalysis jqdatasdk.auth('username', 'password') # 准备持仓权重数据 # index为日期,columns为股票代码,values为权重(各日权重和应<=1,剩余为现金) weights = pd.DataFrame({ '000001.XSHE': [0.1, 0.12, 0.11], '000002.XSHE': [0.15, 0.14, 0.16], '600000.XSHG': [0.2, 0.18, 0.19] }, index=pd.to_datetime(['2020-01-02', '2020-01-03', '2020-01-06'])) # 准备组合日收益率数据 daily_return = pd.Series( [0.002, 0.005, -0.003], index=pd.to_datetime(['2020-01-02', '2020-01-03', '2020-01-06']) ) # 创建归因分析对象 An = AttributionAnalysis( weights=weights, # 持仓权重DataFrame daily_return=daily_return, # 组合日收益率Series style_type='style_pro', # 风格因子类型:'style' 或 'style_pro' industry='sw_l1', # 行业分类:'sw_l1' 或 'jq_l1' use_cn=True, # 是否使用中文图例 show_data_progress=True # 是否显示数据获取进度 ) # 访问归因分析属性 style_exp = An.style_exposure # 组合风格因子暴露 industry_exp = An.industry_exposure # 组合行业因子暴露 all_exp = An.exposure_portfolio # 完整暴露(风格+行业+country) daily_attr = An.attr_daily_returns # 日度归因收益 cum_attr = An.attr_returns # 累积归因收益 ``` -------------------------------- ### View Cumulative Returns Source: https://github.com/joinquant/jqfactor_analyzer/blob/master/README.md Use the .head(5) method to display the first 5 rows of cumulative returns. This is useful for a quick inspection of recent performance. ```python An.attr_returns.head(5) #查看累积收益 ``` -------------------------------- ### 查看因子暴露度 Source: https://github.com/joinquant/jqfactor_analyzer/blob/master/README.md 调用 exposure_portfolio 属性查看计算出的因子暴露度。 ```python An.exposure_portfolio.head(5) #查看暴露 ``` -------------------------------- ### Calculate and Display Daily Weight Sums Source: https://github.com/joinquant/jqfactor_analyzer/blob/master/README.md Calculates the sum of weights for each day and displays the first 5 results. This helps verify that the daily weight sums are less than 1, as required. ```python weight_infos.sum(axis=1).head(5) ``` -------------------------------- ### Plot Exposure and Returns Comparison Source: https://github.com/joinquant/jqfactor_analyzer/blob/master/docs/API文档.md Creates a comparative plot of factor exposures and returns. Can display factor performance and relative to a benchmark index. Requires specifying the type of factors, optionally the benchmark index, whether to show factor performance, and figure size. ```python plot_exposure_and_returns(factors='style',index_symbol=None,show_factor_perf=False,figsize=(12,6)) ``` -------------------------------- ### Visualize Factor Performance Source: https://context7.com/joinquant/jqfactor_analyzer/llms.txt Methods for plotting various factor performance metrics such as quantile returns, cumulative returns, turnover, and predictive capability. ```python far.plot_quantile_returns_bar(by_group=False, demeaned=False, group_adjust=False) # 分位数收益柱状图 far.plot_quantile_returns_violin(demeaned=False, group_adjust=False) # 分位数收益小提琴图 far.plot_mean_quantile_returns_spread_time_series(demeaned=False, group_adjust=False) # 多空收益时序图 # 累积收益图 far.plot_cumulative_returns(period=1, demeaned=False, group_adjust=False) # 因子加权组合累积收益 far.plot_top_down_cumulative_returns(period=1, demeaned=False, group_adjust=False) # 多空组合累积收益 far.plot_cumulative_returns_by_quantile(period=1, demeaned=False, group_adjust=False) # 各分位数累积收益 # 换手率分析图 far.plot_top_bottom_quantile_turnover(periods=(1, 3, 9)) # 最高最低分位换手率 far.plot_factor_auto_correlation(periods=None, rank=True) # 因子自相关图 # 因子预测能力图 far.plot_quantile_average_cumulative_return( periods_before=5, # 过去天数 periods_after=10, # 未来天数 by_quantile=False, # 是否分分位数显示 std_bar=False, # 是否显示标准差 demeaned=False, group_adjust=False ) # 有效因子数量统计 far.plot_events_distribution(num_days=5) # 关闭中文图例(解决乱码问题) far.plot_disable_chinese_label() ``` -------------------------------- ### Load Weight and Return Data Source: https://github.com/joinquant/jqfactor_analyzer/blob/master/README.md Loads weight information from a CSV file and separates the daily returns into a pandas Series. Ensure the weight data has dates as index and stock codes as columns, with daily sums less than 1. ```python import os import pandas as pd weight_path = os.path.join(os.path.dirname(ja.__file__), 'sample_data', 'weight_info.csv') weight_infos = pd.read_csv(weight_path, index_col=0) daily_return = weight_infos.pop("return") ``` -------------------------------- ### Calculate Top-Down Cumulative Returns Source: https://github.com/joinquant/jqfactor_analyzer/blob/master/docs/API文档.md Computes daily cumulative returns for a long-short portfolio using a top-down approach. ```python far.calc_top_down_cumulative_returns(period=5, demeaned=False, group_adjust=False) ``` -------------------------------- ### Calculate Average Cumulative Returns by Quantile Source: https://github.com/joinquant/jqfactor_analyzer/blob/master/docs/API文档.md Calculates the mean and standard deviation of future and past returns based on daily quantiles. ```python far.calc_average_cumulative_return_by_quantile(periods_before=5, periods_after=15, demeaned=False, group_adjust=False) ``` -------------------------------- ### Calculate Factor Returns Weighted by Factor Values Source: https://github.com/joinquant/jqfactor_analyzer/blob/master/docs/API文档.md Computes daily returns for a long-short portfolio weighted by factor values. Options include demeaning weights for a cash-neutral portfolio (`demeaned=True`) or demeaning by industry for an industry-neutral portfolio (`group_adjust=True`). ```python far.calc_factor_returns(demeaned=True, group_adjust=False) ``` -------------------------------- ### Plot Quantile Statistics Table Source: https://github.com/joinquant/jqfactor_analyzer/blob/master/docs/API文档.md Prints a table of statistics for each quantile. ```python far.plot_quantile_statistics_table() ``` -------------------------------- ### Plot Daily Cumulative Returns by Quantile Source: https://github.com/joinquant/jqfactor_analyzer/blob/master/docs/API文档.md Plots the daily cumulative returns for different quantiles. Supports multiple periods for rebalancing. Use `demeaned=True` for excess returns and `group_adjust=True` for industry-neutral returns. ```python far.plot_cumulative_returns_by_quantile(period=(1, 3, 9), demeaned=False, group_adjust=False) ``` -------------------------------- ### Portfolio Attribution Methods Source: https://github.com/joinquant/jqfactor_analyzer/blob/master/docs/API文档.md Methods to calculate daily and cumulative attribution returns of a portfolio relative to a benchmark index. ```APIDOC ## get_attr_daily_returns2bench(index_symbol) ### Description 获取组合相对于指数的日度归因收益率。 ### Parameters #### Path Parameters - **index_symbol** (string) - Required - 基准指数, 可选['000300.XSHG','000905.XSHG','000906.XSHG','000852.XSHG','932000.CSI','000985.XSHG'] ### Response - **dataframe** (object) - index为日期, columns为风格因子+行业因子+cash+common_return, specific_return, total_return --- ## get_attr_returns2bench(index_symbol) ### Description 获取相对于指数的累积归因收益率。 ### Parameters #### Path Parameters - **index_symbol** (string) - Required - 基准指数, 可选['000300.XSHG','000905.XSHG','000906.XSHG','000852.XSHG','932000.CSI','000985.XSHG'] ### Response - **dataframe** (object) - index为日期, columns为风格因子+行业因子+cash+common_return, specific_return, total_return ``` -------------------------------- ### Calculate Cumulative Returns by Quantile Source: https://github.com/joinquant/jqfactor_analyzer/blob/master/docs/API文档.md Computes daily cumulative returns for each quantile given a specific rebalancing period. ```python far.calc_cumulative_return_by_quantile(period=None, demeaned=False, group_adjust=False) ``` -------------------------------- ### Visualize Attribution Results Source: https://context7.com/joinquant/jqfactor_analyzer/llms.txt Methods to plot factor exposures and return attribution results. ```python # 绘制风格/行业暴露时序图 An.plot_exposure( factors='style', # 'style'(风格)/'industry'(行业)/因子名列表 index_symbol=None, # 指定时绘制相对于指数的暴露 figsize=(15, 7) ) # 绘制相对于中证500的暴露 An.plot_exposure(factors='style', index_symbol='000905.XSHG') # 绘制行业暴露 An.plot_exposure(factors='industry', index_symbol=None) # 绘制归因收益时序图 An.plot_returns( factors='style', # 'style'/'industry'/因子名列表/['common_return','specific_return','total_return'] index_symbol=None, # 指定时绘制相对于指数的收益 figsize=(15, 7) ) # 绘制相对于基准的特异收益 An.plot_returns(factors=['common_return', 'specific_return', 'total_return'], index_symbol='000905.XSHG') # 同时绘制暴露和收益对照图 An.plot_exposure_and_returns( factors='style', # 'style'/'industry'/因子名列表 index_symbol=None, # 基准指数 show_factor_perf=False, # 是否同时绘制因子表现 figsize=(12, 6) # (宽度, 单个子图高度) ) ``` -------------------------------- ### Visualization Methods Source: https://github.com/joinquant/jqfactor_analyzer/blob/master/docs/API文档.md Methods for plotting factor exposures, attribution returns, and exposure-return comparisons. ```APIDOC ## plot_exposure(factors='style', index_symbol=None, figsize=(15,7)) ### Description 绘制风格暴露时序图。 ## plot_returns(factors='style', index_symbol=None, figsize=(15,7)) ### Description 绘制归因分析收益时序图。 ## plot_exposure_and_returns(factors='style', index_symbol=None, show_factor_perf=False, figsize=(12,6)) ### Description 将因子暴露与收益同时绘制在多个子图上。 ## plot_disable_chinese_label() ### Description 关闭中文图例显示,强制使用英文。 ``` -------------------------------- ### Attribution Analysis Module Source: https://github.com/joinquant/jqfactor_analyzer/blob/master/docs/API文档.md This module facilitates attribution analysis of portfolio performance by breaking down returns into style, industry, and country components. ```APIDOC ## Attribution Analysis Module This module facilitates attribution analysis of portfolio performance by breaking down returns into style, industry, and country components. ### Initialization To perform attribution analysis, instantiate the `AttributionAnalysis` class with the necessary portfolio and market data. ```python from jqfactor_analyzer import AttributionAnalysis AttributionAnalysis(weights, daily_return, style_type='style_pro', industry='sw_l1', use_cn=True, show_data_progress=True) ``` **Parameters:** - `weights` (pd.DataFrame): Portfolio weights information. Index should be dates, columns should be security codes, and values represent the portfolio's position percentage for that day. The sum of daily weights may not be 1, with the remainder considered cash. - `daily_return` (pd.Series): A Series of daily portfolio returns. Index should be dates. - `style_type` (str): The type of style factors to use for attribution. Options are 'style' or 'style_pro'. - `industry` (str): The industry classification to use. Options are 'sw_l1' (Shenwan Level 1) or 'jq_l1' (JQ Level 1). - `use_cn` (bool): Whether to use Chinese characters for plotting. Defaults to `True`. - `show_data_progress` (bool): Whether to display data loading progress. Defaults to `True`. Initial runs might be slow as local data is cached. ### Example Usage ```python import pandas as pd from jqfactor_analyzer import AttributionAnalysis # Load portfolio weights and daily returns from CSV files weights = pd.read_csv("position_weights.csv", index_col=0) returns = pd.read_csv("position_daily_return.csv", index_col=0)['daily_return'] # Initialize AttributionAnalysis An = AttributionAnalysis(weights, returns, style_type='style_pro', industry='sw_l1', show_data_progress=True) ``` ### Attributes The `AttributionAnalysis` object provides several attributes containing computed data: - `style_exposure`: Portfolio's exposure to style factors. - `industry_exposure`: Portfolio's exposure to industry factors. - `exposure_portfolio`: Portfolio's combined exposure to style, industry, and country factors. - `attr_daily_returns`: Daily attribution returns for style, industry, and country factors. - `attr_returns`: Cumulative daily attribution returns for style, industry, and country factors. ### Methods #### `get_exposure2bench` Retrieves the portfolio's exposure relative to a benchmark index. **Parameters:** - `index_symbol` (str): The symbol of the benchmark index. Options include '000300.XSHG', '000905.XSHG', '000906.XSHG', '000852.XSHG', '932000.CSI', '000985.XSHG'. **Returns:** - `pd.DataFrame`: A DataFrame with dates as the index and columns representing style factors, industry factors, and country (total holdings percentage). This DataFrame shows the portfolio's exposure to these factors relative to the benchmark. ```python # Get exposure relative to the CSI 300 index exposure_vs_benchmark = An.get_exposure2bench(index_symbol='000300.XSHG') ``` ``` -------------------------------- ### Calculate Cumulative Returns for Weighted Portfolio Source: https://github.com/joinquant/jqfactor_analyzer/blob/master/docs/API文档.md Computes daily cumulative returns for a factor-weighted long-short portfolio. ```python far.calc_cumulative_returns(period=5, demeaned=False, group_adjust=False) ``` -------------------------------- ### Display First 5 Rows of Weight Data Source: https://github.com/joinquant/jqfactor_analyzer/blob/master/README.md Displays the first 5 rows of the loaded weight information DataFrame. This is useful for a quick inspection of the data structure and content. ```python weight_infos.head(5) ``` -------------------------------- ### Create Event Returns Tear Sheet Source: https://github.com/joinquant/jqfactor_analyzer/blob/master/docs/API文档.md Generates a tear sheet for event-driven returns. `avgretplot` defines the lookback and forward days for average returns. `demeaned=True` and `group_adjust=True` control the use of excess and industry-neutralized returns, respectively. ```python far.create_event_returns_tear_sheet(avgretplot=(5, 15),demeaned=False, group_adjust=False,std_bar=False) ``` -------------------------------- ### Plot Factor Exposure and Returns Source: https://github.com/joinquant/jqfactor_analyzer/blob/master/README.md Combines visualization of factor exposure and returns in a single view. ```python An.plot_exposure_and_returns(factors='style',index_symbol=None,show_factor_perf=False,figsize=(12,6)) ``` -------------------------------- ### Plot Information Table Source: https://github.com/joinquant/jqfactor_analyzer/blob/master/docs/API文档.md Prints a table related to information coefficients (IC). Use `group_adjust=True` for industry-neutralized returns and `method='rank'` for rank correlation. ```python far.plot_information_table(group_adjust=False, method='rank') ``` -------------------------------- ### Calculate Daily Information Coefficient (IC) Source: https://github.com/joinquant/jqfactor_analyzer/blob/master/docs/API文档.md Computes the daily IC values for a factor, with options for industry adjustment and grouping. ```python far.calc_factor_information_coefficient(group_adjust=False, by_group=False, method='rank') ``` -------------------------------- ### Execute FactorAnalyzer Calculation Methods Source: https://context7.com/joinquant/jqfactor_analyzer/llms.txt Performs deep analysis using specific calculation methods. These methods support custom parameters for metrics like IC, alpha/beta, and cumulative returns. ```python # 计算分位数收益(支持多种参数组合) mean_ret, std_ret = far.calc_mean_return_by_quantile( by_date=True, # 是否按日期分组 by_group=False, # 是否按行业分组 demeaned=False, # 是否使用超额收益 group_adjust=False # 是否使用行业中性收益 ) # 计算因子加权组合收益 factor_returns = far.calc_factor_returns( demeaned=True, # 对权重去均值,转为cash-neutral组合 group_adjust=False # 对权重分行业去均值,转为industry-neutral组合 ) # 计算因子alpha和beta alpha_beta = far.calc_factor_alpha_beta(demeaned=True, group_adjust=False) # 计算IC值 ic = far.calc_factor_information_coefficient( group_adjust=False, # 是否使用行业中性收益 by_group=False, # 是否分行业计算 method='rank' # 计算方法:'rank'(秩相关) 或 'normal'(皮尔逊相关) ) # 计算IC均值 mean_ic = far.calc_mean_information_coefficient( group_adjust=False, by_group=False, by_time='M', # 时间粒度:'Y'按年/'M'按月/None全部 method='rank' ) # 计算累积收益 cum_ret = far.calc_cumulative_returns( period=5, # 调仓周期 demeaned=False, group_adjust=False ) # 计算各分位数累积收益 cum_ret_by_q = far.calc_cumulative_return_by_quantile( period=5, demeaned=False, group_adjust=False ) # 计算因子自相关性 autocorr = far.calc_autocorrelation(rank=True) # rank=True使用秩相关 # 滞后n天因子自相关性 autocorr_lag = far.calc_autocorrelation_n_days_lag(n=10, rank=False) # 滞后n天IC均值 ic_lag = far.calc_ic_mean_n_days_lag( n=10, group_adjust=False, by_group=False, method='rank' ) ``` -------------------------------- ### 生成因子分析报告 Source: https://github.com/joinquant/jqfactor_analyzer/blob/master/README.md 调用 create_full_tear_sheet 生成因子分析的完整图表和统计数据。参数可用于配置去均值、分组调整及收益计算周期。 ```python far.create_full_tear_sheet( demeaned=False, group_adjust=False, by_group=False, turnover_periods=None, avgretplot=(5, 15), std_bar=False ) ``` -------------------------------- ### Formatting Factor Data into DataFrame Source: https://github.com/joinquant/jqfactor_analyzer/blob/master/docs/API文档.md This section covers how to convert your factor data into a pandas DataFrame with the correct index and column formats required by the library. ```APIDOC ## Formatting Factor Data into DataFrame ### Description This section details how to format your factor data into a pandas DataFrame, ensuring the index is a `DatetimeIndex` and columns adhere to the specified stock code format (e.g., '000001.XSHE' for Shenzhen, '000001.XSHG' for Shanghai). ### Method **1. Converting existing DataFrame:** Ensure the index is `DatetimeIndex` using `pd.to_datetime` and sort it using `sort_index()`. **2. Converting a dictionary of Series:** Directly use `pd.DataFrame(your_dict).T` to convert a dictionary where keys are dates and values are pandas Series of stock factors. ### Request Example ```python import pandas as pd # Example 1: Converting an existing DataFrame sample_data_df = pd.DataFrame( [[0.84, 0.43, 2.33, 0.86, 0.96], [1.06, 0.51, 2.60, 0.90, 1.09], [1.12, 0.54, 2.68, 0.94, 1.12], [1.07, 0.64, 2.65, 1.33, 1.15], [1.21, 0.73, 2.97, 1.65, 1.19]], index=['2018-01-02', '2018-01-03', '2018-01-04', '2018-01-05', '2018-01-08'], columns=['000001.XSHE', '000002.XSHE', '000063.XSHE', '000069.XSHE', '000100.XSHE'] ) factor_data_df = sample_data_df.copy() factor_data_df.index = pd.to_datetime(factor_data_df.index) factor_data_df = factor_data_df.sort_index() # Example 2: Converting a dictionary of Series sample_data_dict = {'2018-01-02': pd.Series([0.84, 0.43, 2.33, 0.86, 0.96], index=['000001.XSHE', '000002.XSHE', '000063.XSHE', '000069.XSHE', '000100.XSHE']), '2018-01-03': pd.Series([1.06, 0.51, 2.60, 0.90, 1.09], index=['000001.XSHE', '000002.XSHE', '000063.XSHE', '000069.XSHE', '000100.XSHE']), '2018-01-04': pd.Series([1.12, 0.54, 2.68, 0.94, 1.12], index=['000001.XSHE', '000002.XSHE', '000063.XSHE', '000069.XSHE', '000100.XSHE']), '2018-01-05': pd.Series([1.07, 0.64, 2.65, 1.33, 1.15], index=['000001.XSHE', '000002.XSHE', '000063.XSHE', '000069.XSHE', '000100.XSHE']), '2018-01-08': pd.Series([1.21, 0.73, 2.97, 1.65, 1.19], index=['000001.XSHE', '000002.XSHE', '000063.XSHE', '000069.XSHE', '000100.XSHE'])} factor_data_dict = pd.DataFrame(sample_data_dict).T print(factor_data_df) print(factor_data_dict) ``` ``` -------------------------------- ### POST /factor/returns Source: https://github.com/joinquant/jqfactor_analyzer/blob/master/docs/API文档.md Performs factor returns analysis. ```APIDOC ## POST /factor/returns ### Description Performs factor returns analysis. ### Parameters #### Request Body - **demeaned** (boolean) - Optional - True: use excess returns; False: use raw returns - **group_adjust** (boolean) - Optional - True: use industry-neutral returns; False: use raw returns - **by_group** (boolean) - Optional - True: plot average returns by quantile for each industry; False: do not plot ``` -------------------------------- ### Retrieve Factor Data via jqdatasdk Source: https://github.com/joinquant/jqfactor_analyzer/blob/master/docs/API文档.md Connects to the JoinQuant data SDK to retrieve historical factor values. ```python # 获取因子数据:以5日平均换手率为例,该数据可以直接用于因子分析 # 具体使用方法可以参照jqdatasdk的API文档 import jqdatasdk jqdatasdk.auth('username', 'password') # 获取聚宽因子库中的VOL5数据 factor_data=jqdatasdk.get_factor_values( securities=jqdatasdk.get_index_stocks('000300.XSHG'), factors=['VOL5'], start_date='2018-01-01', end_date='2018-12-31')['VOL5'] ``` -------------------------------- ### Access Monthly Information Ratio Source: https://github.com/joinquant/jqfactor_analyzer/blob/master/docs/API文档.md Retrieves a DataFrame containing the monthly Information Ratio (IC) for factors. The index represents months, and columns represent rebalancing periods. This is a lazy property, computed upon access. ```python far.ic_monthly ``` -------------------------------- ### Plot Factor Returns Table Source: https://github.com/joinquant/jqfactor_analyzer/blob/master/docs/API文档.md Prints a table of factor returns. Set `demeaned=True` to use excess returns and `group_adjust=True` for industry-neutralized returns. ```python far.plot_returns_table(demeaned=False, group_adjust=False) ``` -------------------------------- ### Save Factor Data to Cache Source: https://github.com/joinquant/jqfactor_analyzer/blob/master/README.md Downloads and saves factor data locally by group for efficient retrieval. ```python from jqfactor_analyzer.factor_cache import save_factor_values_by_group,get_factor_values_by_cache,get_factor_folder,get_cache_dir # import jqdatasdk as jq # jq.auth("账号",'密码') #登陆jqdatasdk来从服务端缓存数据 all_factors = jqdatasdk.get_all_factors() factor_names = all_factors[all_factors.category=='growth'].factor.tolist() #将聚宽因子库中的成长类因子作为一组因子 group_name = 'growth_factors' #因子组名定义为'growth_factors' start_date = '2021-01-01' end_date = '2021-06-01' # 检查/缓存因子数据 factor_path = save_factor_values_by_group(start_date,end_date,factor_names=factor_names,group_name=group_name,overwrite=False,show_progress=True) # factor_path = os.path.join(get_cache_dir(), get_factor_folder(factor_names,group_name=group_name) #等同于save_factor_values_by_group返回的路径 ``` -------------------------------- ### Plot Factor Turnover Table Source: https://github.com/joinquant/jqfactor_analyzer/blob/master/docs/API文档.md Prints a table summarizing factor turnover. ```python far.plot_turnover_table() ``` -------------------------------- ### Set Factor Cache Directory Source: https://github.com/joinquant/jqfactor_analyzer/blob/master/README.md Configures the local directory where factor data will be cached. ```python from jqfactor_analyzer.factor_cache import set_cache_dir,get_cache_dir # my_path = 'E:\\jqfactor_cache' # set_cache_dir(my_path) #设置缓存目录为my_path print(get_cache_dir()) #输出缓存目录 ``` -------------------------------- ### Calculate Factor Alpha and Beta Source: https://github.com/joinquant/jqfactor_analyzer/blob/master/docs/API文档.md Computes the annual alpha and beta for a factor-weighted portfolio. ```python far.calc_factor_alpha_beta(demeaned=True, group_adjust=False) ``` -------------------------------- ### Access Mean Return by Date and Quantile Source: https://github.com/joinquant/jqfactor_analyzer/blob/master/docs/API文档.md Retrieves a DataFrame of weighted average factor returns grouped by date and quantile. The index is a MultiIndex of date and quantile, and columns represent rebalancing periods. This is a lazy property, computed upon access. ```python far.mean_return_by_date ``` -------------------------------- ### Plot Factor Returns Source: https://github.com/joinquant/jqfactor_analyzer/blob/master/README.md Visualizes the returns associated with style factors. ```python An.plot_returns(factors='style',index_symbol=None,figsize=(15,7)) ``` -------------------------------- ### Create Factor Returns Tear Sheet Source: https://github.com/joinquant/jqfactor_analyzer/blob/master/docs/API文档.md Generates a tear sheet for factor returns. Set `demeaned=True` to use excess returns and `group_adjust=True` for industry-neutralized returns. `by_group=True` plots average returns by industry. ```python far.create_returns_tear_sheet(demeaned=False, group_adjust=False, by_group=False) ``` -------------------------------- ### Create Information Tear Sheet Source: https://github.com/joinquant/jqfactor_analyzer/blob/master/docs/API文档.md Generates a tear sheet for information coefficients (IC). Use `group_adjust=True` for industry-neutralized returns and `by_group=True` to plot industry-grouped IC. ```python far.create_information_tear_sheet(group_adjust=False, by_group=False) ```