Factor Portfolios

Calculate the returns of portfolios sorted on a ratio: how the tickers with the lowest values of the ratio performed against those with the highest, period by period, as in the portfolio sorts of Fama and French.

At the end of every rebalancing period the tickers are sorted into quantiles of the ratio by percentile breakpoints, held over the following holding_period periods and weighted equally or by their market cap. The Top Minus Bottom spread is long the highest quantile and short the lowest, so a ratio whose low values do better (such as a low P/E) gives a negative spread. Next to the returns per period, detail gives whether the spread differs from zero (Newey-West t-statistic) with its Sharpe ratio, whether the returns rise or fall across every quantile (Patton and Timmermann’s monotonic relation test), the turnover of each quantile and the weights of the tickers.

The formula is as follows:

\[\text{Breakpoints:}\;\; \text{the} \;\frac{1}{n},\; \ldots,\; \frac{n - 1}{n \;\text{percentiles of the ratio of the tickers at the end of period}\; s}\] \[\text{Equal weight:}\;\; w(i,\; t) = \frac{1}{N(q,\; t)};\;\; \text{value weight:}\;\; w(i,\; t) = \frac{\operatorname{ME}(i,\; t - 1)}{\Sigma_{j} \;\text{ME}(j,\; t - 1)}\] \[R(q,\; t) = \Sigma_{i} w(i,\; t) \cdot R(i,\; t) \;\text{over the tickers}\; i \;\text{in quantile}\; q,\;\; \text{for the periods } t \text{ after } s \text{ up to the next rebalancing}\] \[\text{Top Minus Bottom}(t) = R(n,\; t) - R(1,\; t)\] \[\text{t-Statistic} = \frac{\text{mean}}{\sqrt{\frac{S}{T}}},\;\; \text{with } S \text{ the Newey-West long-run variance (Bartlett weights)}\] \[\text{Sharpe Ratio} = \frac{\text{mean}}{\text{standard deviation}} \cdot \sqrt{\text{periods per year}}\] \[\text{Monotonic relation test:}\;\; J = \min_{k} (\text{mean} \;R(k + 1) - \text{mean} \;R(k)),\;\; \text{its p-value from a stationary bootstrap}\] \[\operatorname{Turnover}(q,\; t) = \frac{1}{2} \cdot \Sigma_{i} \left|w(i,\; t) - \tilde{w}(i,\; t - 1)\right|,\;\; \text{with } w \text{̃ the previous weights drifted by the returns}\]

The ratios are calculated daily from the closing price where they can be (daily values) and otherwise per statement period. Statement figures apply from the end of each fiscal period, or with point-in-time data from the day they were filed, and the ratio at the end of a period sorts the returns of the periods after it, so no return uses figures that were not known yet. The returns use the dividend and split adjusted close, the market caps the traded close at the end of the previous period. A ticker without a ratio is left out of that sort, and one without a return out of that period.

Example · AAPL, MSFT, GOOGL, AMZN, 12 more · 2016 to 2025

Install the Finance Toolkit with pip install financetoolkit -U, then call get_factor_portfolios:

from financetoolkit import Toolkit

toolkit = Toolkit(
    ["AAPL", "MSFT", "GOOGL", "AMZN", "META", "NVDA", "JPM", "JNJ",
     "XOM", "PG", "KO", "WMT", "V", "UNH", "HD", "CVX"],
    api_key="FINANCIAL_MODELING_PREP_KEY",
    start_date="2016-01-01",
    end_date="2025-12-31",
)

toolkit.ratios.get_factor_portfolios(
    "get_price_to_book_ratio",
    quantiles=4,
    detail="statistics",
    show_columns=["Annualized Mean Return", "t-Statistic", "P-Value", "Sharpe Ratio", "Mean Turnover"],
)

Or, with the Finance Toolkit MCP set up, ask an AI assistant such as Claude or ChatGPT:

How did quartile portfolios sorted on the price to book ratio of Apple, Microsoft, Alphabet, Amazon, Meta, Nvidia, JPMorgan Chase, Johnson & Johnson, Exxon Mobil, Procter & Gamble, Coca-Cola, Walmart, Visa, UnitedHealth, Home Depot and Chevron perform from 2016 to 2025, and was the spread between the highest and lowest quartile significant?

Which returns:

Parameters

get_factor_portfolios accepts the following parameters.

ParameterTypeDescriptionExample
metricstrThe ratio method to sort on, e.g. “get_price_to_book_ratio”. Defaults to “get_price_to_earnings_ratio”."get_price_to_earnings_ratio"
periodstrThe frequency of the returns and of the sorts. Options are: “weekly” (weekly returns), “monthly” (monthly returns), “quarterly” (quarterly returns), “yearly” (yearly returns). Defaults to “monthly”."weekly"
quantilesint | NoneThe number of quantile portfolios, at most the number of tickers. Defaults to None, which uses 5 or the number of tickers when there are fewer.[0.05, 0.5, 0.95]
weightingstrHow the tickers within a quantile are weighted. Options are: “equal” (equally, rebalanced every period), “value” (by market cap at the end of the previous period). Defaults to “equal”."equal"
holding_periodintThe number of periods a sort is held before the next, e.g. 12 with monthly returns for yearly rebalancing. Defaults to 1.1
detailstr | NoneReturns another part instead of the returns per period. Options are: “statistics” (the mean return, Newey-West t-statistic, p-value, Sharpe ratio and mean turnover of each quantile and the spread), “monotonicity” (the monotonic relation tests and the Spearman rank correlation of the quantiles’ mean returns), “turnover” (the turnover per period and quantile), “weights” (the weight per period, quantile and ticker). Defaults to None.None
roundingint | NoneThe number of decimals to round the results to. Defaults to None, which uses the Toolkit’s rounding.2
show_columnsstr | list[str] | NoneThe columns to keep, a name or a list of names, matched on every column level, or the rows when no column has those names (such as the line items of a financial statement). Names that do not exist are logged, and when none exist the result is returned in full. Defaults to None, which keeps every column. **kwargs: Parameters passed to the ratio, e.g. trailing=4 or diluted=False.

References

  • Paper Fama, E.F. and French, K.R. (1992). “The Cross-Section of Expected Stock Returns.” Journal of Finance, 47(2), 427-465, for the sorts.
  • Paper Fama, E.F. and French, K.R. (1993). “Common Risk Factors in the Returns on Stocks and Bonds.” Journal of Financial Economics, 33(1), 3-56, for the value weights and the long-short spread.
  • Paper Jegadeesh, N. and Titman, S. (1993). “Returns to Buying Winners and Selling Losers: Implications for Stock Market Efficiency.” Journal of Finance, 48(1), 65-91, for the holding periods.
  • Paper Newey, W.K. and West, K.D. (1987). “A Simple, Positive Semi-Definite, Heteroskedasticity and Autocorrelation Consistent Covariance Matrix.” Econometrica, 55(3), 703-708.
  • Paper Patton, A.J. and Timmermann, A. (2010). “Monotonicity in Asset Returns: New Tests with Applications to the Term Structure, the CAPM, and Portfolio Sorts.” Journal of Financial Economics, 98(3), 605-625.
  • Paper DeMiguel, V., Garlappi, L. and Uppal, R. (2009). “Optimal Versus Naive Diversification: How Inefficient is the 1/N Portfolio Strategy?” Review of Financial Studies, 22(5), 1915-1953, for the turnover.
  • Library Referenced against statsmodels’ OLS with HAC covariance
  • Library Shares similar logic as alphalens’ quantize_factor
  • Library Shares similar logic as alphalens’ mean_return_by_quantile
  • Library Shares similar logic as alphalens’ quantile_turnover
  • Library Shares similar logic as arch’s StationaryBootstrap
Share