<jupyter_start><jupyter_text>Alphamind新手入门之五：Alpha因子的五分位分析<jupyter_code>import os

# %matplotlib inline
import os
import pandas as pd
import numpy as np
from matplotlib import rc
from matplotlib import pyplot as plt
from PyFin.api import makeSchedule
from alphamind.api import *
from alphamind.analysis.quantileanalysis import er_quantile_analysis

rc('font', **{'family': 'Microsoft YaHei', 'size': 10})
rc('mathtext', **{'default': 'regular'})
rc('legend', **{'frameon': False})<jupyter_output><empty_output><jupyter_text>1. 数据准备------------------* 股票池：中证800* 因子：`ETOP`* 调仓频率：5个交易日* 起始日：2010年1月1日* 终止日：2019年1月31日* 分位数：5<jupyter_code>engine = SqlEngine(os.environ['DB_URI'])
universe = Universe('zz800')   # 股票池设置，此处设置为中证800，可选中证500（zz500）和沪深300（hs300）
factor = 'EMA5D'   #"ROE" 因子
freq = '5b' #调仓频率 5个工作日“5b”
start_date = '2020-01-01'  # 回测起始日
end_date = '2021-01-31'    # 回测终止日
n_bins = 5    # 分组数
# 因子中性化设置 
# industry_stryles为行业风格   risk_styles 为风险风格   
neutralized_styles = industry_styles # risk_styles + industry_styles  
# makeSchedule函数 用于设置调仓日的生成工作日序列
dates = makeSchedule(start_date, end_date, freq, 'china.sse') 
horizon = map_freq(freq) # 对于调仓频率的数值化过程
%%time

#获取数据
#fetch_factor_range 获取因子数据
#fetch_risk_model_range 获取风险模型数据
#fetch_dx_return_range 获取收益率数据

#%%time
factor_data = engine.fetch_factor_range(universe, factor, dates=dates)
risk_cov, risk_factors = engine.fetch_risk_model_range(universe, dates=dates)
return_data = engine.fetch_dx_return_range(universe, dates=dates, horizon=horizon)
total_data = pd.merge(factor_data, risk_factors, on=['trade_date', 'code'])
total_data = pd.merge(total_data, return_data, on=['trade_date', 'code']).dropna()<jupyter_output>CPU times: user 3.79 s, sys: 269 ms, total: 4.06 s
Wall time: 41.9 s<jupyter_text>2. 分位数群组收益比较-----------------------<jupyter_code>#neutralize 因子中性化函数

neutralized_factors = neutralize(total_data[neutralized_styles].values.astype(float),
                                 total_data[factor].values,
                                 groups=total_data['trade_date'].values)
total_data['neutralized_factors'] = neutralized_factors
%%time
# er_quantile_analysis 分位数分析函数

df = pd.DataFrame(columns=['q' + str(i) for i in range(1, n_bins+1)])

grouped = total_data.groupby('trade_date')
for k, g in grouped:
    er = g['neutralized_factors'].values
    dx_return = g['dx'].values
    res = er_quantile_analysis(er, n_bins=n_bins, dx_return=dx_return, de_trend=True)
    df.loc[k, :] = res
df.cumsum().plot(figsize=(14, 7))
ret_yearly = df.groupby(df.index.year).sum()
ret_yearly.plot(kind='bar', figsize=(14, 7))
(df.mean() * 50).plot(kind='bar', figsize=(14, 7), color='orange')<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.1488095238095238, 'fraction_numerical': 0.031994047619047616, 'mean_word_length': 5.4639423076923075, 'pattern_counts': {'":': 0, '<': 12, '<?xml version=': 0, '>': 12, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 2, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '3', 'dir': 'jupyter-structured-clean-dedup', 'id': '643930', 'license': 'MIT', 'n_tokens_mistral': 1188, 'n_tokens_neox': 1171, 'n_words': 187, 'path': 'notebooks/Quick Start 5 - Alpha Factor Quantile Analysis.ipynb', 'repo_name': 'rongliang-tech/alpha-mind', 'size': '2688'}