API

pyfolio API 按不同模块组织:

分析报告

Pyfolio 将关键投资组合指标整合为主题图表和摘要报表。

pyfolio.tears.create_capacity_tear_sheet(returns, positions, transactions, market_data, liquidation_daily_vol_limit=0.2, trade_daily_vol_limit=0.05, last_n_days=126, days_to_liquidate_limit=1, estimate_intraday='infer', return_fig=False)

生成一份详细报告,说明由流动性最差标的设定的投资组合规模限制。绘制一条"容量扫描"曲线,该曲线描述了在不同资金规模下应用滑点惩罚后的预期夏普比率。

Parameters
returnspd.Series
Daily returns of the strategy, noncumulative.
  • 完整说明请参阅create_full_tear_sheet。

positionspd.DataFrame
Daily net position values.
  • 完整说明请参见create_full_tear_sheet。

transactionspd.DataFrame
Prices and amounts of executed trades. One row per trade.
  • 完整说明请参阅create_full_tear_sheet。

market_datapd.DataFrame

每日市场数据 - DataFrame具有多级索引,一级是日期,另一级是 市场数据包含交易量和价格,股票作为列

liquidation_daily_vol_limitfloat

在“清算天数”分析中,每日交易量中可用于平仓的最大比例。

trade_daily_vol_limitfloat

标记每日交易总额超过日线比例的情况。

last_n_daysinteger

仅计算回测最后N天的最大头寸分配和美元交易量

days_to_liquidate_limitinteger

显示所有清算天数上限更高的股票代码。

estimate_intraday: boolean or str, optional

日内策略的近似收益。 详情请参阅create_full_tear_sheet中的描述。

return_figboolean, optional

如果为True,则返回已绘制的图表。

pyfolio.tears.create_full_tear_sheet(returns, positions=None, transactions=None, market_data=None, benchmark_rets=None, slippage=None, live_start_date=None, sector_mappings=None, round_trips=False, estimate_intraday='infer', hide_positions=False, cone_std=(1.0, 1.5, 2.0), bootstrap=False, unadjusted_returns=None, turnover_denom='AGB', set_context=True, factor_returns=None, factor_loadings=None, pos_in_dollars=True, header_rows=None, factor_partitions={'sector': ['basic_materials', 'consumer_cyclical', 'financial_services', 'real_estate', 'consumer_defensive', 'health_care', 'utilities', 'communication_services', 'energy', 'industrials', 'technology'], 'style': ['momentum', 'size', 'value', 'reversal_short_term', 'volatility']})

生成一系列用于分析策略性能的报表。

  • 如果需要的话,获取基准数据。

  • 为收益率和重大事件创建分析报告

    如果可能,还会创建持仓分析和交易分析报告

Parameters
returnspd.Series
Daily returns of the strategy, noncumulative.
  • 包含小数收益的时间序列。

  • 示例:

    2015-07-16 -0.012143 2015-07-17 0.045350 2015-07-20 0.030957 2015-07-21 0.004902

positionspd.DataFrame, optional
Daily net position values.
  • 每个持仓和现金的美元投资金额时间序列。

  • 股票未持有的天数可以用0或NaN表示。

  • 非营运资金被标记为‘现金’

  • 示例:

    指数 'AAPL' 'MSFT' 现金 2004-01-09 13939.3800 -14012.9930 711.5585 2004-01-12 14492.6300 -14624.8700 27.1821 2004-01-13 -13853.2800 13653.6400 -43.6375

transactionspd.DataFrame, optional

执行的交易量和成交价格。 - 每行代表一笔交易。 - 不同名称的交易发生在

同一时间将具有相同的索引。

  • 示例:

    索引 数量 价格 代码 2004-01-09 12:18:01 483 324.12 ‘AAPL’ 2004-01-09 12:18:01 122 83.10 ‘MSFT’ 2004-01-13 14:12:23 -75 340.43 ‘AAPL’

market_datapd.DataFrame, optional

每日市场数据 - DataFrame 具有多级索引,一级是日期,另一级是市场数据 市场数据包含交易量和价格,股票作为列

slippageint/float, optional

在生成统计报表和图表前,对收益率应用滑点的基点值。 如果提供了该参数,系统将基于未经调整的收益率生成滑点参数扫描图。 必须同时传入交易和持仓数据。 - 更多详情请参阅txn.adjust_returns_for_slippage。

live_start_datedatetime, optional

策略在回测期结束后开始实盘交易的时间点。该日期时间应进行标准化处理。

hide_positionsbool, optional

如果为True,将不会输出任何符号名称。

round_trips: boolean, optional

如果为True,将生成一份完整的往返交易分析报告。

sector_mappingsdict or pd.Series, optional

证券标识符到行业的映射。 以证券ID为键,行业为值的字典。

estimate_intraday: boolean or str, optional

不使用每日收盘时的持仓数据,而是采用当日投资金额最高的时点。这将调整持仓数据,以更准确地近似和反映日内交易策略的行为表现。默认情况下,该参数为'infer',系统会自动尝试检测是否为日内策略。若手动指定该参数值,则会跳过自动检测过程。

cone_stdfloat, or tuple, optional

如果是浮点数,表示用于锥形图的标准差。 如果是元组,表示用于锥形图的标准差值组成的元组

  • 该锥形表示围绕线性回归中心的标准差正态分布

    以线性回归为中心。

bootstrapboolean (optional)

是否对性能指标执行引导分析。这会多花费几分钟时间。

turnover_denomstr

可以是AGB或portfolio_value,默认为AGB。 - 完整说明请参见txn.get_turnover。

factor_returnspd.Dataframe, optional

按因子返回收益,日期作为索引,因子作为列

factor_loadingspd.Dataframe, optional

日期范围内所有交易日的因子载荷数据,以日期和股票代码为索引,因子为列。

pos_in_dollarsboolean, optional

表示头寸是否以美元计价

header_rowsdict or OrderedDict, optional

在性能统计表格顶部显示的额外行数。

set_contextboolean, optional
If True, set default plotting style context.
  • 参见 plotting.context()。

factor_partitionsdict, optional

指定在绩效归因中如何分离因子的字典 因子收益和风险暴露图表 - 参见create_perf_attrib_tear_sheet()。

pyfolio.tears.create_interesting_times_tear_sheet(returns, benchmark_rets=None, periods=None, legend_loc='best', return_fig=False)

围绕一些有趣的时间点(如闪电崩盘和9/11事件)生成多个收益图表。

图表展示:互联网泡沫破裂、雷曼兄弟倒闭、9/11事件、美国降级与欧盟债务危机、福岛核泄漏、美国房地产泡沫破裂、欧洲央行利率调整、大衰退(2007年8月、2008年3月和9月、2009年第一季度和第二季度)、闪崩事件、2014年4月和10月期间的收益率情况。

必须传入benchmark_rets参数,因为在没有参考基准的情况下分析特定时期的绩效是没有意义的。

Parameters
returnspd.Series
Daily returns of the strategy, noncumulative.
  • 完整说明请参见create_full_tear_sheet。

benchmark_retspd.Series
Daily noncumulative returns of the benchmark.
  • 这与收益的风格相同。

periods: dict or OrderedDict, optional

可能对市场产生重大影响的历史事件日期

legend_locplt.legend_loc, optional

图例的位置。

return_figboolean, optional

如果为True,则返回已绘制的图表。

pyfolio.tears.create_perf_attrib_tear_sheet(returns, positions, factor_returns, factor_loadings, transactions=None, pos_in_dollars=True, factor_partitions={'sector': ['basic_materials', 'consumer_cyclical', 'financial_services', 'real_estate', 'consumer_defensive', 'health_care', 'utilities', 'communication_services', 'energy', 'industrials', 'technology'], 'style': ['momentum', 'size', 'value', 'reversal_short_term', 'volatility']}, return_fig=False)

生成用于分析策略性能的图表和表格。

Parameters
returnspd.Series

返回日期范围内每一天的收益。

positions: pd.DataFrame

每日持仓(以美元或百分比表示),按日期索引。如果持仓以美元计价,将转换为百分比。空头头寸显示在"cash"列中作为现金。

factor_returnspd.DataFrame

按因子返回收益,日期作为索引,因子作为列

factor_loadingspd.DataFrame

日期范围内所有交易日的因子载荷,以日期和股票代码为索引,因子为列。

transactionspd.DataFrame, optional
Prices and amounts of executed trades. One row per trade.
  • 完整说明请参见create_full_tear_sheet。

  • 默认为 None。

pos_in_dollarsboolean, optional

标志位,指示positions是以美元还是百分比为单位 如果为True,则表示positions以美元为单位。

factor_partitionsdict

指定因子在因子收益和风险暴露图中应如何分离的字典 - 示例:

{‘style’: [‘momentum’, ‘size’, ‘value’, …],

‘sector’: [‘technology’, ‘materials’, … ]}

return_figboolean, optional

如果为True,则返回已绘制的图表。

pyfolio.tears.create_position_tear_sheet(returns, positions, show_and_plot_top_pos=2, hide_positions=False, sector_mappings=None, transactions=None, estimate_intraday='infer', return_fig=False)

