Skip to content

API

This page lists functions, result objects and configuration options. Entries are generated from source docstrings. Import names such as evaluate and Study from alphatonic; server, demo and progress utilities live in the submodules shown below.

Evaluate

evaluate

evaluate(
    factor: DataFrame | Series,
    prices: DataFrame,
    config: EvaluationConfig | None = None,
    *,
    progress: ProgressFactory = silent,
    **options: Any,
) -> Evaluation

Evaluate cross-sectional and time-series prediction of forward returns.

Rows of prices are the bars of the evaluation: horizons and delays count rows, so a daily table of trading days, an hourly 24/7 grid and a table of rebalance dates all work, and a missing price is NaN. A score at a timestamp must be computable from information available at that timestamp's price; the label is the return from delay bars later over horizon bars. By default the cross-sectional IC correlates scores with that return, and the time-series IC with the return divided by the asset's ex-ante volatility over the horizon; target and time_series.target choose. Timestamps are read as UTC when they are naive.

Options come either as an EvaluationConfig or as keyword arguments with the names of its fields, not both.

Parameters:

Name Type Description Default
factor DataFrame | Series

Scores, larger meaning a higher expected return. A DataFrame with one row per timestamp and one column per asset, or a Series indexed by (timestamp, asset). NaN (and infinity) mean no score.

required
prices DataFrame

Prices with one row per bar and one column per asset.

required
config EvaluationConfig | None

The evaluation options.

None
progress ProgressFactory

A progress display; see alphatonic.progress. Silent by default.

silent
**options Any

Fields of EvaluationConfig, such as horizons=[1, 5, 21].

{}

Returns:

Type Description
Evaluation

The Evaluation tables.

Raises:

Type Description
TypeError

If an input has the wrong type or index.

ValueError

If an input is malformed or the options are invalid.

Examples:

from alphatonic import evaluate
from alphatonic.demo import synthetic_market

factor, prices = synthetic_market(n_assets=20, n_bars=300, seed=1)
result = evaluate(factor, prices, horizons=[1, 5], time_series={"bootstrap_samples": 0})
horizons = result.summary.loc[result.summary.method == "spearman", "horizon"].tolist()
print(horizons)  # [1, 5]

Result

Evaluation dataclass

Evaluation(
    config: EvaluationConfig,
    start: Timestamp,
    end: Timestamp,
    bar: Timedelta | None,
    periods: DataFrame,
    summary: DataFrame,
    quantiles: DataFrame,
    time_series: TimeSeriesEvaluation | None = None,
    forward_returns: dict[int, DataFrame] = dict(),
    volatility: DataFrame | None = None,
    persistence: PersistenceEvaluation | None = None,
)

The result of evaluate: tables, not conclusions.

Statistics that cannot be computed are NaN, never zero, and every row records why in its status. The results reference documents each column.

config instance-attribute

The options the evaluation ran with.

start instance-attribute

start: Timestamp

Inclusive start of the evaluation window (UTC).

end instance-attribute

end: Timestamp

Exclusive end of the evaluation window (UTC).

bar instance-attribute

bar: Timedelta | None

Spacing of the bar grid if perfectly regular, otherwise None.

periods instance-attribute

periods: DataFrame

Cross-sectional IC per timestamp and horizon, with counts, coverage and a status.

summary instance-attribute

summary: DataFrame

Cross-sectional summary per horizon and method: mean, HAC inference, ICIR, counts.

quantiles instance-attribute

quantiles: DataFrame

Cross-sectional mean forward return per score bucket, timestamp and horizon.

time_series class-attribute instance-attribute

time_series: TimeSeriesEvaluation | None = None

Time-series results. None only for older saved or manually constructed evaluations.

persistence class-attribute instance-attribute

persistence: PersistenceEvaluation | None = None

Signal persistence tables; absent in evaluations saved before format 3.

forward_returns class-attribute instance-attribute

forward_returns: dict[int, DataFrame] = field(default_factory=dict, repr=False)

The labels by horizon, as returns. Empty after load.

volatility class-attribute instance-attribute

