Python API reference / 2.2.1

Fit and compare with market data

Try it in Python

Fit on earlier bars and evaluate on a later period. Here the input is a generated test fixture. For a market comparison, use your observed OHLCV history.

from pricegenerator import Generate, GenerationConfig
from pricegenerator.calibration import Calibrate, ChronologicalSplit

history = Generate(GenerationConfig(seed=7, horizon=240))
training, holdout = ChronologicalSplit(history, holdout_fraction=0.25)
report = Calibrate(training, holdout)
print(report.profile.ToConfig().volatility)

pricegenerator.calibration

Fit three observable quantities on a training window of equally spaced bars. A later window tests how closely a new synthetic path matches selected features of the held-out history.

Profile

Versioned fit for equally spaced training bars. Records mean and population standard deviation of log(close/open), mean volume, and exactly which history supplied them. Price gaps between bars are outside this return definition.

Profile(
    schema_version: int,
    model: str,
    model_version: int,
    source_start: str,
    source_end: str,
    timeframe_seconds: float,
    source_rows: int,
    source_fingerprint: str,
    drift: float,
    volatility: float,
    volume_base: float,
    data_schema: str = 'datetime:UTC-ns;OHLCV:float64/v1',
    estimator: str = 'body-log-return-population-moments/volume-arithmetic-mean/v1',
    source_semantics: str = 'training-only; regular bars; candle-body returns exclude inter-bar price gaps',
)
Fields (14)
schema_version
Version of the serialized profile schema. This release accepts the integer 1.
model
Regime generator to fit. Select regime_v2 for continuous synthetic volume or regime_v3 for whole synthetic volume counts.
model_version
Implementation version corresponding to the chosen regime model identifier.
source_start
Timezone-aware ISO timestamp of the first training bar.
source_end
Timezone-aware ISO timestamp of the last training bar.
timeframe_seconds
Constant time between neighboring training bar timestamps, in seconds.
source_rows
Count of training bars used to estimate the profile, at least three.
source_fingerprint
SHA-256 digest of the complete canonical training OHLCV series.
drift
Mean per-bar log return from open to close, calculated as mean(ln(close)−ln(open)).
volatility
Population standard deviation of per-bar open-to-close log returns. The value is on the training bar’s timescale.
volume_base
Arithmetic mean of volume per training bar, in the data source’s volume unit. For regime_v3 it must lie between 1 and 2⁵³−1 inclusive.
data_schema
Identifier for the canonical input encoding, UTC nanosecond timestamps and binary64 OHLCV values.
estimator
Identifier for the versioned estimators of candle-body log-return moments and arithmetic mean volume.
source_semantics
Fixed description of the training sample and the within-bar return definition, which excludes inter-bar gaps.

Source ↗

Profile.ToDict

Return every profile field in a fresh JSON-compatible dictionary accepted by FromDict.

Profile.ToDict() -> dict

Source ↗

Profile.FromDict

Restore a Profile from its complete serialized fields. Raises ValueError for missing or unknown fields, unsupported versions, or inconsistent source windows and parameter values.

Profile.FromDict(values: Mapping) -> 'Profile'
Parameters (1)
values
Complete mapping produced by Profile.ToDict, including all version, estimator and source fields.

Source ↗

Profile.Reference

Return the hexadecimal SHA-256 digest of the complete serialized profile. Use it to identify this fit, including its source, when recording a scenario.

Profile.Reference() -> str

Source ↗

Profile.ToConfig

Return a new generation configuration for the same model with fitted drift, volatility and mean volume. Regime scale is set to 1, shock and wick-outlier probabilities to 0, and volume noise, persistence and return coupling to 0. The resulting volume is constant under the model’s bounds and rounding.

Profile.ToConfig(base: GenerationConfig | None = None) -> GenerationConfig
Parameters (1)
base
Optional GenerationConfig for the profile’s model. Unfitted choices such as price bounds and ordinary wick scale come from this configuration.

Source ↗

Profile.ManifestMetadata

Return the profile, its digest, the three fitted parameter names, the fixed restrictions and the parameters the fit cannot identify. This dictionary can be attached to a scenario manifest.

Profile.ManifestMetadata() -> dict

Source ↗

ExtractProfile

Estimate mean log(close/open), its population standard deviation, and arithmetic mean volume. Return a Profile for regime_v2 (default) or regime_v3. Requires at least three equally spaced training bars, strictly positive OHLC prices and a mean volume in the selected model’s supported range.