生成一系列图表用于分析策略的持仓和头寸情况。

  • 图表:总杠杆率、风险敞口、主要持仓和持有情况。

  • 同时会显示持仓最多的头寸。

Parameters
returnspd.Series
Daily returns of the strategy, noncumulative.
  • 完整说明请参阅create_full_tear_sheet。

positionspd.DataFrame
Daily net position values.
  • 完整说明请参阅create_full_tear_sheet。

show_and_plot_top_posint, optional

默认情况下,该值为2,会同时打印并绘制前10大持仓。 如果设为0,则仅绘制图表;如果设为1,则仅打印数据。

hide_positionsbool, optional

如果为True,将不输出任何符号名称。 覆盖show_and_plot_top_pos为0以禁止文本输出。

sector_mappingsdict or pd.Series, optional

证券标识符到行业的映射。 以证券ID为键,行业为值的字典。

transactionspd.DataFrame, optional
Prices and amounts of executed trades. One row per trade.
  • 完整说明请参阅create_full_tear_sheet。

estimate_intraday: boolean or str, optional

日内策略的近似收益。 详情请参阅create_full_tear_sheet中的描述。

return_figboolean, optional

如果为True,则返回已绘制的图表。

pyfolio.tears.create_returns_tear_sheet(returns, positions=None, transactions=None, live_start_date=None, cone_std=(1.0, 1.5, 2.0), benchmark_rets=None, bootstrap=False, turnover_denom='AGB', header_rows=None, return_fig=False)

生成一系列图表用于分析策略的收益表现。

  • 获取基准数据,然后在单个图表上创建绘图。

  • 图表:滚动收益率(带置信区间)、滚动贝塔值、滚动夏普比率、

    滚动法玛-弗伦奇风险因子、回撤分析、水下走势图、月度 和年度收益率图表、日相似性图表、 以及收益率分位数箱线图。

  • 同时会显示策略的起始和结束日期,

    绩效统计数据、回撤周期以及收益范围。

Parameters
returnspd.Series
Daily returns of the strategy, noncumulative.
  • 完整说明请参阅create_full_tear_sheet。

positionspd.DataFrame, optional
Daily net position values.
  • 完整说明请参阅create_full_tear_sheet。

transactionspd.DataFrame, optional

执行的交易量和成交价格。 - 完整说明请参阅create_full_tear_sheet。

live_start_datedatetime, optional

策略在回测期结束后,开始实盘交易的时间点。

cone_stdfloat, or tuple, optional

如果是浮点数,表示用于锥形图的标准差。 如果是元组,表示用于锥形图的标准差值组成的元组

  • 该锥形表示围绕线性回归中心的正态分布,其标准差为

    以线性回归为中心。

benchmark_retspd.Series, optional
Daily noncumulative returns of the benchmark.
  • 这与收益的风格相同。

bootstrapboolean, optional

是否对性能指标执行引导分析。这会多花费几分钟时间。

turnover_denomstr, optional

可以是AGB或portfolio_value,默认为AGB。 - 完整说明请参见txn.get_turnover。

header_rowsdict or OrderedDict, optional

在性能统计表格顶部显示的额外行数。

return_figboolean, optional

如果为True,则返回已绘制的图表。

pyfolio.tears.create_round_trip_tear_sheet(returns, positions, transactions, sector_mappings=None, estimate_intraday='infer', return_fig=False)

生成一系列图表,用于描述交易"往返"的持续时间、频率和盈利能力。 一次往返交易始于新开多头或空头头寸,只有当该头寸的股票数量回归或跨越零时才完成。

Parameters
returnspd.Series
Daily returns of the strategy, noncumulative.
  • 完整说明请参阅create_full_tear_sheet。

positionspd.DataFrame
Daily net position values.
  • 完整说明请参阅create_full_tear_sheet。

transactionspd.DataFrame
Prices and amounts of executed trades. One row per trade.
  • 完整说明请参阅create_full_tear_sheet。

sector_mappingsdict or pd.Series, optional

证券标识符到行业的映射。 以证券ID为键,行业为值的字典。

estimate_intraday: boolean or str, optional

日内策略的近似收益。 详情请参阅create_full_tear_sheet中的描述。

return_figboolean, optional

如果为True,则返回已绘制的图表。

pyfolio.tears.create_simple_tear_sheet(returns, positions=None, transactions=None, benchmark_rets=None, slippage=None, estimate_intraday='infer', live_start_date=None, turnover_denom='AGB', header_rows=None)

简化版的create_full_tear_sheet;生成汇总性能统计数据和重要图表作为单张图像。

  • 图表:累计收益、滚动贝塔值、滚动夏普比率、水下回撤、

    风险暴露、前十大持仓、总持仓、多头/空头持仓、 每日换手率、交易时间分布。

  • 从不接受市场数据输入 (market_data = None)

  • 从不接受sector_mappings输入(sector_mappings = None)

  • 永不执行自助法分析 (bootstrap = False)

  • 在前十大持仓图表中永不隐藏持仓位置 (hide_positions = False)

  • 始终使用默认的cone_std (cone_std = (1.0, 1.5, 2.0))

Parameters
returnspd.Series
Daily returns of the strategy, noncumulative.
  • 包含小数收益的时间序列。

  • 示例:

    2015-07-16 -0.012143 2015-07-17 0.045350 2015-07-20 0.030957 2015-07-21 0.004902

positionspd.DataFrame, optional
Daily net position values.
  • 每个持仓和现金的美元投资金额时间序列。

  • 股票未持有的天数可以用0或NaN表示。

  • 非营运资金被标记为‘现金’

  • 示例:

    指数 'AAPL' 'MSFT' 现金 2004-01-09 13939.3800 -14012.9930 711.5585 2004-01-12 14492.6300 -14624.8700 27.1821 2004-01-13 -13853.2800 13653.6400 -43.6375

transactionspd.DataFrame, optional

执行的交易量和成交价格。 - 每行代表一笔交易。 - 不同名称的交易发生在

同一时间将具有相同的索引。

  • 示例:

    索引 数量 价格 符号 2004-01-09 12:18:01 483 324.12 ‘AAPL’ 2004-01-09 12:18:01 122 83.10 ‘MSFT’ 2004-01-13 14:12:23 -75 340.43 ‘AAPL’

benchmark_retspd.Series, optional

基准的每日回报,非累计。

slippageint/float, optional

在生成统计报表和图表前,对收益率应用滑点的基点值。 如果提供了该参数,系统将基于未经调整的收益率生成滑点参数扫描图。 必须同时传入交易和持仓数据。 - 更多详情请参阅txn.adjust_returns_for_slippage。

live_start_datedatetime, optional

策略在回测期结束后开始实盘交易的时间点。该日期时间应进行标准化处理。

turnover_denomstr, optional

可以是AGB或portfolio_value,默认为AGB。 - 完整说明请参见txn.get_turnover。

header_rowsdict or OrderedDict, optional

在性能统计表格顶部显示的额外行数。

set_contextboolean, optional

如果为True,则设置默认的绘图样式上下文。

pyfolio.tears.create_txn_tear_sheet(returns, positions, transactions, turnover_denom='AGB', unadjusted_returns=None, estimate_intraday='infer', return_fig=False)

生成多个图表用于分析策略的交易情况。

图表:换手率、日成交量以及日成交量的直方图。

Parameters
returnspd.Series
Daily returns of the strategy, noncumulative.
  • 完整说明请参见create_full_tear_sheet。

positionspd.DataFrame
Daily net position values.
  • 完整说明请参见create_full_tear_sheet。

transactionspd.DataFrame
Prices and amounts of executed trades. One row per trade.
  • 完整说明请参见create_full_tear_sheet。

turnover_denomstr, optional

可以是AGB或portfolio_value,默认为AGB。 - 完整说明请参见txn.get_turnover。

unadjusted_returnspd.Series, optional

策略的每日未调整收益,非累积性。 将绘制额外的滑点扫描分析。

  • 参见 pyfolio.plotting.plot_swippage_sleep 和 pyfolio.plotting.plot_slippage_sensitivity

estimate_intraday: boolean or str, optional

日内策略的近似收益。 详情请参阅create_full_tear_sheet中的描述。

return_figboolean, optional

如果为True,则返回已绘制的图表。

pyfolio.tears.timer(msg_body, previous_time)

时间序列指标

模块 pyfolio.timeseries 提供绩效和风险指标。

pyfolio.timeseries.aggregate_returns(returns, convert_to)

按周、月或年汇总收益。

Parameters
returnspd.Series
Daily returns of the strategy, noncumulative.
convert_tostr

可以是 'weekly'(每周)、'monthly'(每月)或 'yearly'(每年)。

Returns
pd.Series

聚合收益率。

pyfolio.timeseries.alpha(returns, factor_returns)

计算年化阿尔法。

Parameters
returnspd.Series

策略的日收益率,非累计值。 - 完整解释请参见cum_returns()

factor_returnspd.Series

用于计算贝塔值的基准因子的每日非累积回报。通常是一个基准,如市场回报。

  • 这与收益的风格相同。

Returns
float

阿尔法。

pyfolio.timeseries.alpha_beta(returns, factor_returns)

计算阿尔法和贝塔值。

Parameters
returnspd.Series

