一. 去极值
因子数据中过大或过小的值会影响分析结果,特别是在回归时,离群值会严重影响因子和收益率之间的相关性估计结果。
因子去极值的处理方法:
- 确定上下限
- 将上下限外的数据修改为上下限值
常见的去极值方法有三种,分别是MAD法,3 σ \sigma σ法,百分位法
1. MAD法
处理步骤:
- 找出所有因子的中位数 F m e d i a n F_{median} Fmedian
- 得到每个因子与中位数的绝对偏差值 ∣ F i − F m e d i a n ∣ |F_i - F_{median}| ∣Fi−Fmedian∣
- 得到绝对偏差值的中位数 M A D MAD MAD
- 确定阈值参数 n n n,对超出范围 [ F m e d i a n − n ∗ M A D , F m e d i a n + n ∗ M A D ] [F_{median} - n * MAD, F_{median} + n * MAD] [Fmedian−n∗MAD,Fmedian+n∗MAD]的因子值做调整
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import baostock as bsdef get_hs300_stocks():lg = bs.login()# 获取沪深300成分股rs = bs.query_hs300_stocks()hs300_stocks = []while (rs.error_code == '0') & rs.next():hs300_stocks.append(rs.get_row_data())# 获取沪深300成分股数据result = pd.DataFrame()for element in hs300_stocks:print(element[1])rs = bs.query_history_k_data_plus(element[1], "code,peTTM, pbMRQ",start_date='2024-03-29', end_date='2024-03-29',frequency="d", adjustflag="3")#### 打印结果集 ####data_list = []while (rs.error_code == '0') & rs.next():data_list.append(rs.get_row_data())result = result.append(pd.DataFrame(data_list), ignore_index=True)result.columns = ['code','pe', 'pb']result['pe'] = result['pe'].astype('float64')result['pb'] = result['pb'].astype('float64')result.set_index('code', inplace=True)return result
# 获取沪深300所有成分股2024-02-29的市盈率和市净率
factor_data = get_hs300_stocks()
# MAD去极值
def extreme_mad(factor, n):median = factor.quantile(0.5)mad = (factor - median).abs().quantile(0.5)upper = median + mad * nlower = median - mad * nreturn factor.clip(lower = lower, upper = upper, axis = 1)
# 对比用MAD法去极值后与原始数据的数据分布
fig, ax = plt.subplots(figsize = (10, 8))
factor_data['pe'].plot(kind = 'kde',label='pe')
extreme_mad(factor_data, 5)['pe'].plot(kind = 'kde', label = 'pe_mad')
ax.legend()
2. 3 σ \sigma σ法
处理步骤:
- 计算出因子的平均值 m e a n mean mean与标准差 δ \delta δ
- 确定阈值参数 n n n(默认为3),对超出范围 [ m e a n − n δ , m e a n + n δ ] [mean - n\delta, mean + n\delta] [mean−nδ,mean+nδ]的因子值做调整
# 3 sigma法
def extreme_nsigma(factor, n):mean = factor.mean()std = factor.std()upper = mean + n * stdlower = mean - n * stdreturn factor.clip(lower = lower, upper = upper, axis = 1)
# 对比用3 sigma法去极值后与原始数据的数据分布
fig, ax = plt.subplots(figsize = (10, 8))
factor_data['pe'].plot(kind = 'kde',label='pe')
extreme_nsigma(factor_data, 3)['pe'].plot(kind = 'kde', label = '3sigma_pe')
ax.legend()
3. 百分位法
处理步骤:
- 找出因子值的上限分位数和下限分位数(一般为97.5%和2.5%)
- 对大于上限分位数和小于下限分位数的因子值进行调整
# 百分位数去极值
def extreme_percentage(factor, lower_pencentage, upper_percentage):lower = factor.quantile(lower_pencentage)upper = factor.quantile(upper_percentage)return factor.clip(upper = upper, lower = lower, axis = 1)
# 对比用百分位法去极值后与原始数据的数据分布
fig, ax = plt.subplots(figsize = (10, 8))
factor_data['pe'].plot(kind = 'kde',label='pe')
extreme_percentage(factor_data, 0.025, 0.975)['pe'].plot(kind = 'kde', label = 'percent_pe')
ax.legend()
二. 标准化
一般不同因子数据的量纲和数量级可能会存在较大的差别,比如市盈率和成交量这两个因子之间会差好几个数量级,这样会放大数值大的因子,削弱数值小的因子。因此需要对因子数据进行标准化处理。
经过标准化处理后,因子数据会出现如下变化
- 原始数据从有量纲数据转换为无量纲数据,
- 各指标数据处于同一数量级上,数据更加集中
- 不同的指标能够进行比较和回归,可以进行综合测评分析
1. Z-score法
处理步骤:
- 计算因子的均值和标准差
- 因子值减去均值后再除以标准差得到的值即是标准化后的因子值
def standlize_z(factor):mean, std = factor.mean(), factor.std()return (factor - mean) / std
fig, ax = plt.subplots(figsize = (10, 8))
extreme_mad(factor_data, 5)['pe'].plot(kind = 'kde',label='pe_mad')
standlize_z(extreme_mad(factor_data, 5))['pe'].plot(kind = 'kde', label = 'pe_standlize')
ax.legend()