volatility: DataFrame | None = field(default=None, repr=False)

The ex-ante volatility of a one-bar return on the evaluation grid, when a target is vol_scaled: that target is forward_returns[h] / (volatility * sqrt(h)). None otherwise and after load.

ic

ic(method: str = 'spearman') -> DataFrame

Return the cross-sectional IC as a table of timestamps by horizon.

Parameters:

Name Type Description Default
method str

spearman (rank IC) or pearson.

'spearman'

Returns:

Type Description
DataFrame

One column per horizon (in bars) and one row per timestamp; NaN where the IC is

DataFrame

undefined.

monthly_ic

monthly_ic() -> DataFrame

Return the mean and count of cross-sectional IC in each UTC calendar month.

metrics

metrics() -> dict[str, float]

Flatten the summaries into finite scalars, named <cs|ts>.h<horizon>.<method>.<stat>.

Persistence summaries use persistence.<scope>.lag<lag>[.q<quantile>].<metric>.<stat>. Undefined statistics are omitted. The flat form suits parameter sweeps and experiment trackers. Both analyses contribute their available statistics.

to_dict

to_dict() -> dict[str, Any]

Return the result as plain JSON values: the configuration, the window and every table.

json.dumps(result.to_dict(), allow_nan=False) succeeds: missing values are None. Timestamps are ISO 8601 strings in UTC, durations are seconds, and each table is an object of equally long columns, named and ordered as in the table. Nothing is recomputed, so the document holds what the tearsheet draws. Forward returns and volatilities are left out, as by save. The results reference describes the layout.

Returns:

Type Description
dict[str, Any]

A dictionary with format ("alphatonic.evaluation"), format_version,

dict[str, Any]

alphatonic_version, config, start, end, bar_seconds, metrics, and the

dict[str, Any]

tables under cross_section, time_series and persistence (the last two None

dict[str, Any]

when the evaluation lacks them).

save

save(directory: str | Path) -> Path

Write the tables as gzip-compressed CSV files and the configuration as JSON.

Each table is a .csv.gz file that pandas.read_csv reads as it is. Forward returns are not saved; they follow from the prices and the configuration. Existing files of the same tables are replaced, including the plain .csv files that earlier versions wrote.

Returns:

Type Description
Path

The directory.

load classmethod

load(directory: str | Path, config: EvaluationConfig | None = None) -> Evaluation

Read an evaluation written by save.

Parameters:

Name Type Description Default
directory str | Path

The directory save wrote.

required
config EvaluationConfig | None

The configuration to attach if the directory has no evaluation.json, for example one written by another tool.

None

Raises:

Type Description
FileNotFoundError

If the tables are missing.

ValueError

If there is no configuration to attach.

render_tearsheet

render_tearsheet(
    *,
    options: ReportOptions | None = None,
    title: str = "Factor tearsheet",
    eyebrow: str | None = None,
    subtitle: str | None = None,
    context: dict[str, str] | None = None,
    footer: list[str] | None = None,
) -> str

Render the tearsheet as a standalone HTML document.

Parameters:

Name Type Description Default
options ReportOptions | None

Display options of the cross-sectional charts.

None
title str

Page heading.

'Factor tearsheet'
eyebrow str | None

Small label above the heading, such as a project's name; default: none.

None
subtitle str | None

A line under the heading, such as the factor's name.

None
context dict[str, str] | None

Extra labelled facts shown under the heading, such as the universe.

None
footer list[str] | None

Extra lines in the page footer.

None

Returns:

Type Description
str

The HTML. The JavaScript that draws the charts is embedded, so the page works offline.

tearsheet

tearsheet(path: str | Path, **options: Any) -> Path

Write the tearsheet to path and return it.

Accepts the keyword arguments of render_tearsheet. A directory writes tearsheet.html inside it.

TimeSeriesEvaluation dataclass

TimeSeriesEvaluation(
    assets: DataFrame,
    monthly: DataFrame,
    rolling: DataFrame,
    summary: DataFrame,
    quantiles: DataFrame,
)

Time-series results, one table per view.

