Validate, save and replay OHLCV
Try it in Python
Keep a manifest alongside your test data. Replay reconstructs the candles and checks their fingerprint.
from pricegenerator import CreateManifest, Fingerprint, Generate, GenerationConfig, Replay
config = GenerationConfig(seed=7, horizon=96)
candles = Generate(config)
manifest = CreateManifest(config, candles)
assert Fingerprint(Replay(manifest)) == Fingerprint(candles)pricegenerator.market_data
Validate timestamps, open, high, low, close and volume before analysis. These rules also apply to imported market data, which may have zero or negative prices and fractional volume.
OHLCVError
ValueError subclass raised when a table or CSV violates the OHLCV contract, for example through a duplicate timestamp, negative volume or a high below the closing price.
class OHLCVError(ValueError)
TimeframeNanoseconds
Convert an interval in seconds to a positive integer number of nanoseconds. Fractional seconds are valid if the result is exact and fits a pandas Timedelta. Otherwise raise OHLCVError.
TimeframeNanoseconds(timeframe_seconds)
Parameters (1)
timeframe_seconds- Positive interval in seconds, given as a real number. An exact whole number of nanoseconds must fit in a signed 64-bit duration.
TimestampRange
Return a UTC pandas DatetimeIndex starting at the specified instant with one entry per period. Zero periods returns an empty index. Naive start times, negative counts and times outside the nanosecond range raise OHLCVError.
TimestampRange(start, periods, timeframe_seconds)
Parameters (3)
start- Timestamp of the first candle, with an explicit time zone. The output timeline uses UTC.
periods- Nonnegative integer number of timestamps. The starting timestamp counts as the first entry when the count is positive.
timeframe_seconds- Spacing of the requested timestamps in seconds. Fractional seconds are allowed down to exact nanoseconds.
ValidateOHLCV
Return an independent six-column DataFrame. Times must be unique and strictly increasing. High and low must enclose the candle body, volume must be nonnegative and all values finite. Optional interval checks enforce the chosen gap policy. Violations raise OHLCVError.
ValidateOHLCV(frame, *, assume_timezone=None, timeframe_seconds=None, allow_gaps=True)
Parameters (4)
frame- A pandas DataFrame with exactly datetime, open, high, low, close and volume. The time values belong in a column and the volume unit should match the source series.
assume_timezone- Time zone to apply to timestamps without an offset. Leave unset for timezone-aware values. Mixed aware and naive timestamps, ambiguous local times and nonexistent times are rejected.
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.
ToDatetimeIndex
Validate the candles and return a new DataFrame indexed by UTC datetime, with open, high, low, close and volume as columns. Invalid data raise OHLCVError under the same rules as ValidateOHLCV.
ToDatetimeIndex(frame, *, assume_timezone=None, timeframe_seconds=None, allow_gaps=True)
Parameters (4)
frame- A pandas DataFrame with exactly datetime, open, high, low, close and volume. The time values belong in a column and the volume unit should match the source series.
assume_timezone- Time zone to apply to timestamps without an offset. Leave unset for timezone-aware values. Mixed aware and naive timestamps, ambiguous local times and nonexistent times are rejected.
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.
Module constants
OHLCV_COLUMNS= ('datetime', 'open', 'high', 'low', 'close', 'volume')- Canonical order of the six OHLCV columns used to validate tables and to read and write CSV headers.
VALUE_COLUMNS= OHLCV_COLUMNS[1:]- The five numeric columns hold open, high, low, close and volume. Each is normalized to float64 by validation.
ISO_DATETIME_PATTERN= re.compile('\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(?:\\.\\d{1,9})?(?:Z|[+-]\\d{2}:\\d{2})?\\Z')- An ISO timestamp string uses T and includes seconds, up to nine fractional digits and optionally Z or an explicit offset. Omitting the offset requires assume_timezone for validation.
pricegenerator.io
Exchange six-column OHLCV files with a fixed CSV header, UTC timestamps and a period as the decimal separator.
ReadCSV
Read a UTF-8 comma-separated file or text stream and return a validated DataFrame. The header must be exactly datetime,open,high,low,close,volume. A malformed row, ambiguous timestamp or invalid candle raises OHLCVError.
ReadCSV(source, *, assume_timezone=None, timeframe_seconds=None, allow_gaps=True)
Parameters (4)
source- Path to a UTF-8 OHLCV CSV or an already open text stream positioned at the header.
assume_timezone- Time zone to apply to timestamps without an offset. Leave unset for timezone-aware values. Mixed aware and naive timestamps, ambiguous local times and nonexistent times are rejected.
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.
WriteCSV
Validate the table, then write one CSV header and UTC timestamps with nanosecond precision. Returns None. Integer volume formatting rejects fractional values with OHLCVError. A caller-owned text stream stays open.
WriteCSV(
frame,
destination,
*,
assume_timezone=None,
timeframe_seconds=None,
allow_gaps=True,
volume_as_count=False,
)
Parameters (6)
frame- A pandas DataFrame with exactly datetime, open, high, low, close and volume. The time values belong in a column and the volume unit should match the source series.
destination- Output CSV path or an already open text stream for writing. The caller retains ownership of a supplied stream.
assume_timezone- Time zone to apply to timestamps without an offset. Leave unset for timezone-aware values. Mixed aware and naive timestamps, ambiguous local times and nonexistent times are rejected.
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.
volume_as_count- Write whole volumes without a decimal point. If a volume has a fractional part, enabling this option raises OHLCVError instead of rounding it.
Module constants
NUMBER_PATTERN= re.compile('[+-]?(?:\\d+(?:\\.\\d*)?|\\.\\d+)(?:[eE][+-]?\\d+)?\\Z')- Accepted CSV numeric syntax for the price and volume columns, including a sign, a decimal point or scientific notation. Validation then checks that the parsed number is finite.
pricegenerator.scenario
Record the inputs to a regime-model run and check that replay reproduces the same candle values.
Environment
Return a dictionary with the Python version and implementation, platform string, and installed pandas and NumPy versions used to verify a recorded run.
Environment() -> dict[str, str]
Fingerprint
Return the SHA-256 digest of the validated candle values. It includes UTC timestamps as nanoseconds and the exact binary64 prices and volumes. CSV spelling and the original DataFrame index do not enter the digest.
Fingerprint(data: pd.DataFrame) -> str
Parameters (1)
data- OHLCV DataFrame whose exact timestamps, prices and volumes are used to compute a fingerprint.
CreateManifest
Return a dictionary recording the full configuration, model, random generator, software environment and separate hashes for the scenario identity and candle values. If data is supplied its hash is recorded directly. Otherwise the function generates the candles first.
CreateManifest(
config: GenerationConfig,
data: pd.DataFrame | None = None,
*,
metadata: Mapping[str, Any] | None = None,
) -> dict[str, Any]
Parameters (3)
config- GenerationConfig instance defining the model and candle series, including its length, time grid and seed.
data- Optional existing OHLCV output. Its fingerprint is recorded as supplied. Omit to generate the output directly from config.
metadata- Optional JSON object for provenance. If provided, profile_reference must be a lowercase 64-character SHA-256 digest and becomes part of the scenario identity.
Replay
Regenerate a regime-model path and return its verified DataFrame. An incompatible version, altered scenario identity or different output digest raises ValueError. Disabling strict_environment relaxes only the comparison with the current environment.
Replay(manifest: Mapping[str, Any], *, strict_environment: bool = True) -> pd.DataFrame
Parameters (2)
manifest- The complete saved manifest for this model, including its settings, version and fingerprints. Use the dictionary returned by the corresponding creation function.
strict_environment- True requires an exact match to the recorded environment. False attempts replay in the current environment and still requires the recorded library version, matching scenario identity and an identical output digest.
Module constants
MANIFEST_VERSION= 1- Format version for recording and replaying regime-model scenarios. It is checked independently of the library release and model identifier.