ExtractProfile(frame: pd.DataFrame, *, model: str = CONTINUOUS_MODEL_ID) -> Profile
Parameters (2)
frame
Regularly spaced training OHLCV with at least three bars and strictly positive open, high, low and close prices.
model
Regime generator to fit. Select regime_v2 for continuous synthetic volume or regime_v3 for whole synthetic volume counts.

Source ↗

ChronologicalSplit

Return two detached DataFrames in time order. The first floor(n·(1−holdout_fraction)) bars form the training window and all remaining bars go to the holdout window. Raises ValueError if either part contains fewer than three bars.

ChronologicalSplit(
    frame: pd.DataFrame,
    *,
    holdout_fraction: float = 0.25,
) -> tuple[pd.DataFrame, pd.DataFrame]
Parameters (2)
frame
Valid time-ordered OHLCV data from which to take two nonoverlapping windows.
holdout_fraction
Requested fraction of the sequence reserved at its end, strictly between 0 and 1. Rounding the training count down can make the actual holdout fraction slightly larger.

Source ↗

CalibrationReport

Fit, training and holdout comparison reports, plus one replayable scenario manifest for each window. Read the holdout metrics to evaluate a path generated with parameters learned from earlier bars.

CalibrationReport(
    profile: Profile,
    training: ComparisonReport,
    holdout: ComparisonReport,
    training_manifest_json: str,
    holdout_manifest_json: str,
)
Fields (5)
profile
Frozen profile estimated exclusively from the chronological training window.
training
Comparison between the historical training bars and a synthetic path generated for that window.
holdout
Comparison between the later observed bars and an independently seeded path using the training fit.
training_manifest_json
JSON replay manifest for the training-window synthetic path and its fitted profile metadata.
holdout_manifest_json
JSON replay manifest for the independently seeded holdout path and its training-derived metadata.

Source ↗

CalibrationReport.ToDict

Return the profile, separate comparison results, decoded manifests and a statement of the fit’s scope as a nested dictionary.

CalibrationReport.ToDict() -> dict

Source ↗

Calibrate

Fit the training window only, then generate one path for each window, starting at its observed open and using consecutive seeds. Return both comparisons and replay manifests. The training window must precede the holdout. Each needs at least three bars, the same regular whole-second cadence and a start aligned to a microsecond.

Calibrate(
    training: pd.DataFrame,
    holdout: pd.DataFrame,
    *,
    base: GenerationConfig | None = None,
    tolerances: Mapping[str, float] | None = None,
) -> CalibrationReport
Parameters (4)
training
Earlier, equally spaced OHLCV training window. The model learns its three moments exclusively from these bars.
holdout
Later OHLCV window at the same cadence. Its timestamps and first open initialize the holdout simulation, and its observations serve to evaluate the fit.
base
Optional GenerationConfig setting the model, starting seed and unfitted assumptions. With no base the fit uses regime_v2.
tolerances
Optional mapping from metric keys to finite, nonnegative absolute tolerances specified before evaluation. For example, 0.005 for log_return_std is an absolute difference in per-bar log-return volatility.

Source ↗

pricegenerator.evaluation

Compare a reference series with a synthetic one using seven named metrics. Set an absolute tolerance for each quantity of interest, or use block resampling to assess how precisely a separate sample mean is estimated.

MeanInterval

Percentile interval for a sample mean, with bounds in the observation units. Stores the seed, block length, resample count and NumPy version needed to repeat the estimate.

MeanInterval(
    lower: float,
    upper: float,
    confidence: float,
    resamples: int,
    seed: int,
    block_length: int,
    observations: int,
    method: str = 'moving-block percentile bootstrap of mean',
    rng: str = 'numpy.PCG64',
    numpy_version: str = np.__version__,
)
Fields (10)
lower
Lower empirical percentile of the resampled means, in the input units.
upper
Upper empirical percentile of the resampled means, in the input units.
confidence
Two-sided confidence level strictly between 0 and 1, expressed as a fraction.
resamples
Number of bootstrap samples used to estimate the interval, an integer of at least 100.
seed
Nonnegative integer seed for the NumPy PCG64 generator used in resampling.
block_length
Length of each contiguous sampled block in observations, from 1 to the input length inclusive.
observations
Number of original scalar observations. Each resample is trimmed to this length.
method
Name of the interval estimator, the moving-block percentile bootstrap of the mean.
rng
Resampling generator identifier, numpy.PCG64.
numpy_version
NumPy version used to generate the bootstrap samples and calculate percentiles.

Source ↗

MeanInterval.ToDict

Return the interval bounds and all resampling settings in a fresh dictionary.

MeanInterval.ToDict() -> dict