Every table except summary and quantiles has one row per asset, horizon and method (and window, for monthly and rolling); see the results reference for the columns.

assets instance-attribute

assets: DataFrame

Full-period IC per asset with eligibility, monthly statistics, bootstrap intervals and t-tests.

monthly instance-attribute

monthly: DataFrame

IC recomputed inside each UTC calendar month.

rolling instance-attribute

rolling: DataFrame

IC recomputed inside trailing windows.

summary instance-attribute

summary: DataFrame

Equal-asset summaries per horizon and method, with bootstrap intervals and t-tests.

quantiles instance-attribute

quantiles: DataFrame

Mean return by score bucket within each eligible asset.

tables

tables() -> dict[str, DataFrame]

Return the tables by name.

PersistenceEvaluation dataclass

PersistenceEvaluation(
    periods: DataFrame, quantiles: DataFrame, assets: DataFrame, summary: DataFrame
)

Stored signal diagnostics. Fractions are decimals; lags count original grid rows.

periods instance-attribute

periods: DataFrame

Rank persistence and eligible-universe overlap by timestamp and lag.

quantiles instance-attribute

quantiles: DataFrame

Bucket entry/exit counts and entry fractions by timestamp, lag and quantile.

assets instance-attribute

assets: DataFrame

Normalised signal change, sign and zero transitions by asset and lag.

summary instance-attribute

summary: DataFrame

Equal-timestamp CS means and equal-asset TS means with contributing counts.

tables

tables() -> dict[str, DataFrame]

Return all stored tables by name.

Study

Study

Study(
    directory: str | Path,
    *,
    holdout_start: datetime | Timestamp | str | None = None,
    name: str | None = None,
)

Keep every evaluation of a research question as a trial in one directory.

Run evaluations through evaluate instead of alphatonic.evaluate: the study saves each result, refuses windows that cross the holdout boundary, and counts trials per family. Read the trials back with trials and compare them with board. Delete nothing from the directory: the trial count is what keeps the p-values honest.

Parameters:

Name Type Description Default
directory str | Path

Where the trials are kept. It is created by the first evaluation.

required
holdout_start datetime | Timestamp | str | None

First timestamp of the holdout period. In-sample evaluations end before it, and only an evaluation that asks for the holdout reads from it on. None means no holdout. Naive timestamps are UTC.

None
name str | None

The project's name, shown in each tearsheet's specification and on the list of trials.

None

window

window(
    start: datetime | Timestamp | str | None = None,
    end: datetime | Timestamp | str | None = None,
    *,
    holdout: bool = False,
) -> tuple[datetime | None, datetime | None]

Return the evaluation window after applying the holdout rule.

An in-sample window ends at the holdout boundary unless it ends earlier; a holdout window starts there unless it starts later. Call this before computing a signal to know which data it may read.

Parameters:

Name Type Description Default
start datetime | Timestamp | str | None

Inclusive start, or None for the first score (the boundary on the holdout).

None
end datetime | Timestamp | str | None

Exclusive end, or None for the end of the prices (the boundary in sample).

None
holdout bool

Evaluate the holdout instead of the in-sample period.

False

Returns:

Type Description
tuple[datetime | None, datetime | None]

The start and end, as UTC datetimes or None.

Raises:

Type Description
HoldoutError

If an in-sample window ends after the boundary, a holdout window starts before it, the holdout is asked for and the study has none, or the window is empty.

evaluate

evaluate(
    factor: DataFrame | Series,
    prices: DataFrame,
    config: EvaluationConfig | None = None,
    *,
    signal: str,
    summary: str | None = None,
    family: str | None = None,
    parameters: dict[str, JsonValue] | None = None,
    holdout: bool = False,
    context: dict[str, str] | None = None,
    versions: dict[str, str | None] | None = None,
    note: str | None = None,
    report: bool = False,
    progress: ProgressFactory = silent,
    **options: Any,
) -> Trial

Evaluate factor against prices, save the result as a trial, and return its record.

The window of config passes through window first. When the prices end before the window does, the window ends with them, so the record states the period evaluated. A failed evaluation saves nothing and is not counted.

