API¶
The alphalens API is organized into four modules:
Tear Sheets:
alphalens.tears
Performance Metrics:
alphalens.performance
Plotting Functions:
alphalens.plotting
Utilities:
alphalens.utils
Tear Sheets¶
Alphalens combines key metrics in plots in thematic and summary tear sheets.
-
class
alphalens.tears.
GridFigure
(rows, cols)¶ Bases:
object
It makes life easier with grid plots
Methods
close
next_cell
next_row
-
close
()¶
-
next_cell
()¶
-
next_row
()¶
-
-
alphalens.tears.
create_event_returns_tear_sheet
(factor_data, returns, avgretplot=(5, 15), long_short=True, group_neutral=False, std_bar=True, by_group=False)¶ Creates a tear sheet to view the average cumulative returns for a factor within a window (pre and post event).
- Parameters
- factor_datapd.DataFrame - MultiIndex
A MultiIndex Series indexed by date (level 0) and asset (level 1), containing the values for a single alpha factor, the factor quantile/bin that factor value belongs to and (optionally) the group the asset belongs to. - See full explanation in utils.get_clean_factor_and_forward_returns
- returnspd.DataFrame
A DataFrame indexed by date with assets in the columns containing daily returns. - See full explanation in utils.get_clean_factor_and_forward_returns
- avgretplot: tuple (int, int) - (before, after)
If not None, plot quantile average cumulative returns
- long_shortbool
Should this computation happen on a long short portfolio? if so then factor returns will be demeaned across the factor universe
- group_neutralbool
Should this computation happen on a group neutral portfolio? if so, returns demeaning will occur on the group level.
- std_barboolean, optional
Show plots with standard deviation bars, one for each quantile
- by_groupbool
If True, display graphs separately for each group.
-
alphalens.tears.
create_event_study_tear_sheet
(factor_data, returns, avgretplot=(5, 15), rate_of_ret=True, n_bars=50)¶ Creates an event study tear sheet for analysis of a specific event.
- Parameters
- factor_datapd.DataFrame - MultiIndex
A MultiIndex DataFrame indexed by date (level 0) and asset (level 1), containing the values for a single event, forward returns for each period, the factor quantile/bin that factor value belongs to, and (optionally) the group the asset belongs to.
- returnspd.DataFrame, required only if ‘avgretplot’ is provided
A DataFrame indexed by date with assets in the columns containing daily returns. - See full explanation in utils.get_clean_factor_and_forward_returns
- avgretplot: tuple (int, int) - (before, after), optional
If not None, plot event style average cumulative returns within a window (pre and post event).
- rate_of_retbool, optional
Display rate of return instead of simple return in ‘Mean Period Wise Return By Factor Quantile’ and ‘Period Wise Return By Factor Quantile’ plots
- n_barsint, optional
Number of bars in event distribution plot
-
alphalens.tears.
create_full_tear_sheet
(factor_data, long_short=True, group_neutral=False, by_group=False)¶ Creates a full tear sheet for analysis and evaluating single return predicting (alpha) factor.
- Parameters
- factor_datapd.DataFrame - MultiIndex
A MultiIndex DataFrame indexed by date (level 0) and asset (level 1), containing the values for a single alpha factor, forward returns for each period, the factor quantile/bin that factor value belongs to, and (optionally) the group the asset belongs to. - See full explanation in utils.get_clean_factor_and_forward_returns
- long_shortbool
Should this computation happen on a long short portfolio? - See tears.create_returns_tear_sheet for details on how this flag affects returns analysis
- group_neutralbool
Should this computation happen on a group neutral portfolio? - See tears.create_returns_tear_sheet for details on how this flag affects returns analysis - See tears.create_information_tear_sheet for details on how this flag affects information analysis
- by_groupbool
If True, display graphs separately for each group.
-
alphalens.tears.
create_information_tear_sheet
(factor_data, group_neutral=False, by_group=False)¶ Creates a tear sheet for information analysis of a factor.
- Parameters
- factor_datapd.DataFrame - MultiIndex
A MultiIndex DataFrame indexed by date (level 0) and asset (level 1), containing the values for a single alpha factor, forward returns for each period, the factor quantile/bin that factor value belongs to, and (optionally) the group the asset belongs to. - See full explanation in utils.get_clean_factor_and_forward_returns
- group_neutralbool
Demean forward returns by group before computing IC.
- by_groupbool
If True, display graphs separately for each group.
-
alphalens.tears.
create_returns_tear_sheet
(factor_data, long_short=True, group_neutral=False, by_group=False)¶ Creates a tear sheet for returns analysis of a factor.
- Parameters
- factor_datapd.DataFrame - MultiIndex
A MultiIndex DataFrame indexed by date (level 0) and asset (level 1), containing the values for a single alpha factor, forward returns for each period, the factor quantile/bin that factor value belongs to, and (optionally) the group the asset belongs to. - See full explanation in utils.get_clean_factor_and_forward_returns
- long_shortbool
Should this computation happen on a long short portfolio? if so, then mean quantile returns will be demeaned across the factor universe. Additionally factor values will be demeaned across the factor universe when factor weighting the portfolio for cumulative returns plots
- group_neutralbool
Should this computation happen on a group neutral portfolio? if so, returns demeaning will occur on the group level. Additionally each group will weight the same in cumulative returns plots
- by_groupbool
If True, display graphs separately for each group.
-
alphalens.tears.
create_summary_tear_sheet
(factor_data, long_short=True, group_neutral=False)¶ Creates a small summary tear sheet with returns, information, and turnover analysis.
- Parameters
- factor_datapd.DataFrame - MultiIndex
A MultiIndex DataFrame indexed by date (level 0) and asset (level 1), containing the values for a single alpha factor, forward returns for each period, the factor quantile/bin that factor value belongs to, and (optionally) the group the asset belongs to. - See full explanation in utils.get_clean_factor_and_forward_returns
- long_shortbool
Should this computation happen on a long short portfolio? if so, then mean quantile returns will be demeaned across the factor universe.
- group_neutralbool
Should this computation happen on a group neutral portfolio? if so, returns demeaning will occur on the group level.
-
alphalens.tears.
create_turnover_tear_sheet
(factor_data, turnover_periods=None)¶ Creates a tear sheet for analyzing the turnover properties of a factor.
- Parameters
- factor_datapd.DataFrame - MultiIndex
A MultiIndex DataFrame indexed by date (level 0) and asset (level 1), containing the values for a single alpha factor, forward returns for each period, the factor quantile/bin that factor value belongs to, and (optionally) the group the asset belongs to. - See full explanation in utils.get_clean_factor_and_forward_returns
- turnover_periodssequence[string], optional
Periods to compute turnover analysis on. By default periods in ‘factor_data’ are used but custom periods can provided instead. This can be useful when periods in ‘factor_data’ are not multiples of the frequency at which factor values are computed i.e. the periods are 2h and 4h and the factor is computed daily and so values like [‘1D’, ‘2D’] could be used instead
Performance Metrics¶
The module alphalens.performance
provides performance and risk metrics.
-
alphalens.performance.
average_cumulative_return_by_quantile
(factor_data, returns, periods_before=10, periods_after=15, demeaned=True, group_adjust=False, by_group=False)¶ Plots average cumulative returns by factor quantiles in the period range defined by -periods_before to periods_after
- Parameters
- factor_datapd.DataFrame - MultiIndex
A MultiIndex DataFrame indexed by date (level 0) and asset (level 1), containing the values for a single alpha factor, forward returns for each period, the factor quantile/bin that factor value belongs to, and (optionally) the group the asset belongs to. - See full explanation in utils.get_clean_factor_and_forward_returns
- returnspd.DataFrame
A wide form Pandas DataFrame indexed by date with assets in the columns. Returns data should span the factor analysis time period plus/minus an additional buffer window corresponding to periods_after/ periods_before parameters.
- periods_beforeint, optional
How many periods before factor to plot
- periods_afterint, optional
How many periods after factor to plot
- demeanedbool, optional
Compute demeaned mean returns (long short portfolio)
- group_adjustbool
Returns demeaning will occur on the group level (group neutral portfolio)
- by_groupbool
If True, compute cumulative returns separately for each group
- Returns
- cumulative returns and std deviationpd.DataFrame
A MultiIndex DataFrame indexed by quantile (level 0) and mean/std (level 1) and the values on the columns in range from -periods_before to periods_after If by_group=True the index will have an additional ‘group’ level
--------------------------------------------------- | | -2 | -1 | 0 | 1 | ... --------------------------------------------------- quantile | | | | | | --------------------------------------------------- | mean | x | x | x | x | 1 --------------------------------------- | std | x | x | x | x | --------------------------------------------------- | mean | x | x | x | x | 2 --------------------------------------- | std | x | x | x | x | --------------------------------------------------- ... | ... ---------------------------------------------------
-
alphalens.performance.
common_start_returns
(factor, returns, before, after, cumulative=False, mean_by_date=False, demean_by=None)¶ A date and equity pair is extracted from each index row in the factor dataframe and for each of these pairs a return series is built starting from ‘before’ the date and ending ‘after’ the date specified in the pair. All those returns series are then aligned to a common index (-before to after) and returned as a single DataFrame
- Parameters
- factorpd.DataFrame
DataFrame with at least date and equity as index, the columns are irrelevant
- returnspd.DataFrame
A wide form Pandas DataFrame indexed by date with assets in the columns. Returns data should span the factor analysis time period plus/minus an additional buffer window corresponding to after/before period parameters.
- before:
How many returns to load before factor date
- after:
How many returns to load after factor date
- cumulative: bool, optional
Whether or not the given returns are cumulative. If False the given returns are assumed to be daily.
- mean_by_date: bool, optional
If True, compute mean returns for each date and return that instead of a return series for each asset
- demean_by: pd.DataFrame, optional
DataFrame with at least date and equity as index, the columns are irrelevant. For each date a list of equities is extracted from ‘demean_by’ index and used as universe to compute demeaned mean returns (long short portfolio)
- Returns
- aligned_returnspd.DataFrame
Dataframe containing returns series for each factor aligned to the same index: -before to after
-
alphalens.performance.
compute_mean_returns_spread
(mean_returns, upper_quant, lower_quant, std_err=None)¶ Computes the difference between the mean returns of two quantiles. Optionally, computes the standard error of this difference.
- Parameters
- mean_returnspd.DataFrame
DataFrame of mean period wise returns by quantile. MultiIndex containing date and quantile. See mean_return_by_quantile.
- upper_quantint
Quantile of mean return from which we wish to subtract lower quantile mean return.
- lower_quantint
Quantile of mean return we wish to subtract from upper quantile mean return.
- std_errpd.DataFrame, optional
Period wise standard error in mean return by quantile. Takes the same form as mean_returns.
- Returns
- mean_return_differencepd.Series
Period wise difference in quantile returns.
- joint_std_errpd.Series
Period wise standard error of the difference in quantile returns. if std_err is None, this will be None
-
alphalens.performance.
create_pyfolio_input
(factor_data, period, capital=None, long_short=True, group_neutral=False, equal_weight=False, quantiles=None, groups=None, benchmark_period='1D')¶ Simulate a portfolio using the input factor and returns the portfolio performance data properly formatted for Pyfolio analysis.
For more details on how this portfolio is built see: - performance.cumulative_returns (how the portfolio returns are computed) - performance.factor_weights (how assets weights are computed)
- Parameters
- factor_datapd.DataFrame - MultiIndex
A MultiIndex DataFrame indexed by date (level 0) and asset (level 1), containing the values for a single alpha factor, forward returns for each period, the factor quantile/bin that factor value belongs to, and (optionally) the group the asset belongs to. - See full explanation in utils.get_clean_factor_and_forward_returns
- periodstring
‘factor_data’ column name corresponding to the ‘period’ returns to be used in the computation of porfolio returns
- capitalfloat, optional
If set, then compute ‘positions’ in dollar amount instead of percentage
- long_shortbool, optional
if True enforce a dollar neutral long-short portfolio: asset weights will be computed by demeaning factor values and dividing by the sum of their absolute value (achieving gross leverage of 1) which will cause the portfolio to hold both long and short positions and the total weights of both long and short positions will be equal. If False the portfolio weights will be computed dividing the factor values and by the sum of their absolute value (achieving gross leverage of 1). Positive factor values will generate long positions and negative factor values will produce short positions so that a factor with only posive values will result in a long only portfolio.
- group_neutralbool, optional
If True simulates a group neutral portfolio: the portfolio weights will be computed so that each group will weigh the same. if ‘long_short’ is enabled the factor values demeaning will occur on the group level resulting in a dollar neutral, group neutral, long-short portfolio. If False group information will not be used in weights computation.
- equal_weightbool, optional
if True the assets will be equal-weighted. If long_short is True then the factor universe will be split in two equal sized groups with the top assets in long positions and bottom assets in short positions. if False the assets will be factor-weighed, see ‘long_short’ argument
- quantiles: sequence[int], optional
Use only specific quantiles in the computation. By default all quantiles are used
- groups: sequence[string], optional
Use only specific groups in the computation. By default all groups are used
- benchmark_periodstring, optional
By default benchmark returns are computed as the factor universe mean daily returns but ‘benchmark_period’ allows to choose a ‘factor_data’ column corresponding to the returns to be used in the computation of benchmark returns. More generally benchmark returns are computed as the factor universe returns traded at ‘benchmark_period’ frequency, equal weighting and long only
- Returns
- returnspd.Series
- Daily returns of the strategy, noncumulative.
Time series with decimal returns.
- Example:
2015-07-16 -0.012143 2015-07-17 0.045350 2015-07-20 0.030957 2015-07-21 0.004902
- positionspd.DataFrame
Time series of dollar amount (or percentage when ‘capital’ is not provided) invested in each position and cash.
Days where stocks are not held can be represented by 0.
Non-working capital is labelled ‘cash’
- Example:
index ‘AAPL’ ‘MSFT’ cash 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
- benchmarkpd.Series
Benchmark returns computed as the factor universe mean daily returns.
-
alphalens.performance.
cumulative_returns
(returns)¶ Computes cumulative returns from simple daily returns.
- Parameters
- returns: pd.Series
pd.Series containing daily factor returns (i.e. ‘1D’ returns).
- Returns
- Cumulative returns seriespd.Series
- Example:
2015-01-05 1.001310 2015-01-06 1.000805 2015-01-07 1.001092 2015-01-08 0.999200
-
alphalens.performance.
factor_alpha_beta
(factor_data, returns=None, demeaned=True, group_adjust=False, equal_weight=False)¶ Compute the alpha (excess returns), alpha t-stat (alpha significance), and beta (market exposure) of a factor. A regression is run with the period wise factor universe mean return as the independent variable and mean period wise return from a portfolio weighted by factor values as the dependent variable.
- Parameters
- factor_datapd.DataFrame - MultiIndex
A MultiIndex DataFrame indexed by date (level 0) and asset (level 1), containing the values for a single alpha factor, forward returns for each period, the factor quantile/bin that factor value belongs to, and (optionally) the group the asset belongs to. - See full explanation in utils.get_clean_factor_and_forward_returns
- returnspd.DataFrame, optional
Period wise factor returns. If this is None then it will be computed with ‘factor_returns’ function and the passed flags: ‘demeaned’, ‘group_adjust’, ‘equal_weight’
- demeanedbool
Control how to build factor returns used for alpha/beta computation – see performance.factor_return for a full explanation
- group_adjustbool
Control how to build factor returns used for alpha/beta computation – see performance.factor_return for a full explanation
- equal_weightbool, optional
Control how to build factor returns used for alpha/beta computation – see performance.factor_return for a full explanation
- Returns
- alpha_betapd.Series
A list containing the alpha, beta, a t-stat(alpha) for the given factor and forward returns.
-
alphalens.performance.
factor_cumulative_returns
(factor_data, period, long_short=True, group_neutral=False, equal_weight=False, quantiles=None, groups=None)¶ Simulate a portfolio using the factor in input and returns the cumulative returns of the simulated portfolio
- Parameters
- factor_datapd.DataFrame - MultiIndex
A MultiIndex DataFrame indexed by date (level 0) and asset (level 1), containing the values for a single alpha factor, forward returns for each period, the factor quantile/bin that factor value belongs to, and (optionally) the group the asset belongs to. - See full explanation in utils.get_clean_factor_and_forward_returns
- periodstring
‘factor_data’ column name corresponding to the ‘period’ returns to be used in the computation of porfolio returns
- long_shortbool, optional
if True then simulates a dollar neutral long-short portfolio - see performance.create_pyfolio_input for more details
- group_neutralbool, optional
If True then simulates a group neutral portfolio - see performance.create_pyfolio_input for more details
- equal_weightbool, optional
Control the assets weights: - see performance.create_pyfolio_input for more details
- quantiles: sequence[int], optional
Use only specific quantiles in the computation. By default all quantiles are used
- groups: sequence[string], optional
Use only specific groups in the computation. By default all groups are used
- Returns
- Cumulative returns seriespd.Series
- Example:
2015-07-16 09:30:00 -0.012143 2015-07-16 12:30:00 0.012546 2015-07-17 09:30:00 0.045350 2015-07-17 12:30:00 0.065897 2015-07-20 09:30:00 0.030957
-
alphalens.performance.
factor_information_coefficient
(factor_data, group_adjust=False, by_group=False)¶ Computes the Spearman Rank Correlation based Information Coefficient (IC) between factor values and N period forward returns for each period in the factor index.
- Parameters
- factor_datapd.DataFrame - MultiIndex
A MultiIndex DataFrame indexed by date (level 0) and asset (level 1), containing the values for a single alpha factor, forward returns for each period, the factor quantile/bin that factor value belongs to, and (optionally) the group the asset belongs to. - See full explanation in utils.get_clean_factor_and_forward_returns
- group_adjustbool
Demean forward returns by group before computing IC.
- by_groupbool
If True, compute period wise IC separately for each group.
- Returns
- icpd.DataFrame
Spearman Rank correlation between factor and provided forward returns.
-
alphalens.performance.
factor_positions
(factor_data, period, long_short=True, group_neutral=False, equal_weight=False, quantiles=None, groups=None)¶ Simulate a portfolio using the factor in input and returns the assets positions as percentage of the total portfolio.
- Parameters
- factor_datapd.DataFrame - MultiIndex
A MultiIndex DataFrame indexed by date (level 0) and asset (level 1), containing the values for a single alpha factor, forward returns for each period, the factor quantile/bin that factor value belongs to, and (optionally) the group the asset belongs to. - See full explanation in utils.get_clean_factor_and_forward_returns
- periodstring
‘factor_data’ column name corresponding to the ‘period’ returns to be used in the computation of porfolio returns
- long_shortbool, optional
if True then simulates a dollar neutral long-short portfolio - see performance.create_pyfolio_input for more details
- group_neutralbool, optional
If True then simulates a group neutral portfolio - see performance.create_pyfolio_input for more details
- equal_weightbool, optional
Control the assets weights: - see performance.create_pyfolio_input for more details.
- quantiles: sequence[int], optional
Use only specific quantiles in the computation. By default all quantiles are used
- groups: sequence[string], optional
Use only specific groups in the computation. By default all groups are used
- Returns
- assets positionspd.DataFrame
Assets positions series, datetime on index, assets on columns. Example:
index ‘AAPL’ ‘MSFT’ cash 2004-01-09 10:30:00 13939.3800 -14012.9930 711.5585 2004-01-09 15:30:00 0.00 -16012.9930 411.5585 2004-01-12 10:30:00 14492.6300 -14624.8700 0.0 2004-01-12 15:30:00 14874.5400 -15841.2500 0.0 2004-01-13 10:30:00 -13853.2800 13653.6400 -43.6375
-
alphalens.performance.
factor_rank_autocorrelation
(factor_data, period=1)¶ Computes autocorrelation of mean factor ranks in specified time spans. We must compare period to period factor ranks rather than factor values to account for systematic shifts in the factor values of all names or names within a group. This metric is useful for measuring the turnover of a factor. If the value of a factor for each name changes randomly from period to period, we’d expect an autocorrelation of 0.
- Parameters
- factor_datapd.DataFrame - MultiIndex
A MultiIndex DataFrame indexed by date (level 0) and asset (level 1), containing the values for a single alpha factor, forward returns for each period, the factor quantile/bin that factor value belongs to, and (optionally) the group the asset belongs to. - See full explanation in utils.get_clean_factor_and_forward_returns
- period: int, optional
Number of days over which to calculate the turnover.
- Returns
- autocorrpd.Series
Rolling 1 period (defined by time_rule) autocorrelation of factor values.
-
alphalens.performance.
factor_returns
(factor_data, demeaned=True, group_adjust=False, equal_weight=False, by_asset=False)¶ Computes period wise returns for portfolio weighted by factor values.
- Parameters
- factor_datapd.DataFrame - MultiIndex
A MultiIndex DataFrame indexed by date (level 0) and asset (level 1), containing the values for a single alpha factor, forward returns for each period, the factor quantile/bin that factor value belongs to, and (optionally) the group the asset belongs to. - See full explanation in utils.get_clean_factor_and_forward_returns
- demeanedbool
Control how to build factor weights – see performance.factor_weights for a full explanation
- group_adjustbool
Control how to build factor weights – see performance.factor_weights for a full explanation
- equal_weightbool, optional
Control how to build factor weights – see performance.factor_weights for a full explanation
- by_asset: bool, optional
If True, returns are reported separately for each esset.
- Returns
- returnspd.DataFrame
Period wise factor returns
-
alphalens.performance.
factor_weights
(factor_data, demeaned=True, group_adjust=False, equal_weight=False)¶ Computes asset weights by factor values and dividing by the sum of their absolute value (achieving gross leverage of 1). Positive factor values will results in positive weights and negative values in negative weights.
- Parameters
- factor_datapd.DataFrame - MultiIndex
A MultiIndex DataFrame indexed by date (level 0) and asset (level 1), containing the values for a single alpha factor, forward returns for each period, the factor quantile/bin that factor value belongs to, and (optionally) the group the asset belongs to. - See full explanation in utils.get_clean_factor_and_forward_returns
- demeanedbool
Should this computation happen on a long short portfolio? if True, weights are computed by demeaning factor values and dividing by the sum of their absolute value (achieving gross leverage of 1). The sum of positive weights will be the same as the negative weights (absolute value), suitable for a dollar neutral long-short portfolio
- group_adjustbool
Should this computation happen on a group neutral portfolio? If True, compute group neutral weights: each group will weight the same and if ‘demeaned’ is enabled the factor values demeaning will occur on the group level.
- equal_weightbool, optional
if True the assets will be equal-weighted instead of factor-weighted If demeaned is True then the factor universe will be split in two equal sized groups, top assets with positive weights and bottom assets with negative weights
- Returns
- returnspd.Series
Assets weighted by factor value.
-
alphalens.performance.
mean_information_coefficient
(factor_data, group_adjust=False, by_group=False, by_time=None)¶ Get the mean information coefficient of specified groups. Answers questions like: What is the mean IC for each month? What is the mean IC for each group for our whole timerange? What is the mean IC for for each group, each week?
- Parameters
- factor_datapd.DataFrame - MultiIndex
A MultiIndex DataFrame indexed by date (level 0) and asset (level 1), containing the values for a single alpha factor, forward returns for each period, the factor quantile/bin that factor value belongs to, and (optionally) the group the asset belongs to. - See full explanation in utils.get_clean_factor_and_forward_returns
- group_adjustbool
Demean forward returns by group before computing IC.
- by_groupbool
If True, take the mean IC for each group.
- by_timestr (pd time_rule), optional
Time window to use when taking mean IC. See http://pandas.pydata.org/pandas-docs/stable/timeseries.html for available options.
- Returns
- icpd.DataFrame
Mean Spearman Rank correlation between factor and provided forward price movement windows.
-
alphalens.performance.
mean_return_by_quantile
(factor_data, by_date=False, by_group=False, demeaned=True, group_adjust=False)¶ Computes mean returns for factor quantiles across provided forward returns columns.
- Parameters
- factor_datapd.DataFrame - MultiIndex
A MultiIndex DataFrame indexed by date (level 0) and asset (level 1), containing the values for a single alpha factor, forward returns for each period, the factor quantile/bin that factor value belongs to, and (optionally) the group the asset belongs to. - See full explanation in utils.get_clean_factor_and_forward_returns
- by_datebool
If True, compute quantile bucket returns separately for each date.
- by_groupbool
If True, compute quantile bucket returns separately for each group.
- demeanedbool
Compute demeaned mean returns (long short portfolio)
- group_adjustbool
Returns demeaning will occur on the group level.
- Returns
- mean_retpd.DataFrame
Mean period wise returns by specified factor quantile.
- std_error_retpd.DataFrame
Standard error of returns by specified quantile.
-
alphalens.performance.
positions
(weights, period, freq=None)¶ Builds net position values time series, the portfolio percentage invested in each position.
- Parameters
- weights: pd.Series
pd.Series containing factor weights, the index contains timestamps at which the trades are computed and the values correspond to assets weights - see factor_weights for more details
- period: pandas.Timedelta or string
Assets holding period (1 day, 2 mins, 3 hours etc). It can be a Timedelta or a string in the format accepted by Timedelta constructor (‘1 days’, ‘1D’, ‘30m’, ‘3h’, ‘1D1h’, etc)
- freqpandas DateOffset, optional
Used to specify a particular trading calendar. If not present weights.index.freq will be used
- Returns
- pd.DataFrame
Assets positions series, datetime on index, assets on columns. Example:
index ‘AAPL’ ‘MSFT’ cash 2004-01-09 10:30:00 13939.3800 -14012.9930 711.5585 2004-01-09 15:30:00 0.00 -16012.9930 411.5585 2004-01-12 10:30:00 14492.6300 -14624.8700 0.0 2004-01-12 15:30:00 14874.5400 -15841.2500 0.0 2004-01-13 10:30:00 -13853.2800 13653.6400 -43.6375
-
alphalens.performance.
quantile_turnover
(quantile_factor, quantile, period=1)¶ Computes the proportion of names in a factor quantile that were not in that quantile in the previous period.
- Parameters
- quantile_factorpd.Series
DataFrame with date, asset and factor quantile.
- quantileint
Quantile on which to perform turnover analysis.
- period: int, optional
Number of days over which to calculate the turnover.
- Returns
- quant_turnoverpd.Series
Period by period turnover for that quantile.
Plotting Functions¶
The module alphalens.plotting
facilitates the visualization of performance metrics.
-
alphalens.plotting.
customize
(func)¶ Decorator to set plotting context and axes style during function call.
-
alphalens.plotting.
plot_cumulative_returns
(factor_returns, period, freq=None, title=None, ax=None)¶ Plots the cumulative returns of the returns series passed in.
- Parameters
- factor_returnspd.Series
Period wise returns of dollar neutral portfolio weighted by factor value.
- periodpandas.Timedelta or string
Length of period for which the returns are computed (e.g. 1 day) if ‘period’ is a string it must follow pandas.Timedelta constructor format (e.g. ‘1 days’, ‘1D’, ‘30m’, ‘3h’, ‘1D1h’, etc)
- freqpandas DateOffset
Used to specify a particular trading calendar e.g. BusinessDay or Day Usually this is inferred from utils.infer_trading_calendar, which is called by either get_clean_factor_and_forward_returns or compute_forward_returns
- title: string, optional
Custom title
- axmatplotlib.Axes, optional
Axes upon which to plot.
- Returns
- axmatplotlib.Axes
The axes that were plotted on.
-
alphalens.plotting.
plot_cumulative_returns_by_quantile
(quantile_returns, period, freq=None, ax=None)¶ Plots the cumulative returns of various factor quantiles.
- Parameters
- quantile_returnspd.DataFrame
Returns by factor quantile
- periodpandas.Timedelta or string
Length of period for which the returns are computed (e.g. 1 day) if ‘period’ is a string it must follow pandas.Timedelta constructor format (e.g. ‘1 days’, ‘1D’, ‘30m’, ‘3h’, ‘1D1h’, etc)
- freqpandas DateOffset
Used to specify a particular trading calendar e.g. BusinessDay or Day Usually this is inferred from utils.infer_trading_calendar, which is called by either get_clean_factor_and_forward_returns or compute_forward_returns
- axmatplotlib.Axes, optional
Axes upon which to plot.
- Returns
- axmatplotlib.Axes
-
alphalens.plotting.
plot_events_distribution
(events, num_bars=50, ax=None)¶ Plots the distribution of events in time.
- Parameters
- eventspd.Series
A pd.Series whose index contains at least ‘date’ level.
- num_barsinteger, optional
Number of bars to plot
- axmatplotlib.Axes, optional
Axes upon which to plot.
- Returns
- axmatplotlib.Axes
-
alphalens.plotting.
plot_factor_rank_auto_correlation
(factor_autocorrelation, period=1, ax=None)¶ Plots factor rank autocorrelation over time. See factor_rank_autocorrelation for more details.
- Parameters
- factor_autocorrelationpd.Series
Rolling 1 period (defined by time_rule) autocorrelation of factor values.
- period: int, optional
Period over which the autocorrelation is calculated
- axmatplotlib.Axes, optional
Axes upon which to plot.
- Returns
- axmatplotlib.Axes
The axes that were plotted on.
-
alphalens.plotting.
plot_ic_by_group
(ic_group, ax=None)¶ Plots Spearman Rank Information Coefficient for a given factor over provided forward returns. Separates by group.
- Parameters
- ic_grouppd.DataFrame
group-wise mean period wise returns.
- axmatplotlib.Axes, optional
Axes upon which to plot.
- Returns
- axmatplotlib.Axes
The axes that were plotted on.
-
alphalens.plotting.
plot_ic_hist
(ic, ax=None)¶ Plots Spearman Rank Information Coefficient histogram for a given factor.
- Parameters
- icpd.DataFrame
DataFrame indexed by date, with IC for each forward return.
- axmatplotlib.Axes, optional
Axes upon which to plot.
- Returns
- axmatplotlib.Axes
The axes that were plotted on.
-
alphalens.plotting.
plot_ic_qq
(ic, theoretical_dist=<scipy.stats._continuous_distns.norm_gen object>, ax=None)¶ Plots Spearman Rank Information Coefficient “Q-Q” plot relative to a theoretical distribution.
- Parameters
- icpd.DataFrame
DataFrame indexed by date, with IC for each forward return.
- theoretical_distscipy.stats._continuous_distns
Continuous distribution generator. scipy.stats.norm and scipy.stats.t are popular options.
- axmatplotlib.Axes, optional
Axes upon which to plot.
- Returns
- axmatplotlib.Axes
The axes that were plotted on.
-
alphalens.plotting.
plot_ic_ts
(ic, ax=None)¶ Plots Spearman Rank Information Coefficient and IC moving average for a given factor.
- Parameters
- icpd.DataFrame
DataFrame indexed by date, with IC for each forward return.
- axmatplotlib.Axes, optional
Axes upon which to plot.
- Returns
- axmatplotlib.Axes
The axes that were plotted on.
-
alphalens.plotting.
plot_information_table
(ic_data)¶
-
alphalens.plotting.
plot_mean_quantile_returns_spread_time_series
(mean_returns_spread, std_err=None, bandwidth=1, ax=None)¶ Plots mean period wise returns for factor quantiles.
- Parameters
- mean_returns_spreadpd.Series
Series with difference between quantile mean returns by period.
- std_errpd.Series
Series with standard error of difference between quantile mean returns each period.
- bandwidthfloat
Width of displayed error bands in standard deviations.
- axmatplotlib.Axes, optional
Axes upon which to plot.
- Returns
- axmatplotlib.Axes
The axes that were plotted on.
-
alphalens.plotting.
plot_monthly_ic_heatmap
(mean_monthly_ic, ax=None)¶ Plots a heatmap of the information coefficient or returns by month.
- Parameters
- mean_monthly_icpd.DataFrame
The mean monthly IC for N periods forward.
- Returns
- axmatplotlib.Axes
The axes that were plotted on.
-
alphalens.plotting.
plot_quantile_average_cumulative_return
(avg_cumulative_returns, by_quantile=False, std_bar=False, title=None, ax=None)¶ Plots sector-wise mean daily returns for factor quantiles across provided forward price movement columns.
- Parameters
- avg_cumulative_returns: pd.Dataframe
The format is the one returned by performance.average_cumulative_return_by_quantile
- by_quantileboolean, optional
Disaggregated figures by quantile (useful to clearly see std dev bars)
- std_barboolean, optional
Plot standard deviation plot
- title: string, optional
Custom title
- axmatplotlib.Axes, optional
Axes upon which to plot.
- Returns
- axmatplotlib.Axes
-
alphalens.plotting.
plot_quantile_returns_bar
(mean_ret_by_q, by_group=False, ylim_percentiles=None, ax=None)¶ Plots mean period wise returns for factor quantiles.
- Parameters
- mean_ret_by_qpd.DataFrame
DataFrame with quantile, (group) and mean period wise return values.
- by_groupbool
Disaggregated figures by group.
- ylim_percentilestuple of integers
Percentiles of observed data to use as y limits for plot.
- axmatplotlib.Axes, optional
Axes upon which to plot.
- Returns
- axmatplotlib.Axes
The axes that were plotted on.
-
alphalens.plotting.
plot_quantile_returns_violin
(return_by_q, ylim_percentiles=None, ax=None)¶ Plots a violin box plot of period wise returns for factor quantiles.
- Parameters
- return_by_qpd.DataFrame - MultiIndex
DataFrame with date and quantile as rows MultiIndex, forward return windows as columns, returns as values.
- ylim_percentilestuple of integers
Percentiles of observed data to use as y limits for plot.
- axmatplotlib.Axes, optional
Axes upon which to plot.
- Returns
- axmatplotlib.Axes
The axes that were plotted on.
-
alphalens.plotting.
plot_quantile_statistics_table
(factor_data)¶
-
alphalens.plotting.
plot_returns_table
(alpha_beta, mean_ret_quantile, mean_ret_spread_quantile)¶
-
alphalens.plotting.
plot_top_bottom_quantile_turnover
(quantile_turnover, period=1, ax=None)¶ Plots period wise top and bottom quantile factor turnover.
- Parameters
- quantile_turnover: pd.Dataframe
Quantile turnover (each DataFrame column a quantile).
- period: int, optional
Period over which to calculate the turnover.
- axmatplotlib.Axes, optional
Axes upon which to plot.
- Returns
- axmatplotlib.Axes
The axes that were plotted on.
-
alphalens.plotting.
plot_turnover_table
(autocorrelation_data, quantile_turnover)¶
Utilities¶
The module alphalens.utils
contains helper functions, e.g. to format factor data into the requisite input format.
-
exception
alphalens.utils.
MaxLossExceededError
¶ Bases:
Exception
-
exception
alphalens.utils.
NonMatchingTimezoneError
¶ Bases:
Exception
-
alphalens.utils.
add_custom_calendar_timedelta
(input, timedelta, freq)¶ Add timedelta to ‘input’ taking into consideration custom frequency, which is used to deal with custom calendars, such as a trading calendar
- Parameters
- inputpd.DatetimeIndex or pd.Timestamp
- timedeltapd.Timedelta
- freqpd.DataOffset (CustomBusinessDay, Day or BusinessDay)
- Returns
- pd.DatetimeIndex or pd.Timestamp
input + timedelta
-
alphalens.utils.
backshift_returns_series
(series, N)¶ Shift a multi-indexed series backwards by N observations in the first level.
This can be used to convert backward-looking returns into a forward-returns series.
-
alphalens.utils.
compute_forward_returns
(factor, prices, periods=(1, 5, 10), filter_zscore=None, cumulative_returns=True)¶ Finds the N period forward returns (as percent change) for each asset provided.
- Parameters
- factorpd.Series - MultiIndex
A MultiIndex Series indexed by timestamp (level 0) and asset (level 1), containing the values for a single alpha factor.
See full explanation in utils.get_clean_factor_and_forward_returns
- pricespd.DataFrame
Pricing data to use in forward price calculation. Assets as columns, dates as index. Pricing data must span the factor analysis time period plus an additional buffer window that is greater than the maximum number of expected periods in the forward returns calculations.
- periodssequence[int]
periods to compute forward returns on.
- filter_zscoreint or float, optional
Sets forward returns greater than X standard deviations from the the mean to nan. Set it to ‘None’ to avoid filtering. Caution: this outlier filtering incorporates lookahead bias.
- cumulative_returnsbool, optional
If True, forward returns columns will contain cumulative returns. Setting this to False is useful if you want to analyze how predictive a factor is for a single forward day.
- Returns
- forward_returnspd.DataFrame - MultiIndex
A MultiIndex DataFrame indexed by timestamp (level 0) and asset (level 1), containing the forward returns for assets. Forward returns column names follow the format accepted by pd.Timedelta (e.g. ‘1D’, ‘30m’, ‘3h15m’, ‘1D1h’, etc). ‘date’ index freq property (forward_returns.index.levels[0].freq) will be set to a trading calendar (pandas DateOffset) inferred from the input data (see infer_trading_calendar for more details).
-
alphalens.utils.
demean_forward_returns
(factor_data, grouper=None)¶ Convert forward returns to returns relative to mean period wise all-universe or group returns. group-wise normalization incorporates the assumption of a group neutral portfolio constraint and thus allows allows the factor to be evaluated across groups.
For example, if AAPL 5 period return is 0.1% and mean 5 period return for the Technology stocks in our universe was 0.5% in the same period, the group adjusted 5 period return for AAPL in this period is -0.4%.
- Parameters
- factor_datapd.DataFrame - MultiIndex
Forward returns indexed by date and asset. Separate column for each forward return window.
- grouperlist
If True, demean according to group.
- Returns
- adjusted_forward_returnspd.DataFrame - MultiIndex
DataFrame of the same format as the input, but with each security’s returns normalized by group.
-
alphalens.utils.
diff_custom_calendar_timedeltas
(start, end, freq)¶ Compute the difference between two pd.Timedelta taking into consideration custom frequency, which is used to deal with custom calendars, such as a trading calendar
- Parameters
- startpd.Timestamp
- endpd.Timestamp
- freqCustomBusinessDay (see infer_trading_calendar)
- freqpd.DataOffset (CustomBusinessDay, Day or BDay)
- Returns
- pd.Timedelta
end - start
-
alphalens.utils.
get_clean_factor
(factor, forward_returns, groupby=None, binning_by_group=False, quantiles=5, bins=None, groupby_labels=None, max_loss=0.35, zero_aware=False)¶ Formats the factor data, forward return data, and group mappings into a DataFrame that contains aligned MultiIndex indices of timestamp and asset. The returned data will be formatted to be suitable for Alphalens functions.
It is safe to skip a call to this function and still make use of Alphalens functionalities as long as the factor data conforms to the format returned from get_clean_factor_and_forward_returns and documented here
- Parameters
- factorpd.Series - MultiIndex
A MultiIndex Series indexed by timestamp (level 0) and asset (level 1), containing the values for a single alpha factor.
----------------------------------- date | asset | ----------------------------------- | AAPL | 0.5 ----------------------- | BA | -1.1 ----------------------- 2014-01-01 | CMG | 1.7 ----------------------- | DAL | -0.1 ----------------------- | LULU | 2.7 -----------------------
- forward_returnspd.DataFrame - MultiIndex
A MultiIndex DataFrame indexed by timestamp (level 0) and asset (level 1), containing the forward returns for assets. Forward returns column names must follow the format accepted by pd.Timedelta (e.g. ‘1D’, ‘30m’, ‘3h15m’, ‘1D1h’, etc). ‘date’ index freq property must be set to a trading calendar (pandas DateOffset), see infer_trading_calendar for more details. This information is currently used only in cumulative returns computation
--------------------------------------- | | 1D | 5D | 10D --------------------------------------- date | asset | | | --------------------------------------- | AAPL | 0.09|-0.01|-0.079 ---------------------------- | BA | 0.02| 0.06| 0.020 ---------------------------- 2014-01-01 | CMG | 0.03| 0.09| 0.036 ---------------------------- | DAL |-0.02|-0.06|-0.029 ---------------------------- | LULU |-0.03| 0.05|-0.009 ----------------------------
- groupbypd.Series - MultiIndex or dict
Either A MultiIndex Series indexed by date and asset, containing the period wise group codes for each asset, or a dict of asset to group mappings. If a dict is passed, it is assumed that group mappings are unchanged for the entire time period of the passed factor data.
- binning_by_groupbool
If True, compute quantile buckets separately for each group. This is useful when the factor values range vary considerably across gorups so that it is wise to make the binning group relative. You should probably enable this if the factor is intended to be analyzed for a group neutral portfolio
- quantilesint or sequence[float]
Number of equal-sized quantile buckets to use in factor bucketing. Alternately sequence of quantiles, allowing non-equal-sized buckets e.g. [0, .10, .5, .90, 1.] or [.05, .5, .95] Only one of ‘quantiles’ or ‘bins’ can be not-None
- binsint or sequence[float]
Number of equal-width (valuewise) bins to use in factor bucketing. Alternately sequence of bin edges allowing for non-uniform bin width e.g. [-4, -2, -0.5, 0, 10] Chooses the buckets to be evenly spaced according to the values themselves. Useful when the factor contains discrete values. Only one of ‘quantiles’ or ‘bins’ can be not-None
- groupby_labelsdict
A dictionary keyed by group code with values corresponding to the display name for each group.
- max_lossfloat, optional
Maximum percentage (0.00 to 1.00) of factor data dropping allowed, computed comparing the number of items in the input factor index and the number of items in the output DataFrame index. Factor data can be partially dropped due to being flawed itself (e.g. NaNs), not having provided enough price data to compute forward returns for all factor values, or because it is not possible to perform binning. Set max_loss=0 to avoid Exceptions suppression.
- zero_awarebool, optional
If True, compute quantile buckets separately for positive and negative signal values. This is useful if your signal is centered and zero is the separation between long and short signals, respectively. ‘quantiles’ is None.
- Returns
- merged_datapd.DataFrame - MultiIndex
A MultiIndex Series indexed by date (level 0) and asset (level 1), containing the values for a single alpha factor, forward returns for each period, the factor quantile/bin that factor value belongs to, and (optionally) the group the asset belongs to.
forward returns column names follow the format accepted by pd.Timedelta (e.g. ‘1D’, ‘30m’, ‘3h15m’, ‘1D1h’, etc)
‘date’ index freq property (merged_data.index.levels[0].freq) is the same as that of the input forward returns data. This is currently used only in cumulative returns computation
-
alphalens.utils.
get_clean_factor_and_forward_returns
(factor, prices, groupby=None, binning_by_group=False, quantiles=5, bins=None, periods=(1, 5, 10), filter_zscore=20, groupby_labels=None, max_loss=0.35, zero_aware=False, cumulative_returns=True)¶ Formats the factor data, pricing data, and group mappings into a DataFrame that contains aligned MultiIndex indices of timestamp and asset. The returned data will be formatted to be suitable for Alphalens functions.
It is safe to skip a call to this function and still make use of Alphalens functionalities as long as the factor data conforms to the format returned from get_clean_factor_and_forward_returns and documented here
- Parameters
- factorpd.Series - MultiIndex
A MultiIndex Series indexed by timestamp (level 0) and asset (level 1), containing the values for a single alpha factor.
----------------------------------- date | asset | ----------------------------------- | AAPL | 0.5 ----------------------- | BA | -1.1 ----------------------- 2014-01-01 | CMG | 1.7 ----------------------- | DAL | -0.1 ----------------------- | LULU | 2.7 -----------------------
- pricespd.DataFrame
A wide form Pandas DataFrame indexed by timestamp with assets in the columns. Pricing data must span the factor analysis time period plus an additional buffer window that is greater than the maximum number of expected periods in the forward returns calculations. It is important to pass the correct pricing data in depending on what time of period your signal was generated so to avoid lookahead bias, or delayed calculations. ‘Prices’ must contain at least an entry for each timestamp/asset combination in ‘factor’. This entry should reflect the buy price for the assets and usually it is the next available price after the factor is computed but it can also be a later price if the factor is meant to be traded later (e.g. if the factor is computed at market open but traded 1 hour after market open the price information should be 1 hour after market open). ‘Prices’ must also contain entries for timestamps following each timestamp/asset combination in ‘factor’, as many more timestamps as the maximum value in ‘periods’. The asset price after ‘period’ timestamps will be considered the sell price for that asset when computing ‘period’ forward returns.
---------------------------------------------------- | AAPL | BA | CMG | DAL | LULU | ---------------------------------------------------- Date | | | | | | ---------------------------------------------------- 2014-01-01 |605.12| 24.58| 11.72| 54.43 | 37.14 | ---------------------------------------------------- 2014-01-02 |604.35| 22.23| 12.21| 52.78 | 33.63 | ---------------------------------------------------- 2014-01-03 |607.94| 21.68| 14.36| 53.94 | 29.37 | ----------------------------------------------------
- groupbypd.Series - MultiIndex or dict
Either A MultiIndex Series indexed by date and asset, containing the period wise group codes for each asset, or a dict of asset to group mappings. If a dict is passed, it is assumed that group mappings are unchanged for the entire time period of the passed factor data.
- binning_by_groupbool
If True, compute quantile buckets separately for each group. This is useful when the factor values range vary considerably across gorups so that it is wise to make the binning group relative. You should probably enable this if the factor is intended to be analyzed for a group neutral portfolio
- quantilesint or sequence[float]
Number of equal-sized quantile buckets to use in factor bucketing. Alternately sequence of quantiles, allowing non-equal-sized buckets e.g. [0, .10, .5, .90, 1.] or [.05, .5, .95] Only one of ‘quantiles’ or ‘bins’ can be not-None
- binsint or sequence[float]
Number of equal-width (valuewise) bins to use in factor bucketing. Alternately sequence of bin edges allowing for non-uniform bin width e.g. [-4, -2, -0.5, 0, 10] Chooses the buckets to be evenly spaced according to the values themselves. Useful when the factor contains discrete values. Only one of ‘quantiles’ or ‘bins’ can be not-None
- periodssequence[int]
periods to compute forward returns on.
- filter_zscoreint or float, optional
Sets forward returns greater than X standard deviations from the the mean to nan. Set it to ‘None’ to avoid filtering. Caution: this outlier filtering incorporates lookahead bias.
- groupby_labelsdict
A dictionary keyed by group code with values corresponding to the display name for each group.
- max_lossfloat, optional
Maximum percentage (0.00 to 1.00) of factor data dropping allowed, computed comparing the number of items in the input factor index and the number of items in the output DataFrame index. Factor data can be partially dropped due to being flawed itself (e.g. NaNs), not having provided enough price data to compute forward returns for all factor values, or because it is not possible to perform binning. Set max_loss=0 to avoid Exceptions suppression.
- zero_awarebool, optional
If True, compute quantile buckets separately for positive and negative signal values. This is useful if your signal is centered and zero is the separation between long and short signals, respectively.
- cumulative_returnsbool, optional
If True, forward returns columns will contain cumulative returns. Setting this to False is useful if you want to analyze how predictive a factor is for a single forward day.
- Returns
- merged_datapd.DataFrame - MultiIndex
A MultiIndex Series indexed by date (level 0) and asset (level 1), containing the values for a single alpha factor, forward returns for each period, the factor quantile/bin that factor value belongs to, and (optionally) the group the asset belongs to. - forward returns column names follow the format accepted by
pd.Timedelta (e.g. ‘1D’, ‘30m’, ‘3h15m’, ‘1D1h’, etc)
‘date’ index freq property (merged_data.index.levels[0].freq) will be set to a trading calendar (pandas DateOffset) inferred from the input data (see infer_trading_calendar for more details). This is currently used only in cumulative returns computation
See also
utils.get_clean_factor
For use when forward returns are already available.
-
alphalens.utils.
get_forward_returns_columns
(columns, require_exact_day_multiple=False)¶ Utility that detects and returns the columns that are forward returns
-
alphalens.utils.
infer_trading_calendar
(factor_idx, prices_idx)¶ Infer the trading calendar from factor and price information.
- Parameters
- factor_idxpd.DatetimeIndex
The factor datetimes for which we are computing the forward returns
- prices_idxpd.DatetimeIndex
The prices datetimes associated withthe factor data
- Returns
- calendarpd.DateOffset
-
alphalens.utils.
non_unique_bin_edges_error
(func)¶ Give user a more informative error in case it is not possible to properly calculate quantiles on the input dataframe (factor)
-
alphalens.utils.
print_table
(table, name=None, fmt=None)¶ Pretty print a pandas DataFrame.
Uses HTML output if running inside Jupyter Notebook, otherwise formatted text output.
- Parameters
- tablepd.Series or pd.DataFrame
Table to pretty-print.
- namestr, optional
Table name to display in upper left corner.
- fmtstr, optional
Formatter to use for displaying table elements. E.g. ‘{0:.2f}%’ for displaying 100 as ‘100.00%’. Restores original setting after displaying.
-
alphalens.utils.
quantize_factor
(*args, **kwargs)¶
-
alphalens.utils.
rate_of_return
(period_ret, base_period)¶ Convert returns to ‘one_period_len’ rate of returns: that is the value the returns would have every ‘one_period_len’ if they had grown at a steady rate
- Parameters
- period_ret: pd.DataFrame
DataFrame containing returns values with column headings representing the return period.
- base_period: string
The base period length used in the conversion It must follow pandas.Timedelta constructor format (e.g. ‘1 days’, ‘1D’, ‘30m’, ‘3h’, ‘1D1h’, etc)
- Returns
- pd.DataFrame
DataFrame in same format as input but with ‘one_period_len’ rate of returns values.
-
alphalens.utils.
rethrow
(exception, additional_message)¶ Re-raise the last exception that was active in the current scope without losing the stacktrace but adding an additional message. This is hacky because it has to be compatible with both python 2/3
-
alphalens.utils.
std_conversion
(period_std, base_period)¶ one_period_len standard deviation (or standard error) approximation
- Parameters
- period_std: pd.DataFrame
DataFrame containing standard deviation or standard error values with column headings representing the return period.
- base_period: string
The base period length used in the conversion It must follow pandas.Timedelta constructor format (e.g. ‘1 days’, ‘1D’, ‘30m’, ‘3h’, ‘1D1h’, etc)
- Returns
- pd.DataFrame
DataFrame in same format as input but with one-period standard deviation/error values.
-
alphalens.utils.
timedelta_strings_to_integers
(sequence)¶ Converts pandas string representations of timedeltas into integers of days.
- Parameters
- sequenceiterable
List or array of timedelta string representations, e.g. [‘1D’, ‘5D’].
- Returns
- sequencelist
Integer days corresponding to the input sequence, e.g. [1, 5].
-
alphalens.utils.
timedelta_to_string
(timedelta)¶ Utility that converts a pandas.Timedelta to a string representation compatible with pandas.Timedelta constructor format
- Parameters
- timedelta: pd.Timedelta
- Returns
- string
string representation of ‘timedelta’