### Install AlphaInspect Source: https://github.com/wukan1986/alphainspect/blob/main/README.md Install AlphaInspect using pip. Use the official PyPI source or a domestic mirror. ```commandline pip install -i https://pypi.org/simple --upgrade alphainspect # 官方源 ``` ```commandline pip install -i https://pypi.tuna.tsinghua.edu.cn/simple --upgrade alphainspect # 国内镜像源 ``` -------------------------------- ### Clone AlphaInspect Repository Source: https://github.com/wukan1986/alphainspect/blob/main/README.md Clone the AlphaInspect repository from GitHub and install it in editable mode. ```commandline git --clone https://github.com/wukan1986/alphainspect.git cd alphainspect pip install -e . ``` -------------------------------- ### Data Preparation Workflow Source: https://context7.com/wukan1986/alphainspect/llms.txt Prepares raw OHLC data into the required AlphaInspect format, including forward returns and factor calculations. ```python import numpy as np import pandas as pd import polars as pl # 生成模拟数据 _N = 250 * 10 # 10年日数据 _K = 500 # 500只股票 asset = [f's_{i:04d}' for i in range(_K)] date = pd.date_range('2018-1-1', periods=_N) np.random.seed(42) # 创建OHLC数据 df = pd.DataFrame({ 'OPEN': np.cumprod(1 + np.random.uniform(-0.01, 0.01, size=(_N, _K)), axis=0).reshape(-1), 'HIGH': np.cumprod(1 + np.random.uniform(-0.01, 0.01, size=(_N, _K)), axis=0).reshape(-1), 'LOW': np.cumprod(1 + np.random.uniform(-0.01, 0.01, size=(_N, _K)), axis=0).reshape(-1), 'CLOSE': np.cumprod(1 + np.random.uniform(-0.01, 0.01, size=(_N, _K)), axis=0).reshape(-1), }, index=pd.MultiIndex.from_product([date, asset], names=['date', 'asset'])).reset_index() df = pl.from_pandas(df) # 计算远期收益率(需要shift到当前位置) # RETURN_OO_01: T+1开盘买入,T+2开盘卖出 # RETURN_CC_01: T+0收盘买入,T+1收盘卖出 df = df.with_columns([ (pl.col('OPEN').shift(-2) / pl.col('OPEN').shift(-1) - 1).over('asset').alias('RETURN_OO_01'), (pl.col('CLOSE').shift(-1) / pl.col('CLOSE') - 1).over('asset').alias('RETURN_CC_01'), ]) # 计算因子 df = df.with_columns([ pl.col('CLOSE').rolling_mean(10).over('asset').alias('SMA_010'), pl.col('CLOSE').rolling_std(10).over('asset').alias('STD_010'), ]) # 保存数据 df.write_parquet('data/data.parquet') ``` -------------------------------- ### Create Portfolio Sheet with Asset-Specific Returns Source: https://github.com/wukan1986/alphainspect/blob/main/deprecated/deprecated.txt Generates plots for individual asset cumulative returns and an overall portfolio equal-weighted return. Assumes weights are provided externally and capital is isolated per asset. ```python def create_portfolio2_sheet(df: pl.DataFrame, fwd_ret_1: str, *, axvlines=()) -> None: """分资产收益。权重由外部指定,资金是隔离""" # 各资产收益,如果资产数量过多,图会比较卡顿 df_cum_ret = calc_cum_return_weights(df, fwd_ret_1, 1) fig, axes = plt.subplots(2, 1, figsize=(12, 9), squeeze=False) axes = axes.flatten() # 分资产收益 plot_quantile_portfolio(df_cum_ret, fwd_ret_1, axvlines=axvlines, ax=axes[0]) # 资产平均收益,相当于等权 s = df_cum_ret.mean(axis=1) s.name = 'portfolio' plot_quantile_portfolio(s, fwd_ret_1, axvlines=axvlines, ax=axes[1]) fig.tight_layout() ``` -------------------------------- ### LightGBM Model Visualization Source: https://context7.com/wukan1986/alphainspect/llms.txt Visualizes feature importance and training metrics for LightGBM models, and exports decision trees to HTML. ```python import matplotlib.pyplot as plt from alphainspect.dtree import plot_importance_box, plot_metric_errorbar, tree_to_html # 假设已训练好多个LightGBM模型 # models = [model1, model2, model3, ...] fig, axes = plt.subplots(1, 2, figsize=(14, 6)) # 多模型特征重要性箱线图 plot_importance_box( models, plot_top_k=20, # 显示前20个特征 importance_type='gain', # 或 'split' ax=axes[0] ) # 训练过程评估指标图 plot_metric_errorbar( models, metric='auc', # 评估指标名 ax=axes[1] ) plt.tight_layout() plt.show() # 将决策树导出为HTML html_content = tree_to_html( models[-1], tree_index=0, show_info=['split_gain', 'leaf_count', 'data_percentage'], precision=3, orientation='horizontal' ) with open('tree.html', 'w', encoding='utf-8') as f: f.write(html_content) ``` -------------------------------- ### Generate Portfolio Performance Sheet Source: https://context7.com/wukan1986/alphainspect/llms.txt Creates a visualization of layered cumulative returns, including net value curves and monthly return heatmaps. ```python import polars as pl import matplotlib.pyplot as plt from alphainspect.portfolio import create_portfolio_sheet from alphainspect.utils import with_factor_quantile from alphainspect import _DATE_ df = pl.read_parquet('data/data.parquet') df = with_factor_quantile(df, 'SMA_010', quantiles=9, by=[_DATE_], factor_quantile='_fq_1') # 生成分层绩效图表 create_portfolio_sheet( df, fwd_ret_1='RETURN_OO_05', factor_quantile='_fq_1', axvlines=('2020-01-01', '2024-01-01') ) # 生成的图表: # - 上半部分:分层净值曲线(含多空对冲) # - 下半部分:最低层和最高层的月度收益热力图 plt.show() ``` -------------------------------- ### Multi-Factor IC Comparison Source: https://context7.com/wukan1986/alphainspect/llms.txt Analyze multiple factors across different holding periods using correlation matrices and heatmaps. ```python import polars as pl import matplotlib.pyplot as plt from alphainspect.ic import create_ic2_sheet df = pl.read_parquet('data/data.parquet') # 多因子多收益率IC分析 df_ic = create_ic2_sheet( df, factors=['SMA_005', 'SMA_010', 'SMA_020'], forward_returns=['RETURN_OO_01', 'RETURN_OO_05', 'RETURN_OO_10'], axvlines=('2020-01-01',) ) plt.show() ``` -------------------------------- ### Daily Simple Returns Calculation Source: https://github.com/wukan1986/alphainspect/blob/main/README.md Formulas for calculating daily simple returns for long and short positions, adjusted for different trading strategies. ```python FWD_RET_LONG = (卖出平仓价 / 买入开仓价) ** (1 / D) - 1 FWD_RET_SHORT = (2 - 买入平仓价 / 卖出开仓价) ** (1 / D) - 1 ``` ```python FWD_RET = (OPEN[-1] / CLOSE) ** (1 / 1) - 1 # 收盘前买入,第二天开盘卖出 ``` ```python FWD_RET = (OPEN[-1] / HIGH[1]) ** (1 / 1) - 1 # 突破昨高买入,第二天开盘卖出 ``` ```python FWD_RET = (OPEN[-1] / max_(OPEN, CLOSE)[1]) ** (1 / 1) - 1 # 突破昨实体上沿买入,第二天开盘卖出 ``` -------------------------------- ### Generate 2x2 Quick Analysis Report Source: https://context7.com/wukan1986/alphainspect/llms.txt Produces a concise 2x2 grid of charts including IC time series, IC heatmaps, factor histograms, and cumulative returns. ```python import polars as pl import matplotlib.pyplot as plt from alphainspect.reports import create_2x2_sheet from alphainspect.utils import with_factor_quantile from alphainspect import _DATE_ df = pl.read_parquet('data/data.parquet') df = with_factor_quantile(df, 'SMA_010', quantiles=9, by=[_DATE_], factor_quantile='_fq_1') # 生成2x2分析图表 fig, ic_dict, hist_dict, cum, avg, std = create_2x2_sheet( df, factor='SMA_010', fwd_ret_1='RETURN_OO_05', factor_quantile='_fq_1', figsize=(12, 9), axvlines=('2020-01-01', '2024-01-01') ) # 返回值包含统计指标 print(f"IC统计: {ic_dict}") # {'mean': 0.0234, 'zscore': 1.23, 'ratio': 0.05, 't_stat': 3.45, 'p_value': 0.001} print(f"直方图统计: {hist_dict}") # {'std': 0.0156, 'skew': 0.12, 'kurt': 3.45, 'mean_': 0.0023} plt.show() ``` -------------------------------- ### Top-K Factor Stratification Source: https://context7.com/wukan1986/alphainspect/llms.txt Use with_factor_top_k for scenarios with limited cross-sectional stock counts, outputting three layers: short, hedge, and long. ```python import polars as pl from alphainspect.utils import with_factor_top_k from alphainspect import _DATE_ df = pl.read_parquet('data/data.parquet') # 使用Top-K分层,选取因子值最高和最低的各20只股票 df = with_factor_top_k( df, factor='SMA_010', top_k=20, # 前20和后20 by=[_DATE_], factor_quantile='_fq_topk' ) # 结果:0=做空组, 1=对冲组, 2=做多组 print(df.group_by('_fq_topk').count()) ``` -------------------------------- ### Calculate cumulative returns Source: https://github.com/wukan1986/alphainspect/blob/main/deprecated/utils.txt Estimates portfolio performance by splitting capital into sub-portfolios. Requires returns and weights as numpy arrays. ```python def cumulative_returns(returns: np.ndarray, weights: np.ndarray, funds: int = 3, freq: int = 3, benchmark: np.ndarray = None, ret_mean: bool = True, init_cash: float = 1.0, risk_free: float = 1.0, # 1.0 + 0.025 / 250 ) -> np.ndarray: """累积收益 精确计算收益是非常麻烦的事情,比如考虑手续费、滑点、涨跌停无法入场。考虑过多也会导致计算量巨大。 这里只做估算,用于不同因子之间收益比较基本够用。更精确的计算请使用专用的回测引擎 需求:因子每天更新,但策略是持仓3天 1. 每3天取一次因子,并持有3天。即入场时间对净值影响很大。净值波动剧烈 2. 资金分成3份,每天入场一份。每份隔3天做一次调仓,多份资金不共享。净值波动平滑 本函数使用的第2种方法,例如:某支股票持仓信息如下 [0,1,1,1,0,0] 资金分成三份,每次持有三天, [0,0,0,1,1,1] # 第0、3、6...位,fill后两格 [0,1,1,1,0,0] # 第1、4、7...位,fill后两格 [0,0,1,1,1,0] # 第2、5、8...位,fill后两格 Parameters ---------- returns: np.ndarray 1期简单收益率。自动记在出场位置。 weights: np.ndarray 持仓权重。需要将信号移动到出场日期。权重绝对值和 funds: int 资金拆成多少份 freq:int 再调仓频率 benchmark: 1d np.ndarray 基准收益率 ret_mean: bool 返回多份资金合成曲线 init_cash: float 初始资金 risk_free: float 无风险收益率。用在现金列。空仓时,可以给现金提供利息 Returns ------- np.ndarray References ---------- https://github.com/quantopian/alphalens/issues/187 """ # 一维修改成二维,代码统一 if returns.ndim == 1: returns = returns.reshape(-1, 1) if weights.ndim == 1: weights = weights.reshape(-1, 1) # 形状 m, n = weights.shape # 现金权重 weights_cash = 1 - np.round(np.nansum(np.abs(weights), axis=1), 5) # TODO 也可以添加两列现金,一列有利息,一列没利息。细节要按策略进行定制 returns = np.concatenate((np.ones(shape=(m, 1), dtype=returns.dtype), returns), axis=1) weights = np.concatenate((np.zeros(shape=(m, 1), dtype=weights.dtype), weights), axis=1) # 添加第0列做为现金,用于处理CTA空仓的问题 weights[:, 0] = weights_cash # 可以考虑给现金指定一个固定收益 returns[:, 0] = risk_free # 修正数据中出现的nan returns = np.where(returns == returns, returns, 1.0) # 权重需要已经分配好,绝对值和为1 weights = np.where(weights == weights, weights, 0.0) # 新形状 m, n = weights.shape # 记录每份资金每期收益率 out = _sub_portfolio_returns(m, n, weights, returns, funds, freq, init_cash) if ret_mean: if benchmark is None: # 多份净值直接叠加后平均 return out.mean(axis=1) else: # 有基准,计算超额收益 return out.mean(axis=1) - (benchmark + 1).cumprod() else: return out ``` -------------------------------- ### Single Factor IC Visualization Source: https://context7.com/wukan1986/alphainspect/llms.txt Generate a comprehensive sheet of IC analysis charts for a single factor, including time-series, histograms, and heatmaps. ```python import polars as pl import matplotlib.pyplot as plt from alphainspect.ic import create_ic1_sheet df = pl.read_parquet('data/data.parquet') # 生成单因子多收益率的IC图表 df_ic = create_ic1_sheet( df, factor='SMA_010', forward_returns=['RETURN_OO_01', 'RETURN_OO_05', 'RETURN_OO_10'], axvlines=('2020-01-01', '2024-01-01'), # 垂直参考线 method='rank_ic' ) plt.show() ``` -------------------------------- ### Stratified Cumulative Return Calculation Source: https://context7.com/wukan1986/alphainspect/llms.txt Calculate cumulative returns for each factor quantile to assess monotonicity and profitability. ```python import polars as pl from alphainspect.portfolio import calc_cum_return_by_quantile from alphainspect.utils import with_factor_quantile from alphainspect import _DATE_ df = pl.read_parquet('data/data.parquet') df = with_factor_quantile(df, 'SMA_010', quantiles=5, by=[_DATE_], factor_quantile='_fq') # 计算分层累计收益 ret, cum, avg, std = calc_cum_return_by_quantile( df, fwd_ret_1='RETURN_OO_01', # 1期远期收益率 factor_quantile='_fq' ) print(cum.tail()) ``` -------------------------------- ### Factor Quantile Stratification Source: https://context7.com/wukan1986/alphainspect/llms.txt Use with_factor_quantile to divide factor values into groups based on quantiles, which is a foundational step for single-factor analysis. ```python import polars as pl from alphainspect.utils import with_factor_quantile from alphainspect import _DATE_ # 加载数据 df = pl.read_parquet('data/data.parquet') # 对因子进行9分位分层,按日期分组 df = with_factor_quantile( df, factor='SMA_010', # 要分层的因子名 quantiles=9, # 分成9层 by=[_DATE_], # 按日期分组 factor_quantile='_fq_1' # 输出的分层列名 ) # 查看分层结果 print(df.select(['date', 'asset', 'SMA_010', '_fq_1']).head(10)) ``` -------------------------------- ### Generate 3x2 Comprehensive Analysis Report Source: https://context7.com/wukan1986/alphainspect/llms.txt Produces a detailed 3x2 grid of charts, extending the 2x2 report with IC histograms and turnover analysis. ```python import polars as pl import matplotlib.pyplot as plt from alphainspect.reports import create_3x2_sheet from alphainspect.utils import with_factor_quantile from alphainspect import _DATE_ df = pl.read_parquet('data/data.parquet') df = with_factor_quantile(df, 'SMA_010', quantiles=9, by=[_DATE_], factor_quantile='_fq_1') # 生成3x2完整分析图表 fig, ic_dict, hist_dict, cum, avg, std = create_3x2_sheet( df, factor='SMA_010', fwd_ret_1='RETURN_OO_05', factor_quantile='_fq_1', periods=[1, 5, 10, 20], # 换手率周期 figsize=(12, 14), axvlines=('2020-01-01', '2024-01-01') ) # 图表布局: # [0,0] IC时序图 [0,1] IC直方图 # [1,0] IC月度热力图 [1,1] 分层累计收益 # [2,0] 因子自相关 [2,1] 换手率图 plt.show() ``` -------------------------------- ### Batch HTML Report Generation Source: https://context7.com/wukan1986/alphainspect/llms.txt Generates multiple HTML reports for different factor groups using multiprocessing to improve efficiency. ```python import polars as pl from multiprocessing import get_context from alphainspect.reports import report_html INPUT_PATH = 'data/data.parquet' OUTPUT_PATH = 'output' def generate_report(kv): name, factors = kv df = pl.read_parquet(INPUT_PATH) report_html( name=name, # 报表名称 factors=factors, # 因子列表 df=df, output=OUTPUT_PATH, fwd_ret_1='RETURN_OO_05', # 用于计算收益的远期收益率 quantiles=9, # 分层数 top_k=0, # 若>0则使用top_k分层 axvlines=('2020-01-01', '2024-01-01') ) return 0 if __name__ == '__main__': # 定义因子分组 factors_kv = { "SMA": ['SMA_005', 'SMA_010', 'SMA_020'], "STD": ['STD_005', 'STD_010', 'STD_020'], } # 多进程并行生成 with get_context("spawn").Pool(2) as pool: results = list(pool.map(generate_report, factors_kv.items())) # 输出:output/SMA.html, output/STD.html ``` -------------------------------- ### Calculate Cumulative Returns by Quantile Source: https://github.com/wukan1986/alphainspect/blob/main/deprecated/deprecated.txt Calculates cumulative returns for each quantile group, assuming equal weighting within each group. Useful for analyzing performance across different factor-based tiers. ```python def _calc_cum_return_by_quantile(df: pl.DataFrame, fwd_ret_1: str, period: int = 5, factor_quantile: str = _QUANTILE_) -> pd.DataFrame: """分层计算收益。分成N层,层内等权""" q_max = df.select(pl.max(factor_quantile)).to_series(0)[0] rr = df.pivot(index=_DATE_, columns=_ASSET_, values=fwd_ret_1, aggregate_function='first', sort_columns=True).sort(_DATE_) qq = df.pivot(index=_DATE_, columns=_ASSET_, values=factor_quantile, aggregate_function='first', sort_columns=True).sort(_DATE_) out = pd.DataFrame(index=rr[_DATE_]) rr = rr.select(pl.exclude(_DATE_)).to_numpy() + 1 # 日收益 qq = qq.select(pl.exclude(_DATE_)).to_numpy() # 分组编号 # logger.info('累计收益准备数据,period={}', period) np.seterr(divide='ignore', invalid='ignore') for i in range(int(q_max) + 1): # 等权 b = qq == i w = b / b.sum(axis=1).reshape(-1, 1) w[(w == 0).all(axis=1), :] = np.nan # 权重绝对值和为1 out[f'G{i}'] = cumulative_returns(rr, w, funds=period, freq=period) # !!!直接减是错误的,因为两资金是独立的,资金减少的一份由于资金不足对冲比例已经不再是1:1 # out['spread'] = out[f'G{q_max}'] - out[f'G0'] logger.info('累计收益计算完成,period={}\n{}', period, out.tail(1).to_string()) return out ``` -------------------------------- ### Calculate Cumulative Return Spread (Long-Short) Source: https://github.com/wukan1986/alphainspect/blob/main/deprecated/deprecated.txt Calculates the spread between the top and bottom quantiles, representing a long-short portfolio return. It handles weight adjustments for a balanced long-short strategy. ```python def calc_cum_return_spread(df: pl.DataFrame, fwd_ret_1: str, period: int = 5, factor_quantile: str = _QUANTILE_) -> pd.DataFrame: """分层计算收益。分成N层,层内等权。 取Top层和Bottom层。比较不同的计算方法多空收益的区别""" q_max = df.select(pl.max(factor_quantile)).to_series(0)[0] rr = df.pivot(index=_DATE_, columns=_ASSET_, values=fwd_ret_1, aggregate_function='first', sort_columns=True).sort(_DATE_).fill_nan(0) qq = df.pivot(index=_DATE_, columns=_ASSET_, values=factor_quantile, aggregate_function='first', sort_columns=True).sort(_DATE_).fill_nan(-1) out = pd.DataFrame(index=rr[_DATE_]) rr = rr.select(pl.exclude(_DATE_)).to_numpy() + 1 # 日收益 qq = qq.select(pl.exclude(_DATE_)).to_numpy() # 分组编号 logger.info('多空收益准备数据,period={}', period) np.seterr(divide='ignore', invalid='ignore') # 等权 w0 = qq == 0 w9 = qq == q_max w0 = w0 / w0.sum(axis=1).reshape(-1, 1) w0 = np.where(w0 == w0, w0, 0) w9 = w9 / w9.sum(axis=1).reshape(-1, 1) w9 = np.where(w9 == w9, w9, 0) ww = (w9 - w0) / 2 # 除2,权重绝对值和一定要调整为1,否则后面会计算错误 # 整行都为0,将其设成nan,后面计算时用于判断是否为0 ww[(ww == 0).all(axis=1), :] = np.nan w0[(w0 == 0).all(axis=1), :] = np.nan w9[(w9 == 0).all(axis=1), :] = np.nan # 曲线的翻转 out['1-G0,w=+1'] = 1 - cumulative_returns(rr, w0, funds=period, freq=period) # 权重的翻转。资金发生了变化。如果资金不共享,无法完全对冲 out['G0-1,w=-1'] = cumulative_returns(rr, -w0, funds=period, freq=period) - 1 out[f'G{q_max},w=+1'] = cumulative_returns(rr, w9, funds=period, freq=period) # 资金是共享的,每次调仓时需要将资金平分成两份 out[f'G{q_max}~G0,w=+.5/-.5'] = cumulative_returns(rr, ww, funds=period, freq=period, init_cash=1.0) logger.info('多空收益计算完成,period={}\n{}', period, out.tail(1).to_string()) return out ``` -------------------------------- ### Calculate Cumulative Returns with Specified Weights Source: https://github.com/wukan1986/alphainspect/blob/main/deprecated/deprecated.txt Calculates cumulative returns for assets based on externally provided weights. This function assumes separate capital for each asset and is suitable for daily rebalancing. ```python def calc_cum_return_weights(df: pl.DataFrame, fwd_ret_1: str, period: int = 1) -> pd.DataFrame: """指定权重计算收益。不再分层计算。资金也不分份""" rr = df.pivot(index=_DATE_, columns=_ASSET_, values=fwd_ret_1, aggregate_function='first', sort_columns=True).sort(_DATE_) ww = df.pivot(index=_DATE_, columns=_ASSET_, values=_WEIGHT_, aggregate_function='first', sort_columns=True).sort(_DATE_) out = pd.DataFrame(index=rr[_DATE_], columns=rr.columns[1:]) rr = rr.select(pl.exclude(_DATE_)).to_numpy() # 日收益 ww = ww.select(pl.exclude(_DATE_)).to_numpy() # 权重 logger.info('权重收益准备数据,period={}', period) np.seterr(divide='ignore', invalid='ignore') rr = np.where(rr == rr, rr, 0.0) # 累计收益分资产,资金不共享 # 由于是每天换仓,所以不存在空头计算不准的问题 out[:] = np.cumprod(rr * ww + 1, axis=0) logger.info('权重收益计算完成,period={}\n{}', period, out.tail(1).to_string()) return out ``` -------------------------------- ### IC Calculation and Metrics Source: https://context7.com/wukan1986/alphainspect/llms.txt Calculate Information Coefficient (IC) matrices and derived metrics like IR to evaluate factor predictive power. ```python import polars as pl from alphainspect.ic import calc_ic, rank_ic, mutual_info df = pl.read_parquet('data/data.parquet') # 定义因子和收益率 factors = ['SMA_005', 'SMA_010', 'SMA_020'] forward_returns = ['RETURN_OO_01', 'RETURN_OO_05'] # 计算RankIC矩阵 df_ic = calc_ic( df, factors=factors, forward_returns=forward_returns, method='rank_ic' # 或 'mutual_info' 计算互信息 ) print(df_ic.head()) # 计算IC均值和IR from alphainspect.calc import calc_mean, calc_ir ic_mean = calc_mean(df_ic) # IC均值 ic_ir = calc_ir(df_ic) # IR = IC均值 / IC标准差 print(f"IC均值: {ic_mean}") print(f"IR值: {ic_ir}") ``` -------------------------------- ### Numba Parallel Sub-Portfolio Returns Calculation Source: https://github.com/wukan1986/alphainspect/blob/main/deprecated/_nb.txt Calculates sub-portfolio returns with Numba's parallel processing. It simulates fund allocation, rebalancing based on frequency, and handles potential losses. ```python @jit(nopython=True, nogil=True, fastmath=True, cache=True, parallel=True) def _sub_portfolio_returns(m: int, n: int, weights: np.ndarray, returns: np.ndarray, funds: int = 1, freq: int = -1, init_cash: float = 1.0) -> np.ndarray: """资金分成N份。每隔N天取一次权重,这N天内每次都用上次的市值乘以权重得到新市值,乘以收益率得到日终市值 输出的数据全不为nan """ if freq == -1: freq = m # 记录每份的收益率 out = np.zeros(shape=(m, funds), dtype=float) # 资金分成funds份 for i in prange(funds): cashflow = np.zeros(shape=(m, n), dtype=float) # 多头为0,空头为2*weights val = np.zeros(shape=(m, n), dtype=float) val[:, 0] = init_cash # 初始资金全放第0列 last_sum = init_cash for j in range(i, m): # 调仓节点,如果设成m表示只第一天进行调仓 if (j % freq == i) and (last_sum > 0): val[j] = last_sum * weights[j] # 负数变正数*2,正数变成0 cashflow[j] = np.maximum(-val[j], 0) * 2 else: # 不调仓,直接取昨天的现金和市值做为盘前值 cashflow[j] = cashflow[j - 1] val[j] = val[j - 1] val[j] = returns[j] * val[j] last = val[j] + cashflow[j] # 在这里,很有可能做空亏成负数 last_sum = np.sum(last) if last_sum <= 0: # 亏损了,将市值移动到现金流中,不玩了 cashflow[j] += val[j] val[j] = 0 # 如果不水平求和,就能看到每支股票的累计收益 np_sum(val + cashflow, axis=1, out=out[:, i]) return out ``` -------------------------------- ### Analyze Factor Turnover and Autocorrelation Source: https://context7.com/wukan1986/alphainspect/llms.txt Calculates factor autocorrelation and quantile-based turnover to assess trading costs and factor stability. ```python import polars as pl import matplotlib.pyplot as plt from alphainspect.turnover import ( calc_auto_correlation, calc_quantile_turnover, create_turnover_sheet ) from alphainspect.utils import with_factor_quantile from alphainspect import _DATE_ df = pl.read_parquet('data/data.parquet') df = with_factor_quantile(df, 'SMA_010', quantiles=5, by=[_DATE_], factor_quantile='_fq') # 计算因子自相关(间隔1、5、10、20期) df_auto_corr = calc_auto_correlation( df, factor='SMA_010', periods=[1, 5, 10, 20] ) print(df_auto_corr.head()) # 输出: # ┌────────────┬────────┬────────┬────────┬────────┐ # │ date │ AC01 │ AC05 │ AC10 │ AC20 │ # ├────────────┼────────┼────────┼────────┼────────┤ # │ 2018-01-05 │ 0.9523 │ 0.8756 │ 0.7892 │ 0.6234 │ # └────────────┴────────┴────────┴────────┴────────┘ # 计算分层换手率 df_turnover = calc_quantile_turnover( df, factor_quantile='_fq', periods=[1, 5, 10, 20] ) # 生成完整换手率分析图表 create_turnover_sheet( df, factor='SMA_010', factor_quantile='_fq', periods=[1, 5, 10, 20], axvlines=('2020-01-01',) ) plt.show() ``` -------------------------------- ### Dual-Factor Grouping Analysis Source: https://context7.com/wukan1986/alphainspect/llms.txt Performs statistical analysis on two factors simultaneously to identify return characteristics across combined quantiles. ```python import polars as pl import matplotlib.pyplot as plt from alphainspect.plotting import create_describe2_sheet from alphainspect.utils import with_factor_quantile from alphainspect import _DATE_ df = pl.read_parquet('data/data.parquet') # 对两个因子分别分层 df = with_factor_quantile(df, 'SMA_010', quantiles=3, by=[_DATE_], factor_quantile='_fq_sma') df = with_factor_quantile(df, 'STD_010', quantiles=5, by=[_DATE_], factor_quantile='_fq_std') # 双因子分组分析 create_describe2_sheet( df, col='RETURN_OO_05', # 要统计的列(可以是收益率) factor_quantiles=['_fq_sma', '_fq_std'] # 两个因子分层列 ) # 生成3个热力图:Mean、Std、Count # 可用于分析3x5=15个组合的收益特征 plt.show() ``` -------------------------------- ### Numba Optimized NumPy Tile Function Source: https://github.com/wukan1986/alphainspect/blob/main/deprecated/_nb.txt Replicates a 2D NumPy array multiple times along the second axis using Numba. This is an optimized version of `np.tile` for specific 2D tiling scenarios. ```python @jit(nopython=True, nogil=True, fastmath=True, cache=True) def np_tile(arr, reps): m, n = arr.shape out = np.empty(shape=(m, n * reps), dtype=arr.dtype) for i in range(reps): out[:, i * n:(i + 1) * n] = arr return out ``` -------------------------------- ### Perform Event Study Analysis Source: https://context7.com/wukan1986/alphainspect/llms.txt Analyzes factor performance around specific events, including price changes, layered returns, and win rates. ```python import polars as pl import matplotlib.pyplot as plt from alphainspect.events import with_around_price, create_events_sheet from alphainspect.utils import with_factor_quantile from alphainspect import _DATE_ df = pl.read_parquet('data/data.parquet') # 添加事件前后的标准化价格(前5后15期) df = with_around_price( df, price='CLOSE', periods_before=5, periods_after=15 ) # 因子分层 df = with_factor_quantile(df, 'STD_010', quantiles=3, by=[_DATE_], factor_quantile='_fq') # 事件分析:分析波动率大于0.005时的表现 create_events_sheet( df, condition=pl.col('STD_010') > 0.005, # 事件条件 fwd_ret_1='RETURN_OO_05', show_long_short=True, factor_quantile='_fq', axvlines=('2020-01-01', '2024-01-01') ) # 生成的6个子图: # - 事件前后平均累计收益曲线(按分层) # - 最高层误差条图 # - 事件胜率时序图 # - 分层累计收益曲线 # - 事件发生次数分布图 plt.show() ``` -------------------------------- ### Apply 1D Function Along Axis with Numba Source: https://github.com/wukan1986/alphainspect/blob/main/deprecated/_nb.txt Applies a 1D function along a specified axis of a 2D NumPy array using Numba for acceleration. Useful for vectorized operations on rows or columns. ```python import numpy as np from numba import jit, prange @jit(nopython=True, nogil=True, fastmath=True) def np_apply_along_axis_1d(func1d, axis, arr, out): if axis == 0: for i in range(len(out)): out[i] = func1d(arr[:, i]) else: for i in range(len(out)): out[i] = func1d(arr[i, :]) return out ``` -------------------------------- ### Apply 2D Function Along Axis with Numba Source: https://github.com/wukan1986/alphainspect/blob/main/deprecated/_nb.txt Applies a function along a specified axis of a 2D NumPy array using Numba. This is distinct from the 1D version and handles operations differently based on the axis. ```python @jit(nopython=True, nogil=True, fastmath=True) def np_apply_along_axis_2d(func1d, axis, arr, out): if axis == 0: for i in range(out.shape[1]): out[:, i] = func1d(arr[:, i]) else: for i in range(out.shape[0]): out[i, :] = func1d(arr[i, :]) return out ``` -------------------------------- ### Numba Optimized NumPy Cumulative Product Source: https://github.com/wukan1986/alphainspect/blob/main/deprecated/_nb.txt Calculates the cumulative product of a NumPy array along a specified axis using Numba. This function utilizes `np_apply_along_axis_2d` for its implementation. ```python @jit(nopython=True, nogil=True, fastmath=True, cache=True) def np_cumprod(arr, axis, out): return np_apply_along_axis_2d(np.cumprod, axis, arr, out) ``` -------------------------------- ### Numba Optimized NumPy Sum Calculation Source: https://github.com/wukan1986/alphainspect/blob/main/deprecated/_nb.txt Computes the sum of a NumPy array along a specified axis with Numba acceleration. Supports the `axis` parameter and uses `np_apply_along_axis_1d`. ```python @jit(nopython=True, nogil=True, fastmath=True, cache=True) def np_sum(arr, axis, out): # sum支持axis return np_apply_along_axis_1d(np.sum, axis, arr, out) ``` -------------------------------- ### High-Correlation Factor Filtering Source: https://context7.com/wukan1986/alphainspect/llms.txt Identifies and filters out highly correlated factors to prevent multicollinearity in multi-factor models. ```python import polars as pl from alphainspect.selection import drop_above_corr_thresh from alphainspect.ic import calc_ic df = pl.read_parquet('data/data.parquet') # 计算多因子IC factors = ['SMA_005', 'SMA_010', 'SMA_020', 'STD_005', 'STD_010'] df_ic = calc_ic(df, factors, ['RETURN_OO_05']) # 筛选高相关因子 cols_to_drop, above_thresh_pairs = drop_above_corr_thresh( df_ic.select(pl.exclude('date')), thresh=0.85 # 相关性阈值 ) print(f"需要删除的因子: {cols_to_drop}") # ['SMA_005__RETURN_OO_05'] print(f"高相关因子对: {above_thresh_pairs}") # [('SMA_005__RETURN_OO_05', 'SMA_010__RETURN_OO_05', 0.92)] ``` -------------------------------- ### Numba Optimized NumPy Mean Calculation Source: https://github.com/wukan1986/alphainspect/blob/main/deprecated/_nb.txt Calculates the mean of a NumPy array along a specified axis using Numba for performance. Leverages the `np_apply_along_axis_1d` function. ```python @jit(nopython=True, nogil=True, fastmath=True, cache=True) def np_mean(arr, axis, out): return np_apply_along_axis_1d(np.mean, axis, arr, out) ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.