Finance API
Returns
price_returns
price_returns
Compute simple or logarithmic returns while preserving time alignment.
Parameters
prices:
One price series or a matrix whose rows are ordered observations and
whose columns are assets.
periods:
Number of observations between consecutive prices.
method:
"log" for log returns or "simple" for arithmetic returns.
Returns
Same container type as prices when a pandas Series/DataFrame is used;
otherwise a NumPy array. The first periods observations are NaN.
Source code in src/capacities_ml_fin/finance/returns.py
to_losses
to_losses
Convert returns to losses using loss = -return.
Parameters
returns : array-like Return series or panel.
Returns
ndarray, Series, or DataFrame Negated values with the original container and labels preserved.
Source code in src/capacities_ml_fin/finance/returns.py
aggregate_returns
Trailing historical return aggregation.
aggregate_returns
Aggregate returns over a trailing historical horizon.
Parameters
returns : array-like Equally spaced return observations ordered through time. horizon : int Positive number of observations in each trailing window. method : {"log", "simple"}, default="log" Sum log returns or compound simple returns.
Returns
ndarray, Series, or DataFrame
Trailing returns aligned at each window end. The first
horizon - 1 rows are missing.
Notes
The value at time t contains no observation after t.
Source code in src/capacities_ml_fin/finance/returns.py
forward_returns
Forward supervised target construction.
forward_returns
Construct forward aggregate-return targets.
Parameters
returns : array-like Equally spaced returns ordered through time. horizon : int Number of future observations in each target. method : {"log", "simple"}, default="log" Sum log returns or compound simple returns.
Returns
ndarray, Series, or DataFrame
Target at t formed from t + 1 through t + horizon.
The final horizon rows are missing.
Notes
These values are supervised targets and must not be included among
predictors available at time t.
Source code in src/capacities_ml_fin/finance/returns.py
forward_losses
forward_losses
Construct forward losses as negative forward aggregate returns.
Parameters
returns : array-like Return observations ordered through time. horizon : int Number of future observations per target. method : {"log", "simple"}, default="log" Return aggregation convention.
Returns
ndarray, Series, or DataFrame
Forward targets under the loss = -return convention.
Source code in src/capacities_ml_fin/finance/returns.py
excess_returns
excess_returns
Subtract an aligned risk-free return from asset returns.
Parameters
returns : array-like Asset returns. risk_free : float or array-like Scalar or aligned risk-free returns.
Returns
ndarray, Series, or DataFrame Arithmetic excess returns with pandas labels aligned when present.
Source code in src/capacities_ml_fin/finance/returns.py
wealth_index
wealth_index
Convert returns into a cumulative wealth index.
Parameters
returns : array-like Simple or logarithmic returns ordered through time. method : {"simple", "log"}, default="simple" Compounding convention. initial_value : float, default=1.0 Positive initial wealth.
Returns
ndarray, Series, or DataFrame Cumulative wealth with the original shape and labels.
Source code in src/capacities_ml_fin/finance/returns.py
Features
realized_volatility
realized_volatility
realized_volatility(
returns: ArrayLike,
*,
window: int = 20,
demean: bool = False,
annualize: bool = False,
periods_per_year: int = 252
)
Estimate trailing realized volatility from equally spaced returns.
Parameters
returns : array-like
Return series or panel ordered through time.
window : int, default=20
Number of observations in each trailing estimate.
demean : bool, default=False
Use the demeaned sample standard deviation when true; otherwise use
the square root of summed squared returns.
annualize : bool, default=False
Scale the window estimate to an annualized value.
periods_per_year : int, default=252
Annual frequency used when annualize=True.
Returns
ndarray, Series, or DataFrame Trailing volatility aligned at each window end.
Source code in src/capacities_ml_fin/finance/features.py
momentum
momentum
Compute trailing return momentum with an optional skip period.
Parameters
returns : array-like Return observations ordered through time. lookback : int, default=252 Total distance from the current observation to the start of the signal. skip : int, default=21 Most recent observations omitted from the signal. method : {"simple", "log"}, default="simple" Compound simple returns or sum log returns.
Returns
ndarray, Series, or DataFrame
Momentum signal based only on information at or before t - skip.
Source code in src/capacities_ml_fin/finance/features.py
drawdown
drawdown
Compute drawdown from the running maximum wealth.
Parameters
returns : array-like Return series or panel. method : {"simple", "log"}, default="simple" Return convention used to build wealth.
Returns
ndarray, Series, or DataFrame
Relative decline wealth / running_max - 1.
Source code in src/capacities_ml_fin/finance/features.py
max_drawdown
max_drawdown
Return the most negative drawdown of each return series.
Parameters
returns : array-like Return series or panel. method : {"simple", "log"}, default="simple" Return convention used to build wealth.
Returns
float or ndarray or Series Minimum drawdown for each input series.
Source code in src/capacities_ml_fin/finance/features.py
dollar_volume
dollar_volume
Compute traded dollar volume as price times volume.
Parameters
price, volume : array-like Aligned prices and traded share volumes.
Returns
ndarray, Series, or DataFrame Elementwise traded values.
Source code in src/capacities_ml_fin/finance/features.py
turnover
turnover
Compute share turnover relative to shares outstanding.
Parameters
volume : array-like Traded share volume. shares_outstanding : array-like Strictly positive aligned shares outstanding.
Returns
ndarray, Series, or DataFrame Elementwise turnover ratios.
Source code in src/capacities_ml_fin/finance/features.py
relative_bid_ask_spread
relative_bid_ask_spread
Compute the quoted bid-ask spread relative to the midpoint.
Parameters
bid, ask : array-like
Positive aligned quotes satisfying ask >= bid.
Returns
ndarray, Series, or DataFrame
(ask - bid) / ((ask + bid) / 2).
Source code in src/capacities_ml_fin/finance/features.py
amihud_illiquidity
amihud_illiquidity
Compute the Amihud absolute-return price-impact proxy.
Parameters
returns : array-like Asset returns. traded_value : array-like Strictly positive aligned dollar volumes. window : int, optional Replace point estimates with their trailing arithmetic mean.
Returns
ndarray, Series, or DataFrame
abs(return) / traded_value, optionally smoothed.
Source code in src/capacities_ml_fin/finance/features.py
Portfolio
normalize_weights
normalize_weights
Normalize static or time-varying portfolio weights to sum to one.
Parameters
weights : array-like Static one-dimensional weights or time-by-asset weights.
Returns
ndarray, Series, or DataFrame Weights normalized once for a vector or row-wise for a matrix.
Raises
ValueError If any normalization total is zero or non-finite.
Source code in src/capacities_ml_fin/finance/portfolio.py
equal_weights
equal_weights
Construct an equally weighted portfolio.
Parameters
assets : int or sequence of str Positive asset count or unique asset names.
Returns
ndarray or Series
Weights equal to 1 / n_assets; names are preserved when supplied.
Source code in src/capacities_ml_fin/finance/portfolio.py
market_cap_weights
market_cap_weights
Construct cross-sectional weights proportional to market capitalizations.
Parameters
market_caps : array-like Non-negative static or time-varying capitalizations.
Returns
ndarray, Series, or DataFrame Capitalizations normalized across assets.
Source code in src/capacities_ml_fin/finance/portfolio.py
lag_weights
lag_weights
Lag time-varying weights to prevent contemporaneous use.
Parameters
weights : DataFrame or two-dimensional array-like Time-by-asset portfolio weights. periods : int, default=1 Positive lag length.
Returns
DataFrame or ndarray Shifted weights with missing leading rows.
Source code in src/capacities_ml_fin/finance/portfolio.py
portfolio_returns
portfolio_returns
Aggregate asset returns using supplied portfolio weights.
Parameters
asset_returns : DataFrame or two-dimensional array-like Time-by-asset returns. weights : array-like Static asset weights or time-varying weights matching the return shape.
Returns
ndarray or Series One portfolio return per observation.
Notes
Weights are neither normalized nor lagged implicitly. Apply
:func:normalize_weights and :func:lag_weights explicitly when required.
DataFrame weights are aligned by asset label.
Source code in src/capacities_ml_fin/finance/portfolio.py
portfolio_losses
portfolio_losses
Aggregate portfolio returns and convert them to losses.
Parameters
asset_returns : DataFrame or two-dimensional array-like Time-by-asset returns. weights : array-like Static or time-varying portfolio weights.
Returns
ndarray or Series
Portfolio losses under the loss = -return convention.
Source code in src/capacities_ml_fin/finance/portfolio.py
Point-in-time alignment
apply_publication_lag
apply_publication_lag
apply_publication_lag(
data: DataFrame,
*,
period_end: str = "period_end",
lag: int | str | Timedelta,
available_col: str = "available_date"
) -> DataFrame
Create availability dates from reporting dates and a fixed lag.
Parameters
data : DataFrame Source observations containing reporting-period dates. period_end : str, default="period_end" Reporting-date column. lag : int, str, or Timedelta Non-negative calendar lag; integers denote days. available_col : str, default="available_date" Name of the generated availability column.
Returns
DataFrame
Copy of data containing parsed dates and availability timestamps.
Notes
Exact publication timestamps are preferable when available. A fixed lag is only a conservative fallback for point-in-time analysis.
Source code in src/capacities_ml_fin/finance/alignment.py
validate_no_lookahead
validate_no_lookahead
validate_no_lookahead(
data: DataFrame,
*,
model_time: str = "date",
available_time: str = "available_date",
raise_on_error: bool = True
) -> bool
Check that every observation was available by its model date.
Parameters
data : DataFrame Aligned modeling data. model_time : str, default="date" Timestamp at which each row is used. available_time : str, default="available_date" Timestamp at which information became observable. raise_on_error : bool, default=True Raise on the first violation instead of returning false.
Returns
bool True when every finite availability time is no later than model time.
Source code in src/capacities_ml_fin/finance/alignment.py
point_in_time_join
point_in_time_join
point_in_time_join(
left: DataFrame,
right: DataFrame,
*,
left_on: str = "date",
available_on: str = "available_date",
by: str | Sequence[str] | None = None,
suffixes: tuple[str, str] = ("", "_right"),
allow_exact_matches: bool = True
) -> DataFrame
Join each model row to the latest information available at that time.
Parameters
left, right : DataFrame
Modeling rows and timestamped information releases.
left_on : str, default="date"
Model timestamp in left.
available_on : str, default="available_date"
Information-availability timestamp in right.
by : str or sequence of str, optional
Grouping keys such as ticker or entity identifier.
suffixes : tuple of str, default=("", "_right")
Suffixes for overlapping payload columns.
allow_exact_matches : bool, default=True
Whether information released exactly at model time is eligible.
Returns
DataFrame Backward as-of join in the original left-row order.
Notes
The result is validated with :func:validate_no_lookahead before return.
Source code in src/capacities_ml_fin/finance/alignment.py
104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 | |