Parameters:

Name Type Description Default
factor DataFrame | Series

Scores, as for alphatonic.evaluate.

required
prices DataFrame

Prices, as for alphatonic.evaluate.

required
config EvaluationConfig | None

The evaluation options.

None
signal str

Name of the signal, used in the identifier and the tearsheet's title.

required
summary str | None

One line saying what the signal bets on.

None
family str | None

Name to count the trial under; default: signal. Give variants of one idea under different names a common family so that they are counted together.

None
parameters dict[str, JsonValue] | None

The signal's parameters, recorded and shown under the title.

None
holdout bool

Evaluate the holdout period. Each such evaluation is counted.

False
context dict[str, str] | None

Labelled facts to record and show, such as {"Returns": "net of funding"}. Keys must differ from the columns of board.

None
versions dict[str, str | None] | None

Versions to record next to alphatonic's, such as your code's commit.

None
note str | None

A note stored with the trial.

None
report bool

Also write the tearsheet into the trial's directory. By default it is not stored, because it can be as large as the compressed tables; draw it from them with render_tearsheet or the server.

False
progress ProgressFactory

A progress display; see alphatonic.progress.

silent
**options Any

Fields of EvaluationConfig, instead of config.

{}

Returns:

Type Description
Trial

The trial's record.

Raises:

Type Description
HoldoutError

If the window crosses the holdout boundary.

TypeError

If an input has the wrong type, or both config and options are given.

ValueError

If an input, an option or a context key is invalid.

trials

trials() -> list[Trial]

Return every finished trial, newest first; see unreadable for records that fail.

unreadable

unreadable() -> list[Path]

Return the records that exist but cannot be read, such as a truncated file.

trial

trial(identifier: str) -> Trial

Return the record of one finished trial.

Raises:

Type Description
UnknownTrialError

If the identifier is malformed or no finished trial has it.

evaluation

evaluation(identifier: str) -> Evaluation

Reload the tables of one finished trial.

Raises:

Type Description
UnknownTrialError

If the identifier is malformed or no finished trial has it.

render_tearsheet

render_tearsheet(identifier: str) -> str

Return the tearsheet of one finished trial as a page of HTML, drawn from its tables.

The page is the one evaluate(report=True) writes: the study's name, the trial's context and note, and its place in its family's count ("2 of momentum, this one included"). Nothing is recomputed.

Raises:

Type Description
UnknownTrialError

If the identifier is malformed or no finished trial has it.

FileNotFoundError

If the trial has no saved tables.

board

board(
    horizon: int | None = None,
    *,
    sort: str | None = None,
    descending: bool | None = None,
) -> DataFrame

Return one row per trial with its headline statistics at one horizon, newest first.

Trials are counted per family, across all parameters and both samples. adjusted_p, ts_adjusted_p and ts_cosine_adjusted_p are the p-values cs_p, ts_p and ts_cosine_p times that count, at most 1: Bonferroni's correction over the family, for each p-value on its own. The count is a lower bound on the alternatives tried, because variants run outside the study, or abandoned before evaluation, are not in it.

Parameters:

Name Type Description Default
horizon int | None

Horizon of the statistics, in bars; default: the smallest horizon of any trial.

None
sort str | None

A column to sort by instead, such as adjusted_p: any column but parameters, including the context keys. Rows without a value come last.

None
descending bool | None

Largest first; default: largest first for the ICs, z- and t-statistics, counts and created_at, smallest first for everything else.

None

Returns:

Type Description
DataFrame

A table indexed by trial identifier with the columns in BOARD_COLUMNS, then one

DataFrame

column per context key. Statistics a trial lacks at the horizon are NaN.

Raises:

Type Description
ValueError

If sort names no sortable column. The message lists them.

to_dict

to_dict(
    horizon: int | None = None,
    *,
    sort: str | None = None,
    descending: bool | None = None,
) -> dict[str, Any]

Return the study as plain JSON values: its trials with the board's statistics.

