Python API reference / 2.2.1

Generate candles

Try it in Python

Generate 240 hourly candles in batches of 48. Batch size controls memory use and preserves the price path for a fixed seed.

from pricegenerator import GenerateChunks, GenerationConfig

config = GenerationConfig(seed=42, horizon=240)
print([len(batch) for batch in GenerateChunks(config, chunk_size=48)])

pricegenerator.config

Settings shared by the two regime models. Choose a candle interval, price dynamics and the unit convention for synthetic volume.

GenerationConfig

Immutable settings for a regime-model path of 1 to 1,000,000 candles. Drift and volatility are per candle. The default regime_v3 yields whole volume counts. Choose regime_v2 for continuous volume. Invalid bounds or times raise ValueError on construction.

GenerationConfig(
    seed: int = 0,
    horizon: int = 150,
    start: datetime = datetime(2000, 1, 1, tzinfo=timezone.utc),
    timeframe_seconds: int = 3600,
    model: str = COUNT_MODEL_ID,
    initial_price: float = 100.0,
    price_floor: float = 1e-06,
    price_ceiling: float = 1000000000000.0,
    drift: float = 0.0,
    volatility: float = 0.01,
    regime_persistence: float = 0.95,
    regime_scale: float = 3.0,
    shock_probability: float = 0.01,
    shock_scale: float = 5.0,
    wick_scale: float = 0.5,
    wick_outlier_probability: float = 0.01,
    wick_outlier_scale: float = 5.0,
    volume_base: float = 1000.0,
    volume_sigma: float = 0.25,
    volume_return_coupling: float = 1.0,
    volume_persistence: float = 0.5,
    volume_ceiling: float = 1000000000000.0,
)
Fields (22)
seed
Integer seed for the private random generator. Reuse it with the same model, settings and environment to reproduce the same path.
horizon
Number of candles to generate, from 1 through 1,000,000. The final timestamp is start plus (horizon − 1) intervals.
start
First candle's time, with an explicit time zone and at most microsecond precision. The whole timeline must fit from 1678-01-01 inclusive to 2262-01-01 exclusive in UTC.
timeframe_seconds
Whole seconds between generated candles, from 1 to 9,223,372,036. Changing this interval changes the time grid. Drift and volatility are specified separately per candle.
model
Select regime_v3 for whole synthetic volume counts or regime_v2 for continuous volume. Both use the same price model.
initial_price
First candle's opening price. It must lie between price_floor and price_ceiling, inclusive.
price_floor
Lower price boundary, at least 1e-100 and below the upper boundary. Proposed closes reflect at the boundary in log space. Lower wicks stop at the boundary.
price_ceiling
Upper price boundary, above the lower boundary and at most 1e100. Proposed closes reflect in log space. Upper wicks stop at the boundary.
drift
Per-candle drift in log-return units, between −2 and 2. Noise, shocks and the price bounds can change the realized return.
volatility
Standard deviation of the ordinary log-return innovation per candle in the calm regime, from 0 to 2. It also sets the scale for wicks and shocks.
regime_persistence
Probability from 0 to 1 of retaining the current volatility regime on a candle. The starting state is calm and the first switch is tested before generating the first candle.
regime_scale
Multiplier on ordinary volatility in the stressed regime, from 1 to 100. At 1, ordinary volatility is equal in both regimes.
shock_probability
Independent probability from 0 to 1 of adding a Gaussian shock to a candle's log return.
shock_scale
Multiplier from 0 to 100. A shock's log-return standard deviation equals volatility × shock_scale, using base volatility in either regime.
wick_scale
Multiplier from 0 to 100 on current regime volatility for the size of each ordinary wick in log-price units. At zero, high and low coincide with the body edges.
wick_outlier_probability
Probability from 0 to 1 of applying the outlier multiplier to a wick. Upper and lower wicks are drawn independently of each other and of return shocks.
wick_outlier_scale
Multiplier from 0 to 100 applied to the wick selected as an outlier. Values above 1 lengthen that wick before it is clipped to the price boundary.
volume_base
Baseline synthetic volume per candle before log noise and price activity. In regime_v3 it must be at least 1, but it need not itself be a whole number. It cannot exceed volume_ceiling.
volume_sigma
Scale of the persistent random component of log volume, from 0 to 2. At zero, that component contributes no variation.
volume_return_coupling
Coefficient from 0 to 10 on the candle's price activity in log volume. Activity is the absolute realized log return divided by current regime volatility, capped at 10 and set to zero when volatility is zero.
volume_persistence
Fraction from 0 to 1 of the previous log-volume noise carried into the next candle. At 1, the initial zero noise is retained and no new noise enters.
volume_ceiling
Maximum synthetic volume per candle. For regime_v3 this must be an integer no greater than 2⁵³ − 1 so the count remains exact in float64. For regime_v2, base and ceiling must lie within [1e-100, 1e100].