策略的日收益率,非累计值。 - 完整解释请参见cum_returns()

factor_returnspd.Series

用于计算贝塔值的基准因子的每日非累积回报。通常是一个基准,如市场回报。

  • 这与收益的风格相同。

Returns
float

阿尔法。

float

Beta版。

pyfolio.timeseries.annual_return(returns, period='daily')

确定收益的平均年增长率。

Parameters
returnspd.Series

策略的周期回报,非累积形式。 - 完整解释请参见cum_returns()

periodstr, optional

定义'returns'数据的周期,用于年化计算。可选值为'monthly'(月度)、'weekly'(周度)或'daily'(日度)。 - 默认为'daily'(日度)。

Returns
float

年化回报率(复合年增长率)。

pyfolio.timeseries.annual_volatility(returns, period='daily')

确定策略的年化波动率。

Parameters
returnspd.Series

策略的周期回报,非累积形式。 - 完整解释请参见cum_returns()

periodstr, optional

定义'returns'数据的周期,用于年化波动率计算。可选值为'monthly'、'weekly'或'daily'。 - 默认为'daily'。

Returns
float

年化波动率。

pyfolio.timeseries.beta(returns, factor_returns)

计算beta值。

Parameters
returnspd.Series

策略的日收益率,非累计值。 - 完整解释请参见cum_returns()

factor_returnspd.Series

用于计算贝塔值的基准因子的每日非累积回报。通常是一个基准,如市场回报。

  • 这与收益的风格相同。

Returns
float

Beta版。

pyfolio.timeseries.calc_bootstrap(func, returns, *args, **kwargs)

对用户定义的返回汇总统计量的函数执行自助法分析。

Parameters
funcfunction

该函数可以接收单个数组(通常是收益数据)或两个数组(通常是收益和因子收益数据),并返回单个值(通常是汇总统计量)。额外的参数和关键字参数也会被传递。

returnspd.Series
Daily returns of the strategy, noncumulative.
  • 完整说明请参阅 tears.create_full_tear_sheet。

factor_returnspd.Series, optional

用于计算贝塔值的基准因子的每日非累积回报。通常是一个基准,如市场回报。

  • 这与收益的风格相同。

n_samplesint, optional

自举抽样的样本数量。默认为1000。 增加该值将得到更稳定/精确的估计结果。

Returns
numpy.ndarray

传入函数的自助采样分布。

pyfolio.timeseries.calc_distribution_stats(x)

计算数据的各种汇总统计量。

Parameters
xnumpy.ndarray or pandas.Series

用于计算汇总统计量的数组。

Returns
pandas.Series

包含传入值的均值、中位数、标准差以及5%、25%、75%和95%分位数的序列。

pyfolio.timeseries.calmar_ratio(returns, period='daily')

确定策略的卡尔玛比率(Calmar ratio)或回撤比率(drawdown ratio)。

Parameters
returnspd.Series

策略的日收益率,非累计值。 - 完整解释请参见cum_returns()

periodstr, optional

定义'returns'数据的周期,用于年化计算。可以是'monthly'(月度)、'weekly'(周度)或'daily'(日度)。 - 默认为'daily'(日度)。

Returns
float

Calmar比率(回撤比率),以浮点数形式返回。如果没有Calmar比率,则返回np.nan。

pyfolio.timeseries.common_sense_ratio(returns)

常识比率是尾部比率与收益-痛苦比率(总利润/总亏损)的乘积。

有关该指标动机的更多信息,请参阅http://bit.ly/1ORzGBk

Parameters
returnspd.Series
Daily returns of the strategy, noncumulative.
  • 完整说明请参阅tears.create_full_tear_sheet。

Returns
float

常识比率

pyfolio.timeseries.cum_returns(returns, starting_value=0)

根据简单收益率计算累计收益率。

Parameters
returnspd.Series
Daily returns of the strategy, noncumulative.
  • 完整说明请参阅 tears.create_full_tear_sheet。

starting_valuefloat, optional

起始回报率(默认为1)。

Returns
pandas.Series

累计收益序列。

备注

为了提高数值精度,在可以求和而非相乘的情况下,将输入转换为对数收益率。

pyfolio.timeseries.downside_risk(returns, required_return=0, period='daily')

确定低于阈值的下行偏差

Parameters
returnspd.Series or pd.DataFrame

策略的日收益率,非累计值。 - 完整解释请参见cum_returns()

required_return: float / series

最低可接受回报

periodstr, optional

定义'returns'数据的周期,用于年化计算。可选值为'monthly'、'weekly'或'daily'。 - 默认为'daily'。

Returns
depends on input type
series ==> float
DataFrame ==> np.array

年化下行偏差

pyfolio.timeseries.extract_interesting_date_ranges(returns, periods=None)

根据感兴趣的事件提取收益。参见gen_date_range_interesting。

Parameters
returnspd.Series
Daily returns of the strategy, noncumulative.
  • 完整说明请参阅 tears.create_full_tear_sheet。

Returns
rangesOrderedDict

所有有效事件的日期范围及其回报率。

pyfolio.timeseries.forecast_cone_bootstrap(is_returns, num_days, cone_std=(1.0, 1.5, 2.0), starting_value=1, num_samples=1000, random_seed=None)

确定预测累计收益的n个标准差锥体的上下界。未来的累计均值和标准差是通过从样本内日收益重复抽样(即自助法)计算得出的。该锥体是非参数化的,意味着它不假设收益服从正态分布。

Parameters
is_returnspd.Series
In-sample daily returns of the strategy, noncumulative.
  • 完整说明请参阅tears.create_full_tear_sheet。

num_daysint

向前预测概率锥的天数。

cone_stdint, float, or list of int/float

用于确定锥形边界范围的标准差数量。如果传入多个值,将为每个值生成对应的锥形边界。

starting_valueint or float

样本外期的起始值。

num_samplesint

从样本内日收益率中抽取的样本数量。 每个样本将是一个长度为num_days的数组。 样本数量越多,生成的bootstrap cone越准确。

random_seedint

用于pandas样本方法的伪随机数生成器的种子值。

Returns
pd.DataFrame

包含上下锥形边界。列名是字符串,对应高于(正值)或低于(负值)预测平均累积收益的标准差倍数。

pyfolio.timeseries.gen_drawdown_table(returns, top=10)

将最大回撤以表格形式展示。

Parameters
returnspd.Series
Daily returns of the strategy, noncumulative.
  • 完整说明请参阅tears.create_full_tear_sheet。

topint, optional

要查找的最大回撤数量(默认为10)。

Returns
df_drawdownspd.DataFrame

关于最大回撤的信息。

pyfolio.timeseries.get_max_drawdown(returns)

确定策略的最大回撤。

Parameters
returnspd.Series

策略的日收益率,非累计值。 - 完整解释请参见cum_returns()

Returns
float

最大回撤。

pyfolio.timeseries.get_max_drawdown_underwater(underwater)

根据给定的"水下"DataFrame确定峰值、谷值和恢复日期。

水下DataFrame是一个预先计算了滚动回撤的DataFrame。

Parameters
underwaterpd.Series

策略的水下回报(滚动回撤)。

Returns
peakdatetime

最大回撤的峰值。

valleydatetime

最大回撤的低谷。

recoverydatetime

最大回撤的恢复情况。

pyfolio.timeseries.get_top_drawdowns(returns, top=10)

找出最大的回撤,按回撤金额排序。

Parameters
returnspd.Series
Daily returns of the strategy, noncumulative.
  • 完整说明请参阅 tears.create_full_tear_sheet。

topint, optional

要查找的最大回撤数量(默认为10)。

Returns
drawdownslist

回撤峰值、谷值和恢复点的列表。参见 get_max_drawdown。

pyfolio.timeseries.gross_lev(positions)

计算策略的总杠杆率。

Parameters
positionspd.DataFrame
Daily net position values.
  • 完整说明请参阅 tears.create_full_tear_sheet。

Returns
pd.Series

总杠杆率。

pyfolio.timeseries.max_drawdown(returns)

确定策略的最大回撤。

Parameters
returnspd.Series
Daily returns of the strategy, noncumulative.
  • 完整说明请参阅 tears.create_full_tear_sheet。

Returns
float

最大回撤。

pyfolio.timeseries.normalize(returns, starting_value=1)

基于初始值对收益时间序列进行归一化处理。

Parameters
returnspd.Series
Daily returns of the strategy, noncumulative.
  • 完整说明请参阅 tears.create_full_tear_sheet。

starting_valuefloat, optional

起始回报率(默认为1)。

Returns
pd.Series

归一化收益。

pyfolio.timeseries.omega_ratio(returns, annual_return_threshhold=0.0)

确定策略的Omega比率。

Parameters
returnspd.Series

策略的日收益率,非累计值。 - 完整解释请参见cum_returns()

annual_return_thresholdfloat, optional

投资者可接受的最低回报率。年度阈值,超过该阈值的回报被视为正或负。它会转换为适合该比率回报周期的值。例如,年度最低可接受回报100转换为每日最低可接受回报0.01848。

(1 + 100) ** (1. / 252) - 1 = 0.01848

日收益率必须超过此值才能被视为正值。当日收益率按一年中平均工作日数复利计算时,可达到期望的年收益率。

