Data & moments¶
See the Data guide.
Synthetic data¶
synthetic
¶
Synthetic market data generation.
A correlated geometric-Brownian-motion generator that produces realistic price panels without any network access. Used throughout the tests and examples so everything is reproducible and offline-friendly.
generate_prices
¶
generate_prices(
n_assets: int = 12,
n_days: int = 756,
*,
seed: int = 0,
start_price: float = 100.0,
mean_annual_return: float = 0.08,
annual_vol_range: tuple[float, float] = (0.15, 0.45),
correlation_strength: float = 0.5,
start_date: str = "2021-01-01",
tickers: list[str] | None = None,
) -> DataFrame
Generate a panel of correlated daily prices via geometric Brownian motion.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
n_assets
|
int
|
Panel shape. |
12
|
n_days
|
int
|
Panel shape. |
12
|
seed
|
int
|
RNG seed for reproducibility. |
0
|
mean_annual_return
|
float
|
Center of the per-asset drift (drifts are jittered around this). |
0.08
|
annual_vol_range
|
tuple[float, float]
|
Range from which per-asset annual volatilities are drawn. |
(0.15, 0.45)
|
correlation_strength
|
float
|
Average cross-asset correlation in |
0.5
|
tickers
|
list[str] | None
|
Optional explicit column names; otherwise |
None
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
Indexed by business day, one column per asset, containing prices. |
Source code in src/jaxfolio/data/synthetic.py
generate_returns
¶
Convenience wrapper returning simple daily returns from synthetic prices.
Source code in src/jaxfolio/data/synthetic.py
Loaders¶
loaders
¶
Data ingestion: CSV, Parquet, and (optionally) live market data via yfinance.
The CSV/Parquet loaders have no third-party dependency beyond pandas. The
yfinance loaders are guarded so importing this module never requires the
[data] extra to be installed.
load_csv
¶
load_csv(
path: str | Path,
*,
date_col: str = "date",
asset_col: str | None = None,
price_col: str = "close",
**read_csv_kwargs,
) -> DataFrame
Load a price panel from CSV.
Two layouts are supported:
- Wide (default when
asset_colisNone): one column per asset, plus a date column used as the index. - Long/tidy (when
asset_colis given): columnsdate_col,asset_col,price_colare pivoted into a wide panel.
Source code in src/jaxfolio/data/loaders.py
load_parquet
¶
load_parquet(
path: str | Path,
*,
date_col: str = "date",
asset_col: str | None = None,
price_col: str = "close",
) -> DataFrame
Load a price panel from Parquet (same layouts as :func:load_csv).
Source code in src/jaxfolio/data/loaders.py
load_yfinance
¶
load_yfinance(
tickers: list[str] | str,
*,
start: str | None = None,
end: str | None = None,
period: str | None = "2y",
interval: str = "1d",
price_field: str = "Close",
) -> DataFrame
Download a price panel from Yahoo Finance (requires the [data] extra).
Returns a wide date-by-ticker panel of price_field values.
Source code in src/jaxfolio/data/loaders.py
load_option_chain
¶
Fetch and normalize an option chain from Yahoo Finance ([data] extra).
Returns a tidy frame with columns [type, strike, expiry, last, bid, ask,
volume, open_interest, implied_vol] for calls and puts combined. If
expiry is None the nearest expiry is used.
Source code in src/jaxfolio/data/loaders.py
Returns & splitting¶
returns
¶
Return computation, alignment, and train/test splitting.
All functions accept and return pandas objects so they compose cleanly with the loaders, and hand off clean float arrays to the JAX optimizers downstream.
to_returns
¶
Convert a price panel to returns.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
prices
|
DataFrame
|
Price panel (rows = dates, columns = assets). |
required |
kind
|
str
|
|
'simple'
|
dropna
|
bool
|
Drop the leading NaN row (and any all-NaN rows) if |
True
|
Source code in src/jaxfolio/data/returns.py
align
¶
Align multiple frames on their common (or union) index.
Useful when combining price series pulled from different sources.
Source code in src/jaxfolio/data/returns.py
clean_returns
¶
clean_returns(
returns: DataFrame,
*,
max_missing_frac: float = 0.1,
fill: str = "zero",
) -> DataFrame
Drop sparse columns and fill remaining gaps.
Columns missing more than max_missing_frac of observations are dropped.
Remaining NaNs are filled with 0.0 ("zero") or forward-filled
("ffill").
Source code in src/jaxfolio/data/returns.py
train_test_split
¶
Chronological split into in-sample and out-of-sample sets.
test_size is the fraction of the most recent observations held out.
Source code in src/jaxfolio/data/returns.py
annualization_factor
¶
Return the annualization factor (kept explicit for clarity in call sites).
Moment estimators¶
estimators
¶
Moment estimators (mean & covariance) implemented in JAX.
Every estimator takes a (T, N) return array and returns JAX arrays, so the
downstream optimizers can jit through the whole pipeline. Inputs may be pandas
frames or numpy arrays; :func:as_matrix normalizes them.
as_matrix
¶
Return (matrix, asset_names) from a returns object.
Accepts a pandas DataFrame (columns become asset names), or a raw array
(names default to asset_0...). NaNs are replaced with zeros.
Source code in src/jaxfolio/moments/estimators.py
mean_returns
¶
Sample mean of returns; annualized if periods_per_year is given.
Source code in src/jaxfolio/moments/estimators.py
sample_covariance
¶
Sample covariance matrix (denominator T - 1); optionally annualized.
Requires at least two observations; a single row has no defined covariance.
Source code in src/jaxfolio/moments/estimators.py
ewma_covariance
¶
ewma_covariance(
returns: Array,
*,
halflife: float = 63.0,
periods_per_year: int | None = None,
) -> Array
Exponentially-weighted covariance matrix.
Recent observations receive more weight; halflife is in periods (default
~one quarter of trading days).
Source code in src/jaxfolio/moments/estimators.py
ledoit_wolf_covariance
¶
ledoit_wolf_covariance(
returns: Array, *, periods_per_year: int | None = None
) -> tuple[Array, float]
Ledoit-Wolf shrinkage toward a scaled-identity target.
Returns (shrunk_cov, shrinkage_intensity). The shrinkage intensity is
estimated analytically (Ledoit & Wolf, 2004) and clipped to [0, 1].
Source code in src/jaxfolio/moments/estimators.py
correlation_from_covariance
¶
Convert a covariance matrix to a correlation matrix.
Constraint projections¶
projections
¶
Constraint projections used by the projected-gradient optimizers.
All projections are pure JAX and jit/vmap-safe. The two workhorses are:
- :func:
project_simplex— Euclidean projection onto the probability simplex{w : w >= 0, sum(w) = 1}(long-only, fully-invested). - :func:
project_box_budget— projection onto a box[lo, hi]intersected with the budget hyperplanesum(w) = budget(allows bounded shorting).
project_simplex
¶
Euclidean projection of v onto the scaled simplex summing to budget.
Implements the classic Duchi et al. (2008) sort-based algorithm, which is exact and differentiable almost everywhere.
Source code in src/jaxfolio/constraints/projections.py
project_box_budget
¶
project_box_budget(
v: Array,
lower: float = 0.0,
upper: float = 1.0,
budget: float = 1.0,
*,
max_iter: int = 50,
tol: float = 1e-10,
) -> Array
Project v onto {w : lower <= w <= upper, sum(w) = budget}.
Solves for the Lagrange multiplier tau on the budget constraint by
bisection: w(tau) = clip(v - tau, lower, upper) is monotone decreasing in
tau, so we bisect until sum(w(tau)) == budget. Feasible whenever
n*lower <= budget <= n*upper.
Source code in src/jaxfolio/constraints/projections.py
normalize_weights
¶
Rescale weights to sum to budget (assumes a non-zero sum).
Source code in src/jaxfolio/constraints/projections.py
softmax_weights
¶
Map unconstrained logits to long-only weights via softmax (sums to budget).