Source ↗ Available through pricegenerator.GenerationConfig

GenerationConfig.ToDict

Return a new JSON-compatible dictionary of all generation settings, including defaults and an ISO 8601 start time in UTC.

GenerationConfig.ToDict() -> dict[str, Any]

Source ↗

GenerationConfig.FromDict

Build a validated GenerationConfig from a mapping. Omitted settings use constructor defaults. An ISO 8601 start must include its time zone and use at most six fractional digits. Unknown keys and invalid settings raise ValueError.

GenerationConfig.FromDict(configuration: Mapping[str, Any]) -> 'GenerationConfig'
Parameters (1)
configuration
Mapping of GenerationConfig field names to values. Omitted fields take their defaults. For a saved configuration use the dictionary returned by ToDict.

Source ↗

Module constants

CONTINUOUS_MODEL_ID = 'regime_v2'
Identifier of regime_v2, the regime model with continuous synthetic volume.
COUNT_MODEL_ID = 'regime_v3'
Identifier of regime_v3, the default model producing a whole synthetic count for each candle's volume.
REGIME_MODEL_VERSIONS = {CONTINUOUS_MODEL_ID: 2, COUNT_MODEL_ID: 3}
Maps regime_v2 and regime_v3 identifiers to their integer algorithm revisions, 2 and 3.
MAX_VOLUME_COUNT = 2 ** 53 - 1
Largest permitted regime_v3 volume ceiling, 2⁵³ − 1. This bound keeps every generated integer count exactly representable in float64.

pricegenerator.generation

Generate a complete synthetic OHLCV series on a regular UTC timeline from a single configuration.

Generate

Return a pandas DataFrame with datetime, open, high, low, close and volume. The UTC grid has no missing intervals. Prices and volume use float64, including whole volume counts in regime_v3. Each call initializes its own random generator from the seed. Passing another configuration type raises TypeError.

Generate(config: GenerationConfig) -> pd.DataFrame
Parameters (1)
config
GenerationConfig instance defining the model and candle series, including its length, time grid and seed.

Source ↗ Available through pricegenerator.Generate

Module constants

OHLCV_COLUMNS = ['datetime', 'open', 'high', 'low', 'close', 'volume']
Column names in generation order. UTC datetime comes first, then open, high, low, close and volume.

pricegenerator.models

The row generator behind the regime models. Use it when you need OHLCV values one candle at a time and manage the random number generator yourself.

GenerateRows

Yield one tuple (open, high, low, close, volume) per candle using the supplied random generator. Each candle opens at the previous close. Log returns combine drift, regime-dependent noise and an occasional shock. Upper and lower wicks are sampled separately. Volume varies with the size of the realized move and persistent noise. The iterator omits timestamps.