(1 + 0.01848) ** 252 - 1 = 99.93

  • 默认为0.0

Returns
float

欧米茄比率。

pyfolio.timeseries.perf_stats(returns, factor_returns=None, positions=None, transactions=None, turnover_denom='AGB')

计算策略的各种性能指标,用于plotting.show_perf_stats。

Parameters
returnspd.Series
Daily returns of the strategy, noncumulative.
  • 完整说明请参阅 tears.create_full_tear_sheet。

factor_returnspd.Series, optional

用于计算贝塔值的基准因子的每日非累积回报。通常是一个基准,如市场回报。

  • 这与收益的风格相同。

  • 如果为None,则不计算alpha、beta和信息比率。

positionspd.DataFrame
Daily net position values.
  • 完整说明请参阅 tears.create_full_tear_sheet。

transactionspd.DataFrame

已执行交易的价格和数量。每行代表一笔交易。 - 完整说明请参见 tears.create_full_tear_sheet。

turnover_denomstr

可以是AGB或portfolio_value,默认为AGB。 - 完整说明请参见txn.get_turnover。

Returns
pd.Series

性能指标。

pyfolio.timeseries.perf_stats_bootstrap(returns, factor_returns=None, return_stats=True, **kwargs)

计算策略的各种自助法(bootstrap)性能指标。

Parameters
returnspd.Series
Daily returns of the strategy, noncumulative.
  • 完整说明请参阅 tears.create_full_tear_sheet。

factor_returnspd.Series, optional

用于计算贝塔值的基准因子的每日非累积回报。通常是一个基准,如市场回报。

  • 这与收益的风格相同。

  • 如果为None,则不计算alpha、beta和信息比率。

return_statsboolean (optional)

如果为True,则返回每个性能指标的均值、中位数、5%和95%分位数的DataFrame。 如果为False,则返回每个性能指标的bootstrap样本的DataFrame。

Returns
pd.DataFrame

如果 return_stats 为 True: - 性能指标的引导抽样分布统计特性。 如果 return_stats 为 False: - 每个性能指标的引导样本。

pyfolio.timeseries.rolling_beta(returns, factor_returns, rolling_window=126)

确定策略的滚动贝塔值。

Parameters
returnspd.Series
Daily returns of the strategy, noncumulative.
  • 完整说明请参阅 tears.create_full_tear_sheet。

factor_returnspd.Series or pd.DataFrame

用于计算贝塔值的基准因子的每日非累积回报。通常是一个基准,如市场回报。

  • 如果传入的是DataFrame,则计算每列的滚动beta值。

  • 这与收益的风格相同。

rolling_windowint, optional

滚动窗口的大小(以天为单位),用于计算beta值(默认为6个月)。

Returns
pd.Series

滚动贝塔值。

pyfolio.timeseries.rolling_regression(returns, factor_returns, rolling_window=126, nan_threshold=0.1)

使用多元线性回归计算滚动因子贝塔值(单独进行线性回归存在问题,因为因子之间可能存在混淆)。

Parameters
returnspd.Series
Daily returns of the strategy, noncumulative.
  • 完整说明请参阅 tears.create_full_tear_sheet。

factor_returnspd.DataFrame

用于计算贝塔值的基准因子的每日非累积回报。通常是一个基准,如市场回报。

  • 计算每列的滚动贝塔值。

  • 这与收益的风格相同。

rolling_windowint, optional

计算beta值的天数窗口。默认为6个月。

nan_thresholdfloat, optional

如果NaN值超过此比例,将跳过给定日期的滚动回归计算。

Returns
pandas.DataFrame

包含滚动beta系数的DataFrame,对应SMB、HML和UMD因子

pyfolio.timeseries.rolling_sharpe(returns, rolling_sharpe_window)

确定策略的滚动夏普比率。

Parameters
returnspd.Series
Daily returns of the strategy, noncumulative.
  • 完整说明请参阅 tears.create_full_tear_sheet。

rolling_sharpe_windowint

滚动窗口的长度,以天为单位,用于计算。

Returns
pd.Series

滚动夏普比率。

pyfolio.timeseries.rolling_volatility(returns, rolling_vol_window)

确定策略的滚动波动率。

Parameters
returnspd.Series
Daily returns of the strategy, noncumulative.
  • 完整说明请参阅 tears.create_full_tear_sheet。

rolling_vol_windowint

滚动窗口的长度,以天为单位,用于计算。

Returns
pd.Series

滚动波动率。

pyfolio.timeseries.sharpe_ratio(returns, risk_free=0, period='daily')

确定策略的夏普比率。

Parameters
returnspd.Series

策略的日收益率,非累计值。 - 完整解释请参见cum_returns()

risk_freeint, float

整个期间的无风险回报率保持不变。

periodstr, optional

定义'returns'数据的周期,用于年化计算。可选值为'monthly'、'weekly'或'daily'。 - 默认为'daily'。

Returns
float

夏普比率。

np.nan

If insufficient length of returns or if if adjusted returns are 0.

pyfolio.timeseries.simulate_paths(is_returns, num_days, starting_value=1, num_samples=1000, random_seed=None)

使用样本内收益中的可用值生成替代路径。

Parameters
is_returnspandas.core.frame.DataFrame

样本内非累积收益。

num_daysint

向前预测概率锥的天数。

starting_valueint or float

样本外期的起始值。

num_samplesint

从样本内日收益率中抽取的样本数量。 每个样本将是一个长度为num_days的数组。 样本数量越多,生成的bootstrap cone越准确。

random_seedint

用于pandas样本方法的伪随机数生成器的种子值。

Returns
samplesnumpy.ndarray
pyfolio.timeseries.sortino_ratio(returns, required_return=0, period='daily')

确定策略的索提诺比率。

Parameters
returnspd.Series or pd.DataFrame

策略的日收益率,非累计值。 - 完整解释请参见cum_returns()

required_return: float / series

最低可接受回报

periodstr, optional

定义'returns'数据的周期,用于年化计算。可选值为'monthly'、'weekly'或'daily'。 - 默认为'daily'。

Returns
depends on input type
series ==> float
DataFrame ==> np.array

年化索提诺比率。

pyfolio.timeseries.stability_of_timeseries(returns)

确定累积对数收益线性拟合的R平方值。计算普通最小二乘线性拟合,并返回R平方值。

Parameters
returnspd.Series

策略的日收益率,非累计值。 - 完整解释请参见cum_returns()

Returns
float

R平方值。

pyfolio.timeseries.summarize_paths(samples, cone_std=(1.0, 1.5, 2.0), starting_value=1.0)

生成预测累计收益的n个标准差锥形区间的上下界。

Parameters
samplesnumpy.ndarray

替代路径,或一系列可能的结果。

cone_stdlist of int/float

用于确定锥形边界范围的标准差数量。如果传入多个值,将为每个值生成对应的锥形边界。

Returns
samplespandas.core.frame.DataFrame
pyfolio.timeseries.tail_ratio(returns)

确定右侧(95%)与左侧尾部(5%)之间的比率。

例如,比率为0.25意味着亏损的严重程度是盈利的四倍。

Parameters
returnspd.Series
Daily returns of the strategy, noncumulative.
Returns
float

尾部比率

pyfolio.timeseries.value_at_risk(returns, period=None, sigma=2.0)

获取风险价值(VaR)。

Parameters
returnspd.Series
Daily returns of the strategy, noncumulative.
  • 完整说明请参阅 tears.create_full_tear_sheet。

periodstr, optional

计算风险价值(VaR)的时间周期。可设置为'weekly'(周)、'monthly'(月)或'yearly'(年),否则默认使用收益率周期(通常为日)。

sigmafloat, optional

VaR的标准差,默认为2。

pyfolio.timeseries.var_cov_var_normal(P, c, mu=0, sigma=1)

投资组合中日风险价值(VaR)的方差-协方差计算。

Parameters
Pfloat

投资组合价值。

cfloat

置信水平。

mufloat, optional

均值。

Returns
float

方差-协方差。

绩效归因分析:

模块 pyfolio.perf_attrib 提供绩效和风险指标。

pyfolio.perf_attrib.compute_exposures(positions, factor_loadings, stack_positions=True, pos_in_dollars=True)

计算每日风险因子暴露。

对持仓进行标准化处理(如有必要)并调用ep.compute_exposures。 更多信息请参阅empyrical.compute_exposures。

Parameters
positions: pd.DataFrame or pd.Series

每日持仓(以美元或百分比表示),按日期索引,或者 按日期和股票代码索引的一系列持仓。 - 示例:

AAPL TLT XOM 现金

2017-01-01 34 58 10 0 2017-01-02 22 77 18 0 2017-01-03 -15 27 30 15

AAPL TLT XOM 现金

2017-01-01 0.333333 0.568627 0.098039 0.0 2017-01-02 0.188034 0.658120 0.153846 0.0 2017-01-03 0.208333 0.375000 0.416667 0.0

日期 股票代码 2017-01-01 AAPL 0.417582

TLT 0.010989 XOM 0.571429

2017-01-02 AAPL 0.202381

TLT 0.535714 XOM 0.261905

factor_loadingspd.DataFrame

