Python API reference / 2.2.1

Describe a price series

Try it in Python

Measure close-to-close returns over a test series. Set acf_lags to study dependence up to that many observed bars.

from pricegenerator import Analyze, Generate, GenerationConfig

report = Analyze(Generate(GenerationConfig(seed=42, horizon=120)), acf_lags=5)
print(report.simple_returns[-3:])

pricegenerator.analysis

Measure what happened in one OHLCV series. Inspect close-to-close returns, candle bodies and wicks, volume and price drawdowns. Each undefined statistic carries its reason.

Estimate

One numerical estimate. Read value when defined and reason when the sample or numerical domain prevents calculation.

Estimate(value: float | None, reason: str | None = None)
Fields (2)
value
Finite numeric estimate in the statistic’s units, or None when undefined.
reason
Explanation when the value is undefined, otherwise None.

Source ↗

OutlierEventSummary

Counts and observed frequencies for two aligned event flags. The union counts a bar once if either flag is set, and the intersection counts bars with both flags.

OutlierEventSummary(
    definition: str,
    trials: int,
    upper_count: int,
    lower_count: int,
    either_count: int,
    both_count: int,
    upper_frequency: Estimate,
    lower_frequency: Estimate,
    either_frequency: Estimate,
    both_frequency: Estimate,
)
Fields (10)
definition
Nonempty description of the upper and lower events as defined by the caller.
trials
Number of paired upper and lower observations, including pairs in which neither event occurred.
upper_count
Number of observations where the upper event occurred, including simultaneous events.
lower_count
Number of observations where the lower event occurred, including simultaneous events.
either_count
Number of pairs with at least one event.
both_count
Number of pairs where upper and lower events both occurred.
upper_frequency
Upper-event count divided by the total paired observations.
lower_frequency
Lower-event count divided by the total paired observations.
either_frequency
Fraction of all paired observations with at least one event.
both_frequency
Fraction of all paired observations in which both events occurred.

Source ↗

OutlierEventSummary.ToDict

Return a fresh dictionary with the event definition, trial and event counts, and each frequency’s value or reason.

OutlierEventSummary.ToDict() -> dict

Source ↗

Distribution

Marginal statistics for the finite values of one variable. Counts record how much data contributed, while the estimates describe location, dispersion, shape and tails in the observed sample.

Distribution(
    name: str,
    count: int,
    excluded: int,
    mean: Estimate,
    variance: Estimate,
    standard_deviation: Estimate,
    skewness: Estimate,
    excess_kurtosis: Estimate,
    minimum: Estimate,
    maximum: Estimate,
    quantiles: tuple[tuple[float, Estimate], ...],
    lower_tail_mean: Estimate,
    upper_tail_mean: Estimate,
    tukey_outlier_fraction: Estimate,
    three_sigma_fraction: Estimate,
)
Fields (15)
name
Label of the measured series, such as log_returns, range or volume.
count
Number of finite observations used in the distribution.
excluded
Number of supplied observations omitted because they were missing or nonfinite.
mean
Arithmetic mean of the retained values in the original measurement units.
variance
Sample variance with denominator n−1, in squared input units. Requires at least two observations.
standard_deviation
Sample standard deviation with denominator n−1, in the original units.
skewness
Adjusted Fisher sample skewness. Requires at least three observations with nonzero variance.
excess_kurtosis
Adjusted Fisher excess kurtosis, with the normal-distribution reference at zero. Requires at least four observations with nonzero variance.
minimum
Smallest retained observation in the input units.
maximum
Largest retained observation in the input units.
quantiles
Pairs of probability level and linearly interpolated quantile at 1%, 5%, 25%, 50%, 75%, 80%, 95% and 99%.
lower_tail_mean
Arithmetic mean of observations at or below the sample’s 5th percentile.
upper_tail_mean
Arithmetic mean of observations at or above the sample’s 95th percentile.
tukey_outlier_fraction
Fraction outside Q1−1.5·IQR and Q3+1.5·IQR, where IQR is the interquartile range.
three_sigma_fraction
Fraction whose absolute deviation from the mean exceeds three population standard deviations (denominator n).

Source ↗

ProportionBand

Lower and upper bounds for an event probability, computed from the observed proportion and Hoeffding’s inequality under independent Bernoulli trials.