The trials come in the order of board with the same arguments, newest first by default, and carry the board's columns, so a page that lists them needs nothing else. Each trial also carries the 95% interval of its cross-sectional rank IC as cs_ci_lower and cs_ci_upper, and the 95% bootstrap intervals of its time-series rank IC as ts_ci_lower and ts_ci_upper and of its time-series cosine IC as ts_cosine_ci_lower and ts_cosine_ci_upper. Each is None when the trial has no inference at the horizon, and the time-series ones when the bootstrap was off. Missing statistics are None, timestamps are ISO 8601 strings in UTC, and json.dumps(..., allow_nan=False) succeeds. The results reference describes the layout.

Parameters:

Name Type Description Default
horizon int | None

Horizon of the statistics, in bars; default: the smallest of any trial.

None
sort str | None

A board column to sort by; default: created_at.

None
descending bool | None

Largest first; default: the column's own direction, as for board.

None

Returns:

Type Description
dict[str, Any]

A dictionary with format ("alphatonic.study"), format_version, name,

dict[str, Any]

holdout_start, horizon, horizons (of all trials), sort, descending,

dict[str, Any]

context_keys, families, trials and unreadable.

Raises:

Type Description
ValueError

If sort names no sortable column. The message lists them.

Trial

Bases: BaseModel

The record of one evaluation: what was evaluated, on which sample, and its metrics.

Fields this version does not know are ignored when a record is read, so a record written by another tool with the same core fields still counts as a trial. A record of another format_version is unreadable.

format_version class-attribute instance-attribute

format_version: Literal[1] = FORMAT_VERSION

Version of the record layout.

id instance-attribute

id: str

Identifier, which is also the name of the trial's directory.

created_at instance-attribute

created_at: datetime

When the evaluation ran, in UTC.

signal instance-attribute

signal: str

Name of the signal evaluated.

family instance-attribute

family: str

Name the trials are counted under: the signal's name unless the caller pooled several signals that test one idea under a common name.

summary class-attribute instance-attribute

summary: str | None = None

One line saying what the signal bets on.

parameters class-attribute instance-attribute

parameters: dict[str, JsonValue] = Field(default_factory=dict)

The signal's parameters.

sample instance-attribute

sample: Sample

in_sample before the holdout boundary, holdout from it on.

holdout_start class-attribute instance-attribute

holdout_start: datetime | None = None

The study's holdout boundary when the evaluation ran.

start instance-attribute

start: datetime

Inclusive start of the evaluated window, in UTC.

end instance-attribute

end: datetime

Exclusive end of the evaluated window, in UTC.

horizons instance-attribute

horizons: list[int]

Forward-return horizons, in bars.

delay class-attribute instance-attribute

delay: int = 0

Bars between a score and the start of its label.

assets class-attribute instance-attribute

assets: list[str] = Field(default_factory=list)

Assets with prices in the evaluation.

bar_seconds class-attribute instance-attribute

bar_seconds: float | None = None

Spacing of the bars in seconds if regular, otherwise None.

data_fingerprint class-attribute instance-attribute

data_fingerprint: str | None = None

SHA-256 of the factor and price tables evaluated.

versions class-attribute instance-attribute

versions: dict[str, str | None] = Field(default_factory=dict)

Versions of alphatonic and of whatever the caller names, such as its own code.

context class-attribute instance-attribute

context: dict[str, str] = Field(default_factory=dict)

Facts the caller supplied, such as how returns were adjusted or what checks the signal passed, shown in the tearsheet and the board.

note class-attribute instance-attribute

note: str | None = None

The researcher's note, such as why this variant was run.

metrics class-attribute instance-attribute

metrics: dict[str, float] = Field(default_factory=dict)

The flat metrics of Evaluation.metrics.

HoldoutError

Bases: ValueError

Refuse a window that crosses the holdout boundary from the side it was asked for.

UnknownTrialError

Bases: LookupError

Refuse an identifier that no finished trial of the study has.

Serve a study

serve

serve(study: Study, host: str = '127.0.0.1', port: int = 8000) -> None

Serve the study's trials until interrupted.

Parameters:

Name Type Description Default
study Study

