portfolios.compute_long_short_returns()

Compute long-short returns.

Usage

Source

portfolios.compute_long_short_returns(
    data, direction="top_minus_bottom", data_options=None
)

Calculates long-short returns based on the returns of portfolios. The long-short return is computed as the difference between the returns of the ‘top’ and ‘bottom’ portfolios. The direction of the calculation can be adjusted based on whether the return from the ‘bottom’ portfolio is subtracted from or added to the return from the ‘top’ portfolio.

Parameters

data: pl.DataFrame

Data frame containing portfolio returns. Must include columns for the portfolio identifier, date, and return measurements (as specified in ‘data_options’).

direction: str = "top_minus_bottom"

Direction of the long-short return calculation. Must be either ‘top_minus_bottom’ or ‘bottom_minus_top’. If set to ‘bottom_minus_top’, the return is computed as (bottom - top).

data_options: dict = None
Column-name mapping (see ‘data_options’). The ‘date’ element specifies the date column, the ‘ret_excess’ element specifies the excess return column, and ‘portfolio’ specifies the assigned portfolio. Uses the ‘data_options’ defaults when None: ‘date’ -> ‘date’, ‘ret_excess’ -> ‘ret_excess’, and ‘portfolio’ -> ‘portfolio’.

Returns

pl.DataFrame
Data frame with columns for date and the computed long-short returns. The data frame is arranged by date and pivoted to have return measurement types as columns with their corresponding long-short returns.

Examples

import datetime as dt
import numpy as np
import polars as pl
from tidyfinance import (
    compute_portfolio_returns,
    compute_long_short_returns,
    breakpoint_options,
)
rng = np.random.default_rng(42)
dates = pl.date_range(
    dt.date(2020, 1, 1), dt.date(2028, 4, 1), '1mo', eager=True
)
data = pl.DataFrame({
    'permno': range(1, 101),
    'date': dates,
    'mktcap_lag': rng.uniform(100, 1000, 100),
    'ret_excess': rng.standard_normal(100),
    'size': rng.uniform(50, 150, 100),
})
portfolio_returns = compute_portfolio_returns(
    data, 'size', 'univariate',
    breakpoint_options_main=breakpoint_options(n_portfolios=5),
)
compute_long_short_returns(portfolio_returns)