ProportionBand(count: int, trials: int, confidence: float, lower: float, upper: float)
Fields (5)
count
Integer number of event occurrences, from zero to the number of trials inclusive.
trials
Positive integer number of independent Bernoulli trials.
confidence
Two-sided confidence level strictly between 0 and 1, expressed as a fraction.
lower
Lower bound for the event probability, limited to a minimum of zero.
upper
Upper bound for the event probability, limited to a maximum of one.

Source ↗

PricePathSummary

Endpoints, price movement, candle directions and total volume over the observed bars. Up and down directions compare each close with its own open.

PricePathSummary(
    start_datetime: str,
    end_datetime: str,
    elapsed_seconds: float,
    first_close: float,
    last_close: float,
    close_range: Estimate,
    endpoint_change: Estimate,
    endpoint_return: Estimate,
    up_candles: int,
    down_candles: int,
    doji_candles: int,
    longest_up_run: int,
    longest_down_run: int,
    total_volume: Estimate,
)
Fields (14)
start_datetime
UTC timestamp of the first observed bar, in ISO 8601 format.
end_datetime
UTC timestamp of the last observed bar, in ISO 8601 format.
elapsed_seconds
Elapsed seconds from first bar timestamp to last. A one-bar window spans zero seconds on this measure.
first_close
First observed closing price, in the input price units.
last_close
Last observed closing price, in the input price units.
close_range
Highest close minus lowest close, in price units.
endpoint_change
Last close minus first close, in price units.
endpoint_return
Last close divided by first close, minus 1. Undefined when the first close is zero.
up_candles
Count of bars with close greater than open.
down_candles
Count of bars with close less than open.
doji_candles
Count of bars with exactly equal open and close prices.
longest_up_run
Longest sequence of consecutive bars closing above their own opens. Doji ends a run.
longest_down_run
Longest sequence of consecutive bars closing below their own opens. Doji ends a run.
total_volume
Sum of reported volumes over all bars, in the input’s volume unit.

Source ↗

AnalysisReport

Full analysis of one validated OHLCV series, including price-path, distribution and dependence statistics. Returns and drawdowns are fractions, so 0.10 denotes 10%.

AnalysisReport(
    candle_count: int,
    cadence_regular: bool,
    distributions: tuple[Distribution, ...],
    simple_returns: tuple[float | None, ...],
    log_returns: tuple[float | None, ...],
    return_reasons: tuple[str | None, ...],
    log_return_reasons: tuple[str | None, ...],
    return_acf: tuple[Estimate, ...],
    absolute_return_acf: tuple[Estimate, ...],
    squared_return_acf: tuple[Estimate, ...],
    drawdown: tuple[float | None, ...],
    maximum_drawdown: Estimate,
    maximum_drawdown_duration_bars: Estimate,
    volume_absolute_return_correlation: Estimate,
    volume_range_correlation: Estimate,
    up_candle_fraction: Estimate,
    zero_volume_fraction: Estimate,
    path: PricePathSummary,
    notes: tuple[str, ...],
)
Fields (19)
candle_count
Total number of validated candles in the analyzed series.
cadence_regular
True when all adjacent timestamp differences are equal. A series of one or two bars also satisfies this check.
distributions
Statistics for returns, bodies, wicks, ranges, their candle-range fractions and volume. Return samples start at the second bar.
simple_returns
Aligned close-to-close returns Cₜ/Cₜ₋₁−1. The first entry, zero denominators and nonfinite results are marked None.
log_returns
Aligned differences ln(Cₜ)−ln(Cₜ₋₁). Each pair needs positive closes. The first entry is None.
return_reasons
Bar-aligned explanations for undefined simple returns, with None where a return was computed.
log_return_reasons
Bar-aligned explanations for undefined log returns, with None where a return was computed.
return_acf
Sample autocorrelations of simple close-to-close returns at observation lags 1 through acf_lags.
absolute_return_acf
Sample autocorrelations of absolute simple returns at successive observation lags.
squared_return_acf
Sample autocorrelations of squared simple returns at successive observation lags.
drawdown
Price drawdown per bar as 1−close/running_peak_close. The first close sets the initial peak. If any close is nonpositive the entire series is undefined.
maximum_drawdown
Largest peak-to-trough drop in closing price, as a nonnegative fraction. Measuring a strategy drawdown would require its equity curve and trading results.
maximum_drawdown_duration_bars
Longest consecutive count of closes strictly below their running peak. Includes an unfinished drawdown at the end of the series.
volume_absolute_return_correlation
Pearson correlation of a bar’s volume with its absolute simple close-to-close return, from the second bar onward using valid pairs.
volume_range_correlation
Pearson correlation of volume with high−low on the same bar. Requires at least two valid pairs and variation on both sides.
up_candle_fraction
Fraction of all bars closing above their opens.
zero_volume_fraction
Fraction of all bars reporting zero volume.
path
Summary of times, endpoint prices, directional runs and volume for the complete observed path.
notes
Text documenting estimator conventions, admissible observations and the interpretation of results.

