Math API¶
Mathematical utilities for precision, rounding, and statistics.
Precision & Rounding¶
round_price_to_tick¶
round_price_to_tick ¶
Round a price down to the nearest valid tick.
round_qty_to_lot¶
round_qty_to_lot ¶
Round a quantity down to the nearest valid lot size.
quantize_fee¶
quantize_fee ¶
Quantize a fee to the desired precision using HALF_UP rounding.
Returns¶
simple_return¶
simple_return ¶
Calculate simple return (current / previous - 1).
Example
from decimal import Decimal simple_return(Decimal("110"), Decimal("100")) Decimal('0.1')
log_return¶
log_return ¶
Calculate log return ln(current / previous).
Example
from decimal import Decimal ret = log_return(Decimal("110"), Decimal("100")) float(ret) # ~0.0953 0.09531...
cumulative_return¶
cumulative_return ¶
Aggregate multiple period returns into a cumulative return.
Example
from decimal import Decimal rets = [Decimal("0.10"), Decimal("0.05"), Decimal("-0.02")] float(cumulative_return(rets)) # (1.1)(1.05)(0.98) - 1 = 0.1319 0.1319
annualized_return¶
annualized_return ¶
Convert total return to annualized return (CAGR).
Uses the formula: (1 + total_return)^(periods_per_year / periods) - 1
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
total_return
|
Decimal
|
Total cumulative return (e.g., 0.50 for 50%) |
required |
periods
|
int
|
Number of periods in the data (e.g., 180 days) |
required |
periods_per_year
|
int
|
Periods per year (default: 365 days) |
365
|
Returns:
| Type | Description |
|---|---|
Decimal
|
Annualized (CAGR) return |
returns_from_prices¶
returns_from_prices ¶
Calculate simple returns from a price series.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
prices
|
Iterable[Decimal]
|
Iterable of prices (at least 2 values) |
required |
Returns:
| Type | Description |
|---|---|
list[Decimal]
|
List of returns (length = len(prices) - 1) |
Example
from decimal import Decimal prices = [Decimal("100"), Decimal("110"), Decimal("105")] rets = returns_from_prices(prices) for r in rets: ... print(round(float(r), 4)) 0.1 -0.0455
Statistics¶
mean¶
stddev¶
variance¶
Volatility¶
realized_volatility¶
realized_volatility ¶
Compute annualized realized volatility from a series of returns.
annualize_volatility¶
annualize_volatility ¶
Scale per-period volatility to an annualized figure.