The study to serve.

required
host str

Address to listen on. The default accepts connections from this machine only.

'127.0.0.1'
port int

Port to listen on.

8000

make_server

make_server(
    study: Study, host: str = "127.0.0.1", port: int = 8000
) -> ThreadingHTTPServer

Return a server for the study, bound but not yet serving; port 0 picks a free port.

For command syntax and defaults, see the command-line reference.

Configuration

EvaluationConfig

Bases: BaseModel

What to evaluate: horizons, eligibility rules and the evaluation window.

Every field has a default, so EvaluationConfig() is a valid configuration. The object is immutable; use model_copy(update=...) to derive a variant.

horizons class-attribute instance-attribute

horizons: Annotated[tuple[PositiveInt, ...], Field(min_length=1)] = (1, 5, 10)

Forward-return horizons in bars (rows of the price table).

min_assets class-attribute instance-attribute

min_assets: int = Field(default=5, ge=3)

Finite score/return pairs a timestamp needs for a cross-sectional IC.

delay class-attribute instance-attribute

delay: int = Field(default=0, ge=0)

Extra bars between the observation and the start of the return it is scored against.

quantiles class-attribute instance-attribute

quantiles: int = Field(default=5, ge=2)

Number of score buckets in the quantile response tables.

hac_lags class-attribute instance-attribute

hac_lags: int | None = Field(default=None, ge=0)

Newey-West lags for the cross-sectional mean IC. At least horizon - 1 are always used. Default: floor(4 * (n / 100) ** (2 / 9)).

target class-attribute instance-attribute

target: Target = 'return'

Label of the cross-sectional IC: the forward return, or vol_scaled, the forward return divided by the asset's ex-ante volatility over the horizon (a risk-adjusted IC). The time-series evaluation has its own time_series.target.

vol_span class-attribute instance-attribute

vol_span: int = Field(default=60, ge=2)

Span, in bars, of the exponentially weighted volatility behind vol_scaled targets.

vol_min_bars class-attribute instance-attribute

vol_min_bars: int = Field(default=20, ge=2)

One-bar returns the volatility estimate needs before it is used.

start class-attribute instance-attribute

start: datetime | None = None

First evaluation timestamp (inclusive, UTC). Default: the first timestamp with a score.

end class-attribute instance-attribute

end: datetime | None = None

End of the evaluation window (exclusive, UTC). Prices at or after it are ignored, and a label must end before it. Default: one bar after the last price.

persistence class-attribute instance-attribute

persistence: PersistenceOptions = Field(default_factory=PersistenceOptions)

Signal persistence diagnostics; computed without future-return labels.

time_series class-attribute instance-attribute

time_series: TimeSeriesOptions = Field(default_factory=TimeSeriesOptions)

Options of the time-series evaluation.

TimeSeriesOptions

Bases: BaseModel

Eligibility rules, windows and bootstrap settings for time-series IC.

The eligibility values are sample-size heuristics, not significance thresholds.

target class-attribute instance-attribute

target: Target = 'vol_scaled'

Label of the time-series IC: vol_scaled divides each forward return by the asset's ex-ante volatility over the horizon, so periods count by risk rather than by size; return uses the forward return as it is.

min_pairs class-attribute instance-attribute

min_pairs: int = Field(default=100, ge=3)

Finite score/return pairs a window needs before an asset's IC is computed.

min_coverage class-attribute instance-attribute

min_coverage: float = Field(default=0.8, gt=0, le=1)

Fraction of a window's eligible bars that must contribute a finite pair.

min_horizons class-attribute instance-attribute

min_horizons: PositiveInt = 20

Minimum window length, in multiples of the return horizon.

min_months class-attribute instance-attribute

min_months: int = Field(default=6, ge=2)

Complete, valid calendar months needed for a monthly ICIR.

rolling_window class-attribute instance-attribute

rolling_window: str = '30D'

Trailing window of the rolling TS IC, as a fixed duration such as 30D.

rolling_step class-attribute instance-attribute

rolling_step: str = '1D'

Spacing of rolling window endpoints, as a fixed duration.