Source ↗

AnalysisReport.ToDict

Return a fresh nested dictionary with the original numerical values, undefined estimates and their explanations.

AnalysisReport.ToDict() -> dict

Source ↗

AnalysisReport.ToJSON

Serialize the full report as compact JSON with sorted keys. Missing estimates become null, and nonfinite numeric literals are rejected.

AnalysisReport.ToJSON() -> str

Source ↗

AnalysisReport.Summary

Return a tuple of human-readable English lines for display or a text report. It includes formatted statistics, sample conventions and reasons for missing estimates.

AnalysisReport.Summary() -> tuple[str, ...]

Source ↗

Describe

Return sample statistics for a numeric sequence, excluding None and nonfinite values. Variance uses n−1, quantiles use linear interpolation and the tail means include observations on the empirical 5th and 95th percentile boundaries.

Describe(values, name: str = 'values') -> Distribution
Parameters (2)
values
Iterable of numeric observations, optionally including None and nonfinite values, which are counted as excluded.
name
Label stored with the resulting distribution.

Source ↗

SummarizeOutlierEvents

Return counts and frequencies for upper, lower, either and simultaneous events defined by the caller. Supply equally long sequences of booleans and a nonempty definition. An empty sample yields zero counts and undefined frequencies.

SummarizeOutlierEvents(upper_flags, lower_flags, *, definition: str) -> OutlierEventSummary
Parameters (3)
upper_flags
One strict True/False flag per observation indicating an upper event.
lower_flags
One strict True/False flag per observation indicating a lower event, aligned with upper_flags.
definition
Nonempty description of the upper and lower events as defined by the caller.

Source ↗

ProportionInterval

Return a two-sided Hoeffding interval for an independent Bernoulli event rate. The half-width is √(ln(2/(1−confidence))/(2·trials)). Bounds are clipped to [0, 1]. Requires at least one trial and a valid event count.

ProportionInterval(count: int, trials: int, *, confidence: float = 0.99) -> ProportionBand
Parameters (3)
count
Integer number of event occurrences, from zero to the number of trials inclusive.
trials
Positive integer number of independent Bernoulli trials.
confidence
Two-sided confidence level strictly between 0 and 1, expressed as a fraction.

Source ↗

ProbabilityTolerance

Return an absolute tolerance for an observed proportion from independent Bernoulli trials. It equals the Hoeffding half-width capped at 1. Choose sample size and confidence before observing outcomes.

ProbabilityTolerance(trials: int, *, confidence: float = 0.99) -> float
Parameters (2)
trials
Positive integer number of independent Bernoulli trials.
confidence
Two-sided confidence level strictly between 0 and 1, expressed as a fraction.

Source ↗

ACF

Return one autocorrelation estimate per observation lag, starting at lag 1. The series is centered on its overall mean and every lag uses the same full-sample denominator. A missing or nonfinite observation invalidates all lags. Constant series and lags at least as long as the sample are undefined.

ACF(values, lags: int = 10) -> tuple[Estimate, ...]
Parameters (2)
values
Ordered numeric series. A missing or nonfinite value prevents estimation across all requested lags.
lags
Nonnegative integer specifying the largest lag, measured in observations. Zero returns an empty tuple.

Source ↗

Analyze

Return an AnalysisReport for at least one validated candle. Simple and log returns use adjacent observed closes. Undefined returns retain their bar positions. Drawdown uses strictly positive closes and starts at the first close. Irregular series retain their observed cadence.