GenerateRows(
    config: GenerationConfig,
    rng: Random,
) -> Iterator[tuple[float, float, float, float, float]]
Parameters (2)
config
GenerationConfig specifying all candle dynamics and the number of rows. This low-level iterator consumes the separately supplied rng.
rng
An initialized random.Random instance. Its existing state is consumed as rows are requested. For the standard seeded path, pass Random(config.seed).

Source ↗

Module constants

RNG_ID = 'python.random.Random/MT19937'
Identifier of the Python random.Random generator using MT19937. Scenario manifests record it to identify the generator required for replay.

pricegenerator.streaming

Generate long regime-model paths in memory-sized chunks or write successive OHLCV frames to a single CSV file.

GenerateChunks

Yield validated DataFrames with at most chunk_size candles each. Joining the chunks in order yields the same candle values and times as Generate for the same configuration. A nonpositive or non-integer chunk size raises ValueError when iteration starts.

GenerateChunks(config, *, chunk_size=10000)
Parameters (2)
config
GenerationConfig instance defining the model and candle series, including its length, time grid and seed.
chunk_size
Maximum number of candles in each yielded frame. A positive integer, default 10,000. The final chunk can be shorter.

Source ↗ Available through pricegenerator.GenerateChunks

WriteCSVChunks

Write successive candle tables to one CSV and return None. The writer validates each chunk and the join between chunks before atomically replacing the destination. A failed write preserves the previous file. An empty input writes just the header.

WriteCSVChunks(chunks, destination, *, timeframe_seconds=None, allow_gaps=True)
Parameters (4)
chunks
Iterable of OHLCV DataFrames in time order. Nonempty chunks must follow one another under the same interval and gap policy.
destination
Destination file path. Its parent directory must exist. After all checks, the completed temporary file replaces this path in one operation.
timeframe_seconds
Candle interval expressed in seconds. When validating data, a specified interval also determines which gaps are permitted.
allow_gaps
With a declared timeframe, True permits whole missing intervals and False requires exactly one interval between adjacent candles. False requires timeframe_seconds. Without a timeframe only chronological order is checked for spacing.

Source ↗ Available through pricegenerator.WriteCSVChunks

pricegenerator.registry

Look up the available models, the questions each can answer and the evidence to check before using their output.

ModelInfo

Immutable description of a model's version, random generator, supported settings, use cases, limitations and validation criteria. Obtain registered descriptions with ListModels or GetModel.

ModelInfo(
    model: str,
    version: int,
    rng: str,
    status: str,
    supported_parameters: tuple[str, ...],
    suitability: tuple[str, ...],
    limitations: tuple[str, ...],
    required_validation: tuple[str, ...],
)
Fields (8)
model
Exact identifier of the generator, such as regime_v3 or bootstrap_v1.
version
Integer revision of this model's algorithm. For example, regime_v3 has revision 3. The package release is versioned independently.
rng
Random number generator identifier recorded for the model. The value is none for the deterministic scripted model.
status
Maturity label assigned by the registry. In this release all four models have experimental status.
supported_parameters
Names of configuration fields accepted by the model.
suitability
Research or testing uses the model is designed to serve.
limitations
Known constraints on how to interpret the synthetic candles and what they can establish about a market.
required_validation
Checks to perform for the intended application, such as OHLCV invariants, temporal dependence or validation on held-out market data.

Source ↗

ModelInfo.ToDict

Return an independent JSON-compatible dictionary. Collections of parameters, use cases, limitations and checks become lists.

ModelInfo.ToDict() -> dict

Source ↗

ListModels

Return a tuple of four ModelInfo entries for regime_v3, regime_v2, bootstrap_v1 and scripted_v1. Each entry describes one experimental model.

ListModels() -> tuple[ModelInfo, ...]

Source ↗

GetModel

Look up a ModelInfo by its exact model identifier. An unknown identifier, including a historical runtime outside the registry, raises ValueError.

GetModel(model: str) -> ModelInfo
Parameters (1)
model
Exact identifier of the generator, such as regime_v3 or bootstrap_v1.

Source ↗