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 |
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 |
silent
|
**options
|
Any
|
Fields of |
{}
|
Returns:
| Type | Description |
|---|---|
Evaluation
|
The |
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.
bar
instance-attribute
¶
Spacing of the bar grid if perfectly regular, otherwise None.
periods
instance-attribute
¶
Cross-sectional IC per timestamp and horizon, with counts, coverage and a status.
summary
instance-attribute
¶
Cross-sectional summary per horizon and method: mean, HAC inference, ICIR, counts.
quantiles
instance-attribute
¶
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
¶
The labels by horizon, as returns. Empty after load.
volatility
class-attribute
instance-attribute
¶
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
¶
Return the cross-sectional IC as a table of timestamps by horizon.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
method
|
str
|
|
'spearman'
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
One column per horizon (in bars) and one row per timestamp; |
DataFrame
|
undefined. |
monthly_ic
¶
Return the mean and count of cross-sectional IC in each UTC calendar month.
metrics
¶
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
¶
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 |
dict[str, Any]
|
|
dict[str, Any]
|
tables under |
dict[str, Any]
|
when the evaluation lacks them). |
save
¶
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 |
required |
config
|
EvaluationConfig | None
|
The configuration to attach if the directory has no |
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
¶
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
¶
Full-period IC per asset with eligibility, monthly statistics, bootstrap intervals and t-tests.
summary
instance-attribute
¶
Equal-asset summaries per horizon and method, with bootstrap intervals and t-tests.
quantiles
instance-attribute
¶
Mean return by score bucket within each eligible asset.
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
¶
Rank persistence and eligible-universe overlap by timestamp and lag.
quantiles
instance-attribute
¶
Bucket entry/exit counts and entry fractions by timestamp, lag and quantile.
assets
instance-attribute
¶
Normalised signal change, sign and zero transitions by asset and lag.
summary
instance-attribute
¶
Equal-timestamp CS means and equal-asset TS means with contributing counts.
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
|
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
|
end
|
datetime | Timestamp | str | None
|
Exclusive end, or |
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 |
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 |
required |
prices
|
DataFrame
|
Prices, as for |
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: |
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 |
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
|
False
|
progress
|
ProgressFactory
|
A progress display; see |
silent
|
**options
|
Any
|
Fields of |
{}
|
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 |
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
¶
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
¶
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 |
None
|
descending
|
bool | None
|
Largest first; default: largest first for the ICs, z- and t-statistics,
counts and |
None
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
A table indexed by trial identifier with the columns in |
DataFrame
|
column per context key. Statistics a trial lacks at the horizon are |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
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: |
None
|
descending
|
bool | None
|
Largest first; default: the column's own direction, as for |
None
|
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
A dictionary with |
dict[str, Any]
|
|
dict[str, Any]
|
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
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
¶
Version of the record layout.
family
instance-attribute
¶
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
¶
One line saying what the signal bets on.
parameters
class-attribute
instance-attribute
¶
The signal's parameters.
sample
instance-attribute
¶
in_sample before the holdout boundary, holdout from it on.
holdout_start
class-attribute
instance-attribute
¶
The study's holdout boundary when the evaluation ran.
delay
class-attribute
instance-attribute
¶
Bars between a score and the start of its label.
assets
class-attribute
instance-attribute
¶
Assets with prices in the evaluation.
bar_seconds
class-attribute
instance-attribute
¶
Spacing of the bars in seconds if regular, otherwise None.
data_fingerprint
class-attribute
instance-attribute
¶
SHA-256 of the factor and price tables evaluated.
versions
class-attribute
instance-attribute
¶
Versions of alphatonic and of whatever the caller names, such as its own code.
context
class-attribute
instance-attribute
¶
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
¶
The researcher's note, such as why this variant was run.
metrics
class-attribute
instance-attribute
¶
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
¶
Forward-return horizons in bars (rows of the price table).
min_assets
class-attribute
instance-attribute
¶
Finite score/return pairs a timestamp needs for a cross-sectional IC.
delay
class-attribute
instance-attribute
¶
Extra bars between the observation and the start of the return it is scored against.
quantiles
class-attribute
instance-attribute
¶
Number of score buckets in the quantile response tables.
hac_lags
class-attribute
instance-attribute
¶
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
¶
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
¶
Span, in bars, of the exponentially weighted volatility behind vol_scaled targets.
vol_min_bars
class-attribute
instance-attribute
¶
One-bar returns the volatility estimate needs before it is used.
start
class-attribute
instance-attribute
¶
First evaluation timestamp (inclusive, UTC). Default: the first timestamp with a score.
end
class-attribute
instance-attribute
¶
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
¶
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
¶
Finite score/return pairs a window needs before an asset's IC is computed.
min_coverage
class-attribute
instance-attribute
¶
Fraction of a window's eligible bars that must contribute a finite pair.
min_horizons
class-attribute
instance-attribute
¶
Minimum window length, in multiples of the return horizon.
min_months
class-attribute
instance-attribute
¶
Complete, valid calendar months needed for a monthly ICIR.
rolling_window
class-attribute
instance-attribute
¶
Trailing window of the rolling TS IC, as a fixed duration such as 30D.
rolling_step
class-attribute
instance-attribute
¶
Spacing of rolling window endpoints, as a fixed duration.
bootstrap_samples
class-attribute
instance-attribute
¶
Circular block-bootstrap draws for confidence intervals; 0 disables them.
block_bars
class-attribute
instance-attribute
¶
Bootstrap block length in bars. Default: max(horizon, ceil(n ** (1/3))).
seed
class-attribute
instance-attribute
¶
Seed of the bootstrap random number generator.
for_bars
classmethod
¶
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 |
required |
**overrides
|
Any
|
Options that replace the preset's values, such as |
{}
|
Returns:
| Type | Description |
|---|---|
Self
|
Ordinary |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
PersistenceOptions
¶
Bases: BaseModel
Signal diagnostics on the original bar grid, independent of return horizons.
ReportOptions
¶
Bases: BaseModel
Display options of the cross-sectional charts in a tearsheet.
Building blocks¶
forward_returns
¶
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. |
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 |
bar_volatility
¶
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 |
summarize_ic
¶
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 |
required |
lags
|
int
|
Number of autocovariance lags in the standard error. |
required |
Returns:
| Type | Description |
|---|---|
dict[str, float | int]
|
|
dict[str, float | int]
|
(mean / std, not annualized), |
dict[str, float | int]
|
|
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'
|
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.05
|
persistence
|
float
|
Autocorrelation of each asset's score from one bar to the next, in |
0.9
|
missing_fraction
|
float
|
Fraction of prices set to |
0.0
|
seed
|
int
|
Seed of the random number generator. |
0
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
|
DataFrame
|
|
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)