bootstrap_samples class-attribute instance-attribute

bootstrap_samples: int = Field(default=1000, ge=0)

Circular block-bootstrap draws for confidence intervals; 0 disables them.

block_bars class-attribute instance-attribute

block_bars: PositiveInt | None = None

Bootstrap block length in bars. Default: max(horizon, ceil(n ** (1/3))).

seed class-attribute instance-attribute

seed: int = Field(default=0, ge=0)

Seed of the bootstrap random number generator.

for_bars classmethod

for_bars(bar: str | timedelta, **overrides: Any) -> Self

Return options whose windows suit bars of length bar, with overrides applied.

The defaults are kept while their 30-day rolling window holds enough bars for 100 pairs at 80% coverage: bars of 5 hours 45 minutes or shorter. Longer bars, such as 12-hour or daily ones, get relaxed windows: 15 pairs, 3 horizons, and a 90-day rolling window moved in 5-day steps. Relaxed windows buy availability, not accuracy: a monthly IC from 15 pairs is noisy. With weekly or longer bars even these windows are mostly too short; rely on the full-period IC and its bootstrap interval.

Parameters:

Name Type Description Default
bar str | timedelta

Spacing of the price table's rows, such as "1h", "1D" or a timedelta.

required
**overrides Any

Options that replace the preset's values, such as bootstrap_samples.

{}

Returns:

Type Description
Self

Ordinary TimeSeriesOptions, saved with an evaluation like any others.

Raises:

Type Description
ValueError

If bar is not a positive fixed duration, or an override is invalid.

PersistenceOptions

Bases: BaseModel

Signal diagnostics on the original bar grid, independent of return horizons.

lags class-attribute instance-attribute

lags: Annotated[tuple[PositiveInt, ...], Field(min_length=1)] = (1, 5, 10)

Endpoint comparison distances in bars; never interpreted as holding periods.

min_pairs class-attribute instance-attribute

min_pairs: int = Field(default=2, ge=1)

Valid endpoint pairs required for each asset's descriptive statistics.

ReportOptions

Bases: BaseModel

Display options of the cross-sectional charts in a tearsheet.

rolling_window class-attribute instance-attribute

rolling_window: str = '7D'

Trailing window of the rolling mean of cross-sectional IC, as a fixed duration.

min_periods class-attribute instance-attribute

min_periods: PositiveInt = 3

Valid IC observations a rolling window needs to draw its mean.

Building blocks

forward_returns

forward_returns(prices: DataFrame, horizon: int, delay: int = 0) -> DataFrame

Compute exact-horizon simple returns, requiring an unbroken path of prices.

For the bar at row t, the label is prices[t + delay + horizon] / prices[t + delay] - 1. Rows are bars, so horizon and delay count rows, not clock time. The label is missing unless every row from t through t + delay + horizon has a price, so a gap never turns an h-bar label into a longer return, and the last delay + horizon rows have no label. Non-finite returns, such as a jump from a vanishing price, are missing too.

Parameters:

Name Type Description Default
prices DataFrame

Prices with one row per bar and one column per asset. NaN marks a missing price.

required
horizon int

Number of bars the return spans.

required
delay int

Bars between the observation and the start of the return.

0

Returns:

Type Description
DataFrame

A frame shaped like prices holding the forward return of each bar.

bar_volatility

bar_volatility(prices: DataFrame, span: int = 60, min_bars: int = 20) -> DataFrame

Estimate each asset's ex-ante volatility of a one-bar return, at every bar.

The estimate at row t is the exponentially weighted standard deviation of the one-bar returns ending at or before t, so it is known when the score at t is observed. A one-bar return needs prices on two consecutive rows; across a gap the last estimate carries forward. The estimate is missing until min_bars returns have been seen, and where it is zero (prices constant over the whole lookback).

Parameters:

Name Type Description Default
prices DataFrame

Prices with one row per bar and one column per asset. Rows before the evaluation window are welcome: they warm the estimate up.

required
span int

Span of the exponential weights, in bars.

60
min_bars int

One-bar returns needed before the first estimate.