Source ↗

BootstrapMeanInterval

Estimate uncertainty in the arithmetic mean of at least two finite observations. Draw overlapping contiguous blocks with replacement, without wrapping at the ends. One observation per block gives independent resampling. Use longer blocks for dependence within each block. The bounds are empirical percentiles of the resampled means. Their coverage depends on the sample and block length.

BootstrapMeanInterval(
    values: Sequence[float],
    *,
    seed: int,
    confidence: float = 0.95,
    resamples: int = 2000,
    block_length: int = 1,
) -> MeanInterval
Parameters (5)
values
One-dimensional sequence of at least two finite numbers, in chronological order when working with time series.
seed
Nonnegative integer seed for the NumPy PCG64 generator used in resampling.
confidence
Two-sided confidence level strictly between 0 and 1, expressed as a fraction.
resamples
Number of bootstrap samples used to estimate the interval, an integer of at least 100.
block_length
Length of each contiguous sampled block in observations, from 1 to the input length inclusive.

Source ↗

MetricComparison

One metric from each series, their signed difference and an optional tolerance decision. A positive difference means the synthetic value is larger.

MetricComparison(
    name: str,
    reference: float | None,
    synthetic: float | None,
    difference: float | None,
    absolute_tolerance: float | None,
    within_tolerance: bool | None,
    reason: str | None,
)
Fields (7)
name
Key used in tolerances. Supported keys are log_return_mean, log_return_std, body_fraction_mean, volume_mean, squared_return_acf_lag1, volume_absolute_return_correlation and maximum_drawdown.
reference
Metric estimated on the reference series, or None when undefined.
synthetic
Metric estimated on the synthetic series in the same units, or None when undefined.
difference
Synthetic value minus reference value, in the original metric units.
absolute_tolerance
Optional limit on the magnitude of the difference, in the metric’s own units.
within_tolerance
True if the absolute difference is at or below the selected tolerance, False if larger, and None when an estimate or tolerance is absent.
reason
Explanation when one of the two metric values is undefined. Detailed causes are in the individual analyses.

Source ↗

ComparisonReport

Pair of independent OHLCV analyses with seven metric comparisons, input fingerprints and software versions. Each tolerance decision refers to its own metric and units.

ComparisonReport(
    reference_fingerprint: str,
    synthetic_fingerprint: str,
    reference_rows: int,
    synthetic_rows: int,
    metrics: tuple[MetricComparison, ...],
    reference_analysis_json: str,
    synthetic_analysis_json: str,
    environment_json: str,
    metric_version: str = 'comparison_v1',
    library_version: str = __version__,
)
Fields (10)
reference_fingerprint
SHA-256 fingerprint of the reference series after OHLCV validation.
synthetic_fingerprint
SHA-256 fingerprint of the synthetic series after OHLCV validation.
reference_rows
Number of bars analyzed in the reference sample.
synthetic_rows
Number of bars analyzed in the synthetic sample.
metrics
Seven named comparisons with values, signed differences and optional decisions.
reference_analysis_json
Full AnalysisReport for the reference sample, serialized as JSON.
synthetic_analysis_json
Full AnalysisReport for the synthetic sample, serialized as JSON.
environment_json
Recorded Python, platform, pandas and NumPy information serialized as JSON.
metric_version
Identifier for the comparison metric definitions, comparison_v1 in this release.
library_version
Version of PriceGenerator that produced the report.

Source ↗

ComparisonReport.ToDict

Return a nested dictionary with the metrics and two full analyses. The environment and both stored JSON analyses are decoded into objects.

ComparisonReport.ToDict() -> dict

Source ↗

Compare

Compare log-return mean and sample deviation, average body-to-range ratio, mean volume, lag-one squared-return autocorrelation, volume versus absolute-return correlation, and maximum price drawdown. Bars are analyzed independently in each series. Supply matching units and comparable sampling intervals. A tolerance decision is available when both estimates and its threshold exist.

Compare(
    reference: pd.DataFrame,
    synthetic: pd.DataFrame,
    *,
    tolerances: Mapping[str, float] | None = None,
) -> ComparisonReport
Parameters (3)
reference
Valid reference OHLCV DataFrame, commonly a historical sample. Its metrics are computed independently of the synthetic timestamps.
synthetic
Valid OHLCV DataFrame for the synthetic series. Use the same price and volume conventions as for the reference.
tolerances
Optional mapping from metric keys to finite, nonnegative absolute tolerances specified before evaluation. For example, 0.005 for log_return_std is an absolute difference in per-bar log-return volatility.

Source ↗