日期范围内所有交易日的因子载荷,以日期和股票代码作为索引,因子作为列。 - 示例:

动量 反转

日期 股票代码 2017-01-01 AAPL -1.592914 0.852830

TLT 0.184864 0.895534 XOM 0.993160 1.149353

2017-01-02 AAPL -0.140009 -0.524952

TLT -1.066978 0.185435 XOM -1.798401 0.761549

stack_positionsbool

标志位,指示是否应将positions转换为长格式。

pos_in_dollarsbool

标志位,指示positions是以美元还是百分比为单位 如果为True,则表示positions以美元为单位。

Returns
risk_exposures_portfoliopd.DataFrame

数据框以日期时间作为索引,各因子作为列。 - 示例:

动量 反转

日期 2017-01-01 -0.238655 0.077123 2017-01-02 0.821872 1.520515

pyfolio.perf_attrib.create_perf_attrib_stats(perf_attrib, risk_exposures)

获取一段时间内的绩效归因数据,并计算年化多因子阿尔法、多因子夏普比率和风险敞口。

pyfolio.perf_attrib.perf_attrib(returns, positions, factor_returns, factor_loadings, transactions=None, pos_in_dollars=True)

将收益流的绩效归因于一组风险因子。

预处理输入数据,然后调用empyrical.perf_attrib。更多信息请参阅empyrical.perf_attrib。

绩效归因用于确定每个风险因素(如动量、科技板块等)对总收益的贡献比例,以及每日对各风险因素的暴露程度。可归因于给定风险因素的收益称为common_returns,而_无法_归因于风险因素的收益则称为specific_returns(即阿尔法收益)。common_returns与specific_returns相加始终等于总收益。

Parameters
returnspd.Series

返回日期范围内每一天的收益。 - 示例:

2017-01-01 -0.017098 2017-01-02 0.002683 2017-01-03 -0.008669

positions: pd.DataFrame

每日持仓(以美元或百分比表示),按日期索引。 如果持仓以美元为单位,将转换为百分比。 空头头寸显示在'cash'列中作为现金。 - 示例:

AAPL TLT XOM 现金

2017-01-01 34 58 10 0 2017-01-02 22 77 18 0 2017-01-03 -15 27 30 15

AAPL TLT XOM 现金

2017-01-01 0.333333 0.568627 0.098039 0.0 2017-01-02 0.188034 0.658120 0.153846 0.0 2017-01-03 0.208333 0.375000 0.416667 0.0

factor_returnspd.DataFrame

按因子返回收益,日期作为索引,因子作为列 - 示例:

动量 反转

2017-01-01 0.002779 -0.005453 2017-01-02 0.001096 0.010290

factor_loadingspd.DataFrame

日期范围内所有交易日的因子载荷,以日期和股票代码作为索引,因子作为列。 - 示例:

动量 反转

日期 股票代码 2017-01-01 AAPL -1.592914 0.852830

TLT 0.184864 0.895534 XOM 0.993160 1.149353

2017-01-02 AAPL -0.140009 -0.524952

TLT -1.066978 0.185435 XOM -1.798401 0.761549

transactionspd.DataFrame, optional

执行的交易量和成交价格。用于检查算法的换手率。默认为None,此时跳过换手率检查。

  • 每笔交易一行。

  • 同一时间发生的不同名称的交易将具有相同的索引。

  • 示例:

    索引 数量 价格 代码 2004-01-09 12:18:01 483 324.12 ‘AAPL’ 2004-01-09 12:18:01 122 83.10 ‘MSFT’ 2004-01-13 14:12:23 -75 340.43 ‘AAPL’

pos_in_dollarsbool

标志位,指示positions是以美元还是百分比为单位 如果为True,则表示positions以美元为单位。

Returns
tuple of (risk_exposures_portfolio, perf_attribution)
risk_exposures_portfoliopd.DataFrame

以日期时间为索引的df,因子作为列 - 示例:

动量 反转

日期 2017-01-01 -0.238655 0.077123 2017-01-02 0.821872 1.520515

perf_attributionpd.DataFrame

包含因子、共同收益和特定收益列的df数据框,以日期时间作为索引 - 示例:

动量 反转 共同收益 特定收益

日期 2017-01-01 0.249087 0.935925 1.185012 1.185012 2017-01-02 -0.003194 -0.400786 -0.403980 -0.403980

pyfolio.perf_attrib.plot_alpha_returns(alpha_returns, ax=None)

绘制每日多因子阿尔法收益(特定收益)的直方图。

Parameters
alpha_returnspd.Series

按日期时间索引的每日阿尔法收益序列

axmatplotlib.axes.Axes

绘制图表所用的坐标轴。如果为None,则使用当前坐标轴

Returns
axmatplotlib.axes.Axes
pyfolio.perf_attrib.plot_factor_contribution_to_perf(perf_attrib_data, ax=None, title='Cumulative common returns attribution')

绘制每个因子对绩效的贡献。

Parameters
perf_attrib_datapd.DataFrame

包含因子、共同收益和特定收益列的df数据框,以日期时间作为索引 - 示例:

动量 反转 共同收益 特定收益

日期 2017-01-01 0.249087 0.935925 1.185012 1.185012 2017-01-02 -0.003194 -0.400786 -0.403980 -0.403980

axmatplotlib.axes.Axes

绘制图表所用的坐标轴。如果为None,则使用当前坐标轴

titlestr, optional

图表标题

Returns
axmatplotlib.axes.Axes
pyfolio.perf_attrib.plot_returns(perf_attrib_data, cost=None, ax=None)

绘制总收益、特定收益和共同收益。

Parameters
perf_attrib_datapd.DataFrame

包含因子、共同收益和特定收益作为列的df,以日期时间作为索引。假设total_returns列未进行成本调整。 - 示例:

动量 反转 共同收益 特定收益

日期 2017-01-01 0.249087 0.935925 1.185012 1.185012 2017-01-02 -0.003194 -0.400786 -0.403980 -0.403980

costpd.Series, optional

如果存在,将从perf_attrib_data['total_returns']中减去,并单独绘制

axmatplotlib.axes.Axes

绘制图表所用的坐标轴。如果为None,将使用当前坐标轴

Returns
axmatplotlib.axes.Axes
pyfolio.perf_attrib.plot_risk_exposures(exposures, ax=None, title='Daily risk factor exposures')
Parameters
exposurespd.DataFrame

以日期时间为索引的df,因子作为列 - 示例:

动量 反转

日期 2017-01-01 -0.238655 0.077123 2017-01-02 0.821872 1.520515

axmatplotlib.axes.Axes

绘制图表所用的坐标轴。如果为None,将使用当前坐标轴

Returns
axmatplotlib.axes.Axes
pyfolio.perf_attrib.show_perf_attrib_stats(returns, positions, factor_returns, factor_loadings, transactions=None, pos_in_dollars=True)

使用输入调用perf_attrib,并通过utils.print_table显示输出结果。

绘图函数

模块 pyfolio.plotting 提供了性能指标的可视化功能。

pyfolio.plotting.customize(func)

装饰器,用于在函数调用期间设置绘图上下文和坐标轴样式。

pyfolio.plotting.plot_annual_returns(returns, ax=None, **kwargs)

绘制按年份统计的收益柱状图。

Parameters
returnspd.Series
Daily returns of the strategy, noncumulative.
  • 完整说明请参阅tears.create_full_tear_sheet。

axmatplotlib.Axes, optional

绘制坐标轴。

**kwargs, optional

传递给绘图函数。

Returns
axmatplotlib.Axes

绘制所在的坐标轴。

pyfolio.plotting.plot_capacity_sweep(returns, transactions, market_data, bt_starting_capital, min_pv=100000, max_pv=300000000, step_size=1000000, ax=None)
pyfolio.plotting.plot_cones(name, bounds, oos_returns, num_samples=1000, ax=None, cone_std=(1.0, 1.5, 2.0), random_seed=None, num_strikes=3)

绘制预测累计收益的n个标准差锥体的上下界。当累计收益超出上次绘制的锥体范围时,会重新绘制新的锥体。

Parameters
namestr

账户名称将用作图表标题。

boundspandas.core.frame.DataFrame

包含上下锥形边界。列名是字符串,对应高于(正值)或低于(负值)预测平均累积收益的标准差倍数。

oos_returnspandas.core.frame.DataFrame

非累积样本外收益。

num_samplesint

从样本内日收益率中抽取的样本数量。 每个样本将是一个长度为num_days的数组。 样本数量越多,生成的bootstrap cone越准确。

axmatplotlib.Axes, optional

绘制坐标轴。

cone_stdlist of int/float

用于确定锥形边界范围的标准差数量。如果传入多个值,将为每个值生成对应的锥形边界。

random_seedint

用于pandas样本方法的伪随机数生成器的种子值。

num_strikesint

绘制的锥体数量上限。可以是0到3之间的任意值。

Returns
Returns are either an ax or fig option, but not both. If a
matplotlib.Axes instance is passed in as ax, then it will be modified
and returned. This allows for users to plot interactively in jupyter
notebook. When no ax object is passed in, a matplotlib.figure instance
is generated and returned. This figure can then be used to save
the plot as an image without viewing it.
axmatplotlib.Axes