Analyze(frame, *, acf_lags: int = 10) -> AnalysisReport
Parameters (2)
frame
OHLCV DataFrame with at least one bar and timezone-aware timestamps, which are validated and converted to UTC before analysis.
acf_lags
Largest observation lag for the return, absolute-return and squared-return autocorrelations. Zero skips the lag sequences.

Source ↗ Available through pricegenerator.Analyze

pricegenerator.fuzzy_diagnostics

Describe observed volatility and trading activity relative to their baselines using four experimental Mamdani rules. The result includes a stress index and the strength of each rule. Requires the fuzzy extra and Python 3.13 or later within the supported versions.

RegimeTermGrade

Membership of one input in an ordinary or elevated fuzzy term, together with the coordinate actually evaluated after capping the observed ratio at 2.

RegimeTermGrade(variable: str, term: str, coordinate: float, grade: float)
Fields (4)
variable
Input variable name, volatility or activity.
term
Fuzzy term evaluated for this input, ordinary or elevated.
coordinate
Input ratio used by the membership function after limiting its upper value to 2.
grade
Membership degree for this input and term, between 0 and 1 inclusive.

Source ↗

RegimeRuleFiring

Evidence for one rule, including the strength of its premise, its weight and its resulting activation of the output term.

RegimeRuleFiring(
    name: str,
    consequent: str,
    antecedent_grade: float,
    weight: float,
    firing_strength: float,
)
Fields (5)
name
Stable rule identifier in the four-rule market stress profile.
consequent
Output term activated by the rule, calm, watch or stress.
antecedent_grade
Degree to which both input conditions hold, taken as the smaller input membership degree.
weight
Rule weight, equal to 1 in this version of the profile.
firing_strength
Effective activation after weighting, which clips the rule’s output membership function.

Source ↗

RegimeDiagnostic

Result of evaluating one observed pair of ratios. Stores the descriptive stress index, the original inputs, membership grades and all four rule activations for inspection.

RegimeDiagnostic(
    profile_id: str,
    fuzzyroutines_version: str,
    method: str,
    volatility_ratio: float,
    activity_ratio: float,
    score: float,
    input_grades: tuple[RegimeTermGrade, ...],
    rules: tuple[RegimeRuleFiring, ...],
)
Fields (8)
profile_id
Identifier of the fixed rule set and membership functions, relative-market-stress-v1.
fuzzyroutines_version
Installed FuzzyRoutines version used for inference, recorded with the score.
method
Inference method recorded by the backend for the centroid calculation.
volatility_ratio
Originally supplied volatility relative to its baseline, retained even when the inference coordinate is capped at 2.
activity_ratio
Originally supplied trading activity relative to its baseline, retained even when the inference coordinate is capped at 2.
score
Centroid of the aggregated fuzzy output on [0, 1]. Larger values indicate higher relative stress under these four rules. The scale represents a descriptive index.
input_grades
Membership records for both observed variables in the ordinary and elevated terms.
rules
All four rule evaluations, in profile declaration order, including their activation strengths.

Source ↗

RegimeDiagnostic.ToDict

Return a new JSON-compatible dictionary containing the index and its complete rule and input trace.

RegimeDiagnostic.ToDict() -> dict

Source ↗

DiagnoseRegime

Supply two observed ratios relative to positive baselines. Four max–min Mamdani rules give a descriptive stress index on [0, 1] and their firing strengths. Coordinates above 2 saturate at 2. Invalid ratios raise ValueError. Missing or incompatible fuzzy dependencies raise ImportError.

DiagnoseRegime(volatility_ratio: float, activity_ratio: float) -> RegimeDiagnostic
Parameters (2)
volatility_ratio
Observed volatility divided by a positive reference volatility, measured on the same cadence. Supply a finite nonnegative ratio. A value of 1 means the reference level.
activity_ratio
Observed trading activity divided by a positive baseline of the same kind, for example mean volume per bar divided by reference mean volume. Supply a finite nonnegative ratio.

Source ↗

Module constants

PROFILE_ID = 'relative-market-stress-v1'
Versioned name of the fixed four-rule relative market stress profile.
FUZZYROUTINES_VERSION = '2.1.0'
Exact FuzzyRoutines version required by the diagnostic engine (2.1.0).