def test_performance(factor, prices): import matplotlib.pyplot as plt from alphalens import utils, performance, plotting # 持股收益-逐只 stocks_holding_return = utils.get_clean_factor_and_forward_returns(factor, prices, quantiles=5, periods=(1, 5, 10)) print("因子的IC值:") ic = performance.factor_information_coefficient(stocks_holding_return) print(ic) plotting.plot_ic_hist(ic) plt.show() plotting.plot_ic_ts(ic) plt.show() print("平均IC值-月:") mean_ic = performance.mean_information_coefficient(stocks_holding_return, by_time="M") plotting.plot_monthly_ic_heatmap(mean_ic) plt.show() # 按quantile区分的持股平均收益(减去了总体平均值) mean_return_by_q = performance.mean_return_by_quantile(stocks_holding_return, by_date=True, demeaned=True)[0] # 按quantile画出累积持有收益 for i in [1, 5, 10]: plotting.plot_cumulative_returns_by_quantile(mean_return_by_q, period=i) plt.show()
def create_ic_tear_sheet(self): factor_and_return = self._get_clean_factor_and_fwd_return( self._factor, self._factor_freq) ic = factor_information_coefficient(factor_and_return) plot_ic_hist(ic) self.ic_bar_tear_sheet(ic) plot_monthly_ic_heatmap(ic) plt.show() return
# 3)计算加权合成的因子 new_factor = factor_admin.ic_cov_weighted_factor(factors_dict, ic_weight_df) # 4)查看合成的因子表现 perf = factor_admin.calculate_performance(new_factor.name, new_factor.multifactor_value, start, end, periods=(1, 5, 10), quantiles=5, price=prices) from alphalens import plotting import matplotlib.pyplot as plt plotting.plot_ic_hist(perf.ic) plt.show() plotting.plot_ic_ts(perf.ic) plt.show() plotting.plot_monthly_ic_heatmap(perf.mean_ic_by_M) plt.show() # 按quantile画出累积持有收益 for i in [1, 5, 10]: plotting.plot_cumulative_returns_by_quantile(perf.mean_return_by_q, period=i) plt.show() # 5) shrink_weight_df合成 holding_period = 10 ic_weight_shrink_df = factor_admin.get_ic_weight_shrink_df(
""" import pandas as pd import numpy as np import scipy.stats as st from alphalens import tears, performance, plotting, utils df = pd.DataFrame([[1, 2], [4, 5]], columns=["A", "B"]) # 计算斯皮尔相关系数Rank IC,取值 [-1, 1]之间 print(st.spearmanr(df["A"], df["B"])) """使用alphalens更简易的做因子分析""" # 输入因子表和收盘价表到返回到期收益率表,再将因子表和到期收益表整合返回综合因子数据表 factor_data = utils.get_clean_factor_and_forward_returns("factor", "price") # 因子IC的计算 IC = performance.factor_information_coefficient(factor_data) # 因子时间序列和移动平均图,看出一个因子在时间上的正负性、 plotting.plot_ic_ts(IC) # 因子分布直方图,IC平均值,标准差 plotting.plot_ic_hist(IC) # 热力图 mean_monthly_ic = performance.mean_information_coefficient(factor_data, by_time="1m") plotting.plot_monthly_ic_heatmap(mean_monthly_ic) # IC分析合集 tears.create_information_tear_sheet(factor_data) # 收益率分析 tears.create_returns_tear_sheet(factor_data) # 因子的每一期的收益(因子收益) performance.factor_returns(factor_data).iloc[:, 0].mean()