绘制在坐标轴上的图形。

figmatplotlib.figure

包含所有绘图元素的图形实例。

pyfolio.plotting.plot_daily_turnover_hist(transactions, positions, turnover_denom='AGB', ax=None, **kwargs)

绘制每日换手率的直方图。

Parameters
transactionspd.DataFrame
Prices and amounts of executed trades. One row per trade.
  • 完整说明请参阅tears.create_full_tear_sheet。

positionspd.DataFrame
Daily net position values.
  • 完整说明请参阅tears.create_full_tear_sheet。

turnover_denomstr, optional

可以是AGB或portfolio_value,默认为AGB。 - 完整说明请参见txn.get_turnover。

axmatplotlib.Axes, optional

绘制坐标轴。

**kwargs, optional

传递给seaborn绘图函数。

Returns
axmatplotlib.Axes

绘制在坐标轴上的图形。

pyfolio.plotting.plot_daily_volume(returns, transactions, ax=None, **kwargs)

绘制每日交易量与日期的对比图。

同时显示历史日均值。

Parameters
returnspd.Series
Daily returns of the strategy, noncumulative.
  • 完整说明请参阅tears.create_full_tear_sheet。

transactionspd.DataFrame
Prices and amounts of executed trades. One row per trade.
  • 完整说明请参阅tears.create_full_tear_sheet。

axmatplotlib.Axes, optional

绘制坐标轴。

**kwargs, optional

传递给绘图函数。

Returns
axmatplotlib.Axes

绘制所在的坐标轴。

pyfolio.plotting.plot_drawdown_periods(returns, top=10, ax=None, **kwargs)

绘制累计收益曲线,突出显示最大回撤期。

Parameters
returnspd.Series
Daily returns of the strategy, noncumulative.
  • 完整说明请参阅tears.create_full_tear_sheet。

topint, optional

要绘制的最大回撤周期数量(默认为10)。

axmatplotlib.Axes, optional

绘制坐标轴。

**kwargs, optional

传递给绘图函数。

Returns
axmatplotlib.Axes

绘制所在的坐标轴。

pyfolio.plotting.plot_drawdown_underwater(returns, ax=None, **kwargs)

绘制随时间推移收益低于水下的程度,或绘制当前回撤与日期的关系。

Parameters
returnspd.Series
Daily returns of the strategy, noncumulative.
  • 完整说明请参阅tears.create_full_tear_sheet。

axmatplotlib.Axes, optional

绘制坐标轴。

**kwargs, optional

传递给绘图函数。

Returns
axmatplotlib.Axes

绘制图表所用的坐标轴。

pyfolio.plotting.plot_exposures(returns, positions, ax=None, **kwargs)

绘制多头和空头头寸的饼状图。

Parameters
returnspd.Series
Daily returns of the strategy, noncumulative.
  • 完整说明请参阅tears.create_full_tear_sheet。

positions_allocpd.DataFrame

持仓组合的资产配置比例。参见 pos.get_percent_alloc。

axmatplotlib.Axes, optional

绘制坐标轴。

**kwargs, optional

传递给绘图函数。

Returns
axmatplotlib.Axes

绘制所在的坐标轴。

pyfolio.plotting.plot_gross_leverage(returns, positions, ax=None, **kwargs)

绘制总杠杆率与日期的关系图。

总杠杆率是每股多头和空头敞口之和除以净资产值。

Parameters
returnspd.Series
Daily returns of the strategy, noncumulative.
  • 完整说明请参阅tears.create_full_tear_sheet。

positionspd.DataFrame
Daily net position values.
  • 完整说明请参见create_full_tear_sheet。

axmatplotlib.Axes, optional

绘制坐标轴。

**kwargs, optional

传递给绘图函数。

Returns
axmatplotlib.Axes

绘制所在的坐标轴。

pyfolio.plotting.plot_holdings(returns, positions, legend_loc='best', ax=None, **kwargs)

绘制持有活跃头寸(无论是空头还是多头)的股票总数量。显示每日总量、每月日均值以及历史日均值。

Parameters
returnspd.Series
Daily returns of the strategy, noncumulative.
  • 完整说明请参阅tears.create_full_tear_sheet。

positionspd.DataFrame, optional
Daily net position values.
  • 完整说明请参阅tears.create_full_tear_sheet。

legend_locmatplotlib.loc, optional

图例在图表上的位置。

axmatplotlib.Axes, optional

绘制坐标轴。

**kwargs, optional

传递给绘图函数。

Returns
axmatplotlib.Axes

绘制所在的坐标轴。

pyfolio.plotting.plot_long_short_holdings(returns, positions, legend_loc='upper left', ax=None, **kwargs)

绘制持有活跃仓位的股票总量,将做空和做多仓位以透明填充区域的形式区分展示。

Parameters
returnspd.Series
Daily returns of the strategy, noncumulative.
  • 完整说明请参阅tears.create_full_tear_sheet。

positionspd.DataFrame, optional
Daily net position values.
  • 完整说明请参阅tears.create_full_tear_sheet。

legend_locmatplotlib.loc, optional

图例在图表上的位置。

axmatplotlib.Axes, optional

绘制坐标轴。

**kwargs, optional

传递给绘图函数。

Returns
axmatplotlib.Axes

绘制所在的坐标轴。

pyfolio.plotting.plot_max_median_position_concentration(positions, ax=None, **kwargs)

绘制多头和空头头寸集中度随时间变化的最大值和中位数。

Parameters
positionspd.DataFrame

该策略随时间变化的持仓情况。

axmatplotlib.Axes, optional

绘制坐标轴。

Returns
axmatplotlib.Axes

绘制图表所用的坐标轴。

pyfolio.plotting.plot_monthly_returns_dist(returns, ax=None, **kwargs)

绘制月度收益的分布图。

Parameters
returnspd.Series
Daily returns of the strategy, noncumulative.
  • 完整说明请参阅tears.create_full_tear_sheet。

axmatplotlib.Axes, optional

绘制坐标轴。

**kwargs, optional

传递给绘图函数。

Returns
axmatplotlib.Axes

绘制所在的坐标轴。

pyfolio.plotting.plot_monthly_returns_heatmap(returns, ax=None, **kwargs)

绘制按月份划分的收益热力图。

Parameters
returnspd.Series
Daily returns of the strategy, noncumulative.
  • 完整说明请参阅tears.create_full_tear_sheet。

axmatplotlib.Axes, optional

绘制坐标轴。

**kwargs, optional

传递给seaborn绘图函数。

Returns
axmatplotlib.Axes

绘制在坐标轴上的图形。

pyfolio.plotting.plot_monthly_returns_timeseries(returns, ax=None, **kwargs)

将月度收益绘制为时间序列图。

Parameters
returnspd.Series
Daily returns of the strategy, noncumulative.
  • 完整说明请参阅tears.create_full_tear_sheet。

axmatplotlib.Axes, optional

绘制坐标轴。

**kwargs, optional

传递给seaborn绘图函数。

Returns
axmatplotlib.Axes

绘制在坐标轴上的图形。

pyfolio.plotting.plot_perf_stats(returns, factor_returns, ax=None)

创建策略部分绩效指标的箱线图。 箱须的宽度由自助法(bootstrap)确定。

Parameters
returnspd.Series
Daily returns of the strategy, noncumulative.
  • 完整说明请参阅tears.create_full_tear_sheet。

factor_returnspd.Series

用于计算贝塔值的基准因子的每日非累积回报。通常是一个基准,如市场回报。

  • 这与收益的风格相同。

axmatplotlib.Axes, optional

绘制坐标轴。

Returns
axmatplotlib.Axes

绘制在坐标轴上的图形。

pyfolio.plotting.plot_prob_profit_trade(round_trips, ax=None)

绘制盈利交易事件的概率分布图。

Parameters
round_tripspd.DataFrame

每笔往返交易对应一行的DataFrame。 - 完整说明请参阅round_trips.extract_round_trips

axmatplotlib.Axes, optional

绘制坐标轴。

Returns
axmatplotlib.Axes

绘制所在的坐标轴。

pyfolio.plotting.plot_return_quantiles(returns, live_start_date=None, ax=None, **kwargs)

创建一个展示日回报、周回报和月回报分布的箱线图。

Parameters
returnspd.Series
Daily returns of the strategy, noncumulative.
  • 完整说明请参阅tears.create_full_tear_sheet。

live_start_datedatetime, optional

策略在回测期结束后开始实盘交易的时间点。

axmatplotlib.Axes, optional

绘制坐标轴。

**kwargs, optional

传递给seaborn绘图函数。

Returns
axmatplotlib.Axes

绘制在坐标轴上的图形。

pyfolio.plotting.plot_returns(returns, live_start_date=None, ax=None)

绘制随时间变化的原始收益。

回测收益以绿色显示,样本外(实盘交易)收益以红色显示。

Parameters
returnspd.Series
Daily returns of the strategy, noncumulative.
  • 完整说明请参阅tears.create_full_tear_sheet。

live_start_datedatetime, optional

策略在回测期结束后开始实盘交易的日期。该日期应进行标准化处理。

axmatplotlib.Axes, optional

绘制坐标轴。

**kwargs, optional

