Coverage for src/tinycta/util.py: 100%
7 statements
« prev ^ index » next coverage.py v7.14.1, created at 2026-07-30 04:16 +0000
« prev ^ index » next coverage.py v7.14.1, created at 2026-07-30 04:16 +0000
1"""Volatility adjustment and price normalization helpers (Polars expressions).
3This module provides expression-level building blocks used to standardize
4log returns by an exponentially weighted volatility estimate and to integrate
5those standardized returns into adjusted log-price series. These are designed
6for use within Polars pipelines (e.g., DataFrame.with_columns) and operate
7column-wise.
9Functions:
10- vol_adj: Standardize log returns using EWMA volatility and clip extremes.
11- adj_log_prices: Cumulative sum (integration) of standardized, clipped returns.
12"""
14import polars as pl
17def vol_adj(x: pl.Expr, vola: int, clip: float, min_samples: int = 1) -> pl.Expr:
18 """Compute clipped, volatility-adjusted log returns per column.
20 Args:
21 x: Price series to transform.
22 vola: EWMA lookback (span-equivalent) for std.
23 clip: Symmetric clipping threshold applied after standardization.
24 min_samples: Minimum samples required by EWM to yield non-null values.
25 Note that ``ewm_std`` is undefined for a single observation, so the
26 first log return is null regardless of this value — the output
27 therefore starts at the *second* log return.
29 Returns:
30 pl.Expr: Standardized and clipped log returns.
31 """
32 log_returns = x.log().diff()
33 vol = log_returns.ewm_std(com=vola - 1, adjust=True, min_samples=min_samples)
34 return (log_returns / vol).clip(-clip, clip)
37def adj_log_prices(x: pl.Expr, vola: int, clip: float, min_samples: int = 1) -> pl.Expr:
38 """Integrate clipped, volatility-adjusted log returns to adjusted log prices.
40 Uses ``vol_adj`` to standardize/clamp log returns and then integrates them
41 via cumulative sum. The resulting series behaves like a standardized price-
42 like process with roughly unit volatility.
44 Args:
45 x: Polars expression of the price series to transform.
46 vola: EWMA lookback (span-equivalent) used to estimate volatility.
47 clip: Symmetric clipping threshold applied after standardization.
48 min_samples: Minimum samples required by EWM to emit non-null values.
50 Returns:
51 pl.Expr: Adjusted-log-price series obtained by cumulative sum of
52 standardized returns.
53 """
54 return vol_adj(x, vola=vola, clip=clip, min_samples=min_samples).cum_sum()