20

Returns:

Type Description
DataFrame

A frame shaped like prices holding the standard deviation of a one-bar return.

summarize_ic

summarize_ic(series: Series, lags: int) -> dict[str, float | int]

Summarize a series of ICs with a Newey-West standard error of its mean.

The standard error uses Bartlett weights and an n / (n - 1) correction. Missing periods contribute zero scores but keep their time positions, so lag k always means k bars, and the denominator is the number of valid observations, not the length of the series. The p-value and 95% interval use the asymptotic normal approximation. Statistics that cannot be computed are omitted from the result: no spread below two observations, no ratio for a constant series, and no inference unless there are more observations than lags + 1.

Parameters:

Name Type Description Default
series Series

ICs in time order, with NaN for periods without a valid IC.

required
lags int

Number of autocovariance lags in the standard error.

required

Returns:

Type Description
dict[str, float | int]

n_periods, hac_lags and, when defined, mean, positive_fraction, std, ic_ir

dict[str, float | int]

(mean / std, not annualized), hac_se, hac_z, hac_p_value, ci95_lower and

dict[str, float | int]

ci95_upper.

Demo data

synthetic_market

synthetic_market(
    n_assets: int = 50,
    n_bars: int = 500,
    *,
    freq: str = "B",
    start: str = "2020-01-01",
    ic: float = 0.05,
    persistence: float = 0.9,
    missing_fraction: float = 0.0,
    seed: int = 0,
) -> tuple[DataFrame, DataFrame]

Simulate prices and a factor that predicts their next-bar returns.

Each asset has a latent score that evolves as an AR(1) process with unit variance. The return over the next bar is a fixed multiple of the score plus independent noise, scaled so that the population correlation between the score and the next-bar return is ic. Longer horizons inherit part of that relationship through persistence. Prices are positive and start at 100.

Parameters:

Name Type Description Default
n_assets int

Number of assets.

50
n_bars int

Number of bars (rows).

500
freq str

A pandas frequency alias for the bars, such as B (business days), D or h.

'B'
start str

First timestamp. The index is timezone-naive.

'2020-01-01'
ic float

Target correlation between the score and the next-bar return, in [0, 1).

0.05
persistence float

Autocorrelation of each asset's score from one bar to the next, in [0, 1).

0.9
missing_fraction float

Fraction of prices set to NaN at random.

0.0
seed int

Seed of the random number generator.

0

Returns:

Type Description
DataFrame

(factor, prices): two tables of the same shape, indexed by timestamp, with the assets

DataFrame

A000, A001, ... as columns.

Progress reporting

progress

An optional progress hook, so long evaluations can report to any display.

Evaluation is silent by default. Pass progress= to evaluate a callable with the signature of silent: it receives a description and an optional total, and returns a context manager that yields an advance function. This is how a command-line tool can draw a Rich or tqdm bar without alphatonic depending on either.

ProgressFactory module-attribute

ProgressFactory = Callable[[str, int | None], AbstractContextManager[Advance]]

Starts a task with a description and a total (None if unknown); yields advance.

Advance

Bases: Protocol

Moves a progress task forward.

silent

silent(description: str, total: int | None = None) -> Iterator[Advance]

Report nothing. This is the default progress display.

track

track(
    items: Sequence[T], description: str, progress: ProgressFactory = silent
) -> Iterator[T]

Iterate over items while reporting progress.

The progress hook lets a command-line tool or notebook display progress without alphatonic depending on a UI library. This one prints each task when it finishes; a Rich or tqdm bar has the same shape, creating the bar in place of done and updating it in advance:

from contextlib import contextmanager

from alphatonic import evaluate
from alphatonic.demo import synthetic_market


@contextmanager
def print_progress(description, total=None):
    done = 0

    def advance(steps=1, *, description=None):
        nonlocal done
        done += steps

    yield advance
    print(f"{description}: {done} of {total if total is not None else '?'}")


factor, prices = synthetic_market(n_assets=10, n_bars=200, seed=0)
result = evaluate(factor, prices, horizons=[1], progress=print_progress)