传递给绘图函数。

Returns
axmatplotlib.Axes

绘制图表所用的坐标轴。

pyfolio.plotting.plot_rolling_beta(returns, factor_returns, legend_loc='best', ax=None, **kwargs)

绘制6个月和12个月滚动贝塔值随时间变化的图表。

Parameters
returnspd.Series
Daily returns of the strategy, noncumulative.
  • 完整说明请参阅tears.create_full_tear_sheet。

factor_returnspd.Series

用于计算贝塔值的基准因子的每日非累积回报。通常是一个基准,如市场回报。

  • 这与收益的风格相同。

legend_locmatplotlib.loc, optional

图例在图表上的位置。

axmatplotlib.Axes, optional

绘制坐标轴。

**kwargs, optional

传递给绘图函数。

Returns
axmatplotlib.Axes

绘制图表所用的坐标轴。

pyfolio.plotting.plot_rolling_returns(returns, factor_returns=None, live_start_date=None, logy=False, cone_std=None, legend_loc='best', volatility_match=False, cone_function=<function forecast_cone_bootstrap>, ax=None, **kwargs)

绘制累计滚动回报与某些基准的对比。

回测收益显示为绿色,样本外(实盘交易)收益显示为红色。

此外,可以在样本外收益区域添加一个非参数锥形图。

Parameters
returnspd.Series
Daily returns of the strategy, noncumulative.
  • 完整说明请参阅tears.create_full_tear_sheet。

factor_returnspd.Series, optional

用于计算贝塔值的基准因子的每日非累积回报。通常是一个基准,如市场回报。

  • 这与收益的风格相同。

live_start_datedatetime, optional

策略在回测期结束后开始实盘交易的日期。该日期应进行标准化处理。

logybool, optional

是否对y轴使用对数刻度。

cone_stdfloat, or tuple, optional

如果是浮点数,表示用于锥形图的标准差。 如果是元组,表示用于锥形图的标准差值组成的元组

  • 更多详情请参阅 timeseries.forecast_cone_bounds。

legend_locmatplotlib.loc, optional

图例在图表上的位置。

volatility_matchbool, optional

是否将收益的波动率归一化为基准收益的波动率。这有助于比较具有不同波动率的策略。需要传入benchmark_rets参数。

cone_functionfunction, optional

用于生成预测概率锥形图的函数。 该函数签名必须遵循以下形式: def cone(in_sample_returns (pd.Series),

days_to_project_forward (int), cone_std= (float, or tuple), starting_value= (int, or float))

参见 timeseries.forecast_cone_bootstrap 的示例。

axmatplotlib.Axes, optional

绘制坐标轴。

**kwargs, optional

传递给绘图函数。

Returns
axmatplotlib.Axes

绘制所在的坐标轴。

pyfolio.plotting.plot_rolling_sharpe(returns, factor_returns=None, rolling_window=126, legend_loc='best', ax=None, **kwargs)

绘制滚动夏普比率与日期的关系图。

Parameters
returnspd.Series
Daily returns of the strategy, noncumulative.
  • 完整说明请参阅tears.create_full_tear_sheet。

factor_returnspd.Series, optional

用于计算基准滚动夏普率的基准因子的每日非累积回报。通常是一个基准,如市场回报。

  • 这与收益的风格相同。

rolling_windowint, optional

计算夏普比率的天数窗口。

legend_locmatplotlib.loc, optional

图例在图表上的位置。

axmatplotlib.Axes, optional

绘制坐标轴。

**kwargs, optional

传递给绘图函数。

Returns
axmatplotlib.Axes

绘制所在的坐标轴。

pyfolio.plotting.plot_rolling_volatility(returns, factor_returns=None, rolling_window=126, legend_loc='best', ax=None, **kwargs)

绘制滚动波动率与日期的关系图。

Parameters
returnspd.Series
Daily returns of the strategy, noncumulative.
  • 完整说明请参阅tears.create_full_tear_sheet。

factor_returnspd.Series, optional

用于计算基准滚动波动率的基准因子的每日非累积回报。通常是一个基准,如市场回报。

  • 这与收益的风格相同。

rolling_windowint, optional

计算波动率的天数窗口。

legend_locmatplotlib.loc, optional

图例在图表上的位置。

axmatplotlib.Axes, optional

绘制坐标轴。

**kwargs, optional

传递给绘图函数。

Returns
axmatplotlib.Axes

绘制所在的坐标轴。

pyfolio.plotting.plot_round_trip_lifetimes(round_trips, disp_amount=16, lsize=18, ax=None)

绘制一组往返交易的持续时间与方向样本。

Parameters
round_tripspd.DataFrame

每笔往返交易对应一行的DataFrame。 - 完整说明请参阅round_trips.extract_round_trips

axmatplotlib.Axes, optional

绘制坐标轴。

Returns
axmatplotlib.Axes

绘制图表所用的坐标轴。

pyfolio.plotting.plot_sector_allocations(returns, sector_alloc, ax=None, **kwargs)

绘制投资组合随时间变化的行业风险敞口。

Parameters
returnspd.Series
Daily returns of the strategy, noncumulative.
  • 完整说明请参阅tears.create_full_tear_sheet。

sector_allocpd.DataFrame

持仓组合的资产配置情况。参见 pos.get_sector_alloc。

axmatplotlib.Axes, optional

绘制坐标轴。

**kwargs, optional

传递给绘图函数。

Returns
axmatplotlib.Axes

绘制图表所用的坐标轴。

pyfolio.plotting.plot_slippage_sensitivity(returns, positions, transactions, ax=None, **kwargs)

绘制每美元滑点与年均回报率的关系曲线。

Parameters
returnspd.Series

投资组合收益的时间序列,将针对不同程度的滑点进行调整。

positionspd.DataFrame
Daily net position values.
  • 完整说明请参阅tears.create_full_tear_sheet。

transactionspd.DataFrame
Prices and amounts of executed trades. One row per trade.
  • 完整说明请参阅tears.create_full_tear_sheet。

axmatplotlib.Axes, optional

绘制坐标轴。

**kwargs, optional

传递给seaborn绘图函数。

Returns
axmatplotlib.Axes

绘制图表所用的坐标轴。

pyfolio.plotting.plot_slippage_sweep(returns, positions, transactions, slippage_params=(3, 8, 10, 12, 15, 20, 50), ax=None, **kwargs)

在不同每美元滑点假设下绘制权益曲线。

Parameters
returnspd.Series

投资组合收益的时间序列,将针对不同程度的滑点进行调整。

positionspd.DataFrame
Daily net position values.
  • 完整说明请参阅tears.create_full_tear_sheet。

transactionspd.DataFrame
Prices and amounts of executed trades. One row per trade.
  • 完整说明请参阅tears.create_full_tear_sheet。

slippage_params: tuple

应用于回报时间序列的滑点参数(以基点为单位)。

axmatplotlib.Axes, optional

绘制坐标轴。

**kwargs, optional

传递给seaborn绘图函数。

Returns
axmatplotlib.Axes

绘制图表所用的坐标轴。

pyfolio.plotting.plot_turnover(returns, transactions, positions, turnover_denom='AGB', legend_loc='best', ax=None, **kwargs)

绘制换手率与日期的关系图。

换手率是指在一定时期内交易的股票数量占总股本的比例。

显示每日总计、每月日均值以及历史日均值。

Parameters
returnspd.Series
Daily returns of the strategy, noncumulative.
  • 完整说明请参阅tears.create_full_tear_sheet。

transactionspd.DataFrame
Prices and amounts of executed trades. One row per trade.
  • 完整说明请参阅tears.create_full_tear_sheet。

positionspd.DataFrame
Daily net position values.
  • 完整说明请参阅tears.create_full_tear_sheet。

turnover_denomstr, optional

可以是AGB或portfolio_value,默认为AGB。 - 完整说明请参见txn.get_turnover。

legend_locmatplotlib.loc, optional

图例在图表上的位置。

axmatplotlib.Axes, optional

绘制坐标轴。

**kwargs, optional

传递给绘图函数。

Returns
axmatplotlib.Axes

绘制图表所用的坐标轴。

pyfolio.plotting.plot_txn_time_hist(transactions, bin_minutes=5, tz='America/New_York', ax=None, **kwargs)

绘制交易时间的直方图,将时间按给定时长分桶。

Parameters
transactionspd.DataFrame
Prices and amounts of executed trades. One row per trade.
  • 完整说明请参阅tears.create_full_tear_sheet。

bin_minutesfloat, optional

分箱大小(以分钟计),默认为5分钟。

tzstr, optional

绘制时区。请注意,如果指定的时区不适用夏令时,分布可能会部分偏移。

axmatplotlib.Axes, optional

绘制坐标轴。

**kwargs, optional

传递给绘图函数。

Returns
axmatplotlib.Axes

绘制图表所用的坐标轴。

pyfolio.plotting.show_and_plot_top_positions(returns, positions_alloc, show_and_plot=2, hide_positions=False, legend_loc='real_best', ax=None, **kwargs)

打印和/或绘制所有时间持仓前10位的风险敞口。

Parameters
returnspd.Series
Daily returns of the strategy, noncumulative.
  • 完整说明请参阅tears.create_full_tear_sheet。

positions_allocpd.DataFrame

持仓组合的资产配置比例。参见 pos.get_percent_alloc。

show_and_plotint, optional

默认值为2,表示同时打印和绘图。 如果设为0,则仅绘图;如果设为1,则仅打印。

hide_positionsbool, optional

如果为True,将不会输出任何符号名称。

legend_locmatplotlib.loc, optional

图例在图表上的位置。 默认情况下,图例会显示在图表下方。

axmatplotlib.Axes, optional

绘制坐标轴。

**kwargs, optional

传递给绘图函数。

Returns
axmatplotlib.Axes, conditional

绘制图表所用的坐标轴。

pyfolio.plotting.show_perf_stats(returns, factor_returns=None, positions=None, transactions=None, turnover_denom='AGB', live_start_date=None, bootstrap=False, header_rows=None)

打印策略的一些性能指标。

  • 显示策略在回测和样本外(实盘交易)中运行的时间长度。

  • 显示Omega比率、最大回撤、Calmar比率、年化收益率、稳定性、夏普比率、年化波动率、阿尔法和贝塔。

Parameters
returnspd.Series
Daily returns of the strategy, noncumulative.
  • 完整说明请参阅tears.create_full_tear_sheet。

factor_returnspd.Series, optional

用于计算贝塔值的基准因子的每日非累积回报。通常是一个基准,如市场回报。

  • 这与收益的风格相同。

positionspd.DataFrame, optional
Daily net position values.
  • 完整说明请参见create_full_tear_sheet。

transactionspd.DataFrame, optional

已执行交易的价格和数量。每行代表一笔交易。 - 完整说明请参见 tears.create_full_tear_sheet

turnover_denomstr, optional

可以是AGB或portfolio_value,默认为AGB。 - 完整说明请参见txn.get_turnover。

live_start_datedatetime, optional

策略在回测期结束后开始实盘交易的时间点。

bootstrapboolean, optional

是否对性能指标执行引导分析。

  • 更多信息,请参阅 timeseries.perf_stats_bootstrap

header_rowsdict or OrderedDict, optional

在显示表格顶部额外显示的行数。

pyfolio.plotting.show_profit_attribution(round_trips)

显示每个交易标的对总盈亏的贡献比例。

Parameters
round_tripspd.DataFrame

每笔往返交易对应一行的DataFrame。 - 完整说明请参阅round_trips.extract_round_trips

axmatplotlib.Axes, optional

绘制坐标轴。

Returns
axmatplotlib.Axes

绘制图表所用的坐标轴。

pyfolio.plotting.show_worst_drawdown_periods(returns, top=5)

打印有关最严重回撤期间的信息。

打印峰值日期、谷值日期、恢复日期和净回撤。

Parameters
returnspd.Series
Daily returns of the strategy, noncumulative.
  • 完整说明请参阅tears.create_full_tear_sheet。

topint, optional

要绘制的最大回撤期数量(默认为5)。

实用工具

模块 pyfolio.utils 包含各种辅助函数,例如将因子数据格式化为所需的输入格式。

pyfolio.utils.check_intraday(estimate, returns, positions, transactions)

用于检查策略是否为日内交易并进行处理的逻辑。

Parameters
estimate: boolean or str, optional

日内策略的近似收益。 详情请参阅tears.create_full_tear_sheet中的描述。

returnspd.Series
Daily returns of the strategy, noncumulative.
  • 完整说明请参见create_full_tear_sheet。

positionspd.DataFrame
Daily net position values.
  • 完整说明请参见create_full_tear_sheet。

transactionspd.DataFrame
Prices and amounts of executed trades. One row per trade.
  • 完整说明请参见create_full_tear_sheet。

Returns
pd.DataFrame

每日净持仓值,已根据日内波动调整。

pyfolio.utils.clip_returns_to_benchmark(rets, benchmark_rets)

从rets中删除条目,使rets的开始和结束日期与benchmark_rets的日期相匹配。

Parameters
retspd.Series
Daily returns of the strategy, noncumulative.
  • 更多详情请参阅 pf.tears.create_full_tear_sheet

benchmark_retspd.Series

基准的每日回报,非累计。

Returns
clipped_retspd.Series

每日非累积回报,其指数范围已调整以匹配基准回报的指数范围。

pyfolio.utils.configure_legend(ax, autofmt_xdate=True, change_colors=False, rotation=30, ha='right')

绩效归因图例格式说明: - 将图例置于图表右侧而非重叠 - 使图例顺序与图形线条对应 - 根据色谱设置颜色

pyfolio.utils.detect_intraday(positions, transactions, threshold=0.25)

尝试检测日内交易策略。获取每日收盘时持有的仓位数量,除以每日交易的唯一股票数量。如果平均商值低于阈值,则判定为日内交易策略。

Parameters
positionspd.DataFrame
Daily net position values.
  • 完整说明请参见create_full_tear_sheet。

transactionspd.DataFrame
Prices and amounts of executed trades. One row per trade.
  • 完整说明请参见create_full_tear_sheet。

Returns
boolean

如果检测到日内交易策略则为True。

pyfolio.utils.estimate_intraday(returns, positions, transactions, EOD_hour=23)

日内交易策略通常不会在交易日结束时持有头寸。 该方法尝试找出一天中最能代表该策略活动的时点, 并有效地将日终头寸与该时点头寸进行重新采样。 通过检测我们在市场中的敞口达到最高点时来确定该时点。 请注意,这是一个估算值。

Parameters
returnspd.Series
Daily returns of the strategy, noncumulative.
  • 完整说明请参见create_full_tear_sheet。

positionspd.DataFrame
Daily net position values.
  • 完整说明请参见create_full_tear_sheet。

transactionspd.DataFrame
Prices and amounts of executed trades. One row per trade.
  • 完整说明请参见create_full_tear_sheet。

Returns
pd.DataFrame

每日净持仓值,按日内行为重新采样。

pyfolio.utils.extract_rets_pos_txn_from_zipline(backtest)

从zipline.TradingAlgorithm.run()返回的回测数据结构中提取收益、持仓、交易和杠杆数据。

返回的数据结构格式与pyfolio其他部分兼容,可以直接传递给例如tears.create_full_tear_sheet()等函数。

Parameters
backtestpd.DataFrame

由zipline.TradingAlgorithm.run()返回的DataFrame

Returns
returnspd.Series
Daily returns of strategy.
  • 完整说明请参阅tears.create_full_tear_sheet。

positionspd.DataFrame
Daily net position values.
  • 完整说明请参阅tears.create_full_tear_sheet。

transactionspd.DataFrame
Prices and amounts of executed trades. One row per trade.
  • 完整说明请参阅tears.create_full_tear_sheet。

pyfolio.utils.format_asset(asset)

如果使用了zipline资产对象,我们希望能在分析报告中美观地展示它们。此函数应仅在显示前直接应用。

pyfolio.utils.get_symbol_rets(symbol, start=None, end=None)

调用当前注册的'returns_func'

Parameters
symbolobject

资产标识符,用于指定所需的收益序列。 例如股票代码或数据库ID

startdate, optional

获取数据的最早日期。 默认为可用的最早日期。

enddate, optional

获取数据的最新日期。 默认为可用的最新日期。

Returns
pandas.Series

由当前 'returns_func' 返回

pyfolio.utils.one_dec_places(x, pos)

在绘图刻度上添加1/10的小数位。

pyfolio.utils.percentage(x, pos)

在绘图刻度上添加百分比符号。

pyfolio.utils.print_table(table, name=None, float_format=None, formatters=None, header_rows=None)

漂亮地打印一个pandas DataFrame。

Uses HTML output if running inside Jupyter Notebook, otherwise formatted text output.

Parameters
tablepandas.Series or pandas.DataFrame

用于美化打印的表格。

namestr, optional

在左上角显示的表格名称。

float_formatfunction, optional

Formatter to use for displaying table elements, passed as the float_format arg to pd.Dataframe.to_html. E.g. ‘{0:.2%}’.format for displaying 100 as ‘100.00%’.

formatterslist or dict, optional

Formatters to use by column, passed as the formatters arg to pd.Dataframe.to_html.

header_rowsdict, optional

在表格顶部显示的额外行。

pyfolio.utils.register_return_func(func)

注册将被调用的'returns_func'函数,用于获取收益数据。

Parameters
funcfunction

一个返回资产收益pandas Series的函数。 该函数的签名必须如下所示

>>> func(symbol)

其中symbol是资产标识符

Returns
None
pyfolio.utils.sample_colormap(cmap_name, n_samples)

从matplotlib中采样一个颜色映射

pyfolio.utils.standardize_data(x)

使用均值和标准差对数组进行标准化处理。

Parameters
xnp.array

需要标准化的数组。

Returns
np.array

标准化数组。

pyfolio.utils.to_series(df)

用于测试;将DataFrame的第一列转换为Series。

pyfolio.utils.to_utc(df)

用于测试;将UTC时间戳应用于DataFrame。

pyfolio.utils.two_dec_places(x, pos)

在图表刻度上添加1/100的小数位。

pyfolio.utils.vectorize(func)

装饰器,使函数可以编写为处理Series,但仍可使用DataFrames调用。