quantdata.dysanos.grid.rndysanos.torch_drift_change#

Path-level marginal-utility measure change for simulated Dysanos universes.

Each model step optimizes utility of the complete path P&L and produces one terminal density increment per simulated path. The same path density weights every time step in martingale and transaction-cost diagnostics.

All Monte Carlo variances use the population convention. Paths are the independent sampling units, so costs and reported Monte Carlo errors scale with sqrt(S_split) rather than sqrt(S_split * TAU).

class quantdata.dysanos.grid.rndysanos.torch_drift_change.DeterministicTimeAction(env, *, steps, instruments)[source]#

Bases: BaseModel

One unrestricted deterministic action vector for every path time.

base_value holds an optional per-instrument optimum b in optimizer coordinates. value is the subsequently optimized correction a. Their sum is the physical strategy after applying preconditioner.

set_preconditioner(rms, *, floor)[source]#

Use reciprocal return RMS as an optimizer-only coordinate scale.

set_preprocessed_action(physical_action)[source]#

Set the fixed per-instrument action b and reset correction a.

property physical_base_action: Tensor#
property physical_correction_action: Tensor#
forward(z)[source]#

Forward method.

Parameters:
  • data (dict) – Input data dictionary containing tensors for the model. The expected keys and tensor shapes depend on the specific model implementation.

  • training (bool, default False) – Whether the model is in training mode.

  • return_what (BaseModel.ReturnWhat, default ReturnWhat.LOSS_WEIGHT) – Specifies what the model should return. Options are: - ReturnWhat.LOSS_WEIGHT: return float loss (with gradient) and float weight (without gradient) for training. - ReturnWhat.VALUATION: return loss, weight and a dictionary of additional float metrics. - ReturnWhat.PATHWISE: return pathwise metrics as dictionary.

class quantdata.dysanos.grid.rndysanos.torch_drift_change.DysanosConfig(*, label, group='', user_version='0.1', utility='powexp', lmbda=1.0, oce_variant='simplified', action_type='network', deterministic_precondition=False, deterministic_preprocess=False, state_mode='full', zero_action_initialization=True, trade_spot=True, delta_hedged=True, cash_returns=False, learn_cost=True, cost_cond=None, cost_uncond=1.0, cost_prop=0.0001, seed=1231231, pf_config=FeedForwardConfig(activation='LeakyReLU', num_depth=2, num_width=100, use_bias=True), moment_config=FeedForwardConfig(activation='LeakyReLU', num_depth=2, num_width=100, use_bias=True), action_scale=1.0, drift_scale=1.0, sqr_scale=1.0, cash_floor=1e-08, density_floor=1e-12, denominator_floor=1e-12)[source]#

Bases: object

Logical OCE model and measure-change configuration.

group: str = ''#
user_version: str = '0.1'#
utility: str = 'powexp'#
lmbda: float = 1.0#
oce_variant: str = 'simplified'#
action_type: str = 'network'#
deterministic_precondition: bool = False#
deterministic_preprocess: bool = False#
state_mode: str = 'full'#
zero_action_initialization: bool = True#
trade_spot: bool = True#
delta_hedged: bool = True#
cash_returns: bool = False#
learn_cost: bool = True#
cost_cond: float | None = None#
cost_uncond: float = 1.0#
cost_prop: float = 0.0001#
seed: int = 1231231#
pf_config: FeedForwardConfig = FeedForwardConfig(activation='LeakyReLU', num_depth=2, num_width=100, use_bias=True)#
moment_config: FeedForwardConfig = FeedForwardConfig(activation='LeakyReLU', num_depth=2, num_width=100, use_bias=True)#
action_scale: float = 1.0#
drift_scale: float = 1.0#
sqr_scale: float = 1.0#
cash_floor: float = 1e-08#
density_floor: float = 1e-12#
denominator_floor: float = 1e-12#
property filename: str#
class quantdata.dysanos.grid.rndysanos.torch_drift_change.DysanosModel(env, *, geometry, config, previous_density=None)[source]#

Bases: BaseModel

Complete-path expected-utility model with an optional moment phase.

moment_outputs(z, dH)[source]#
moment_loss(data)[source]#
freeze_moments()[source]#

Freeze conditional moments before the main OCE optimizer can step.

main_parameters()[source]#
moment_parameters()[source]#
costs(z, dH, H, *, variance=None)[source]#
pathwise(data)[source]#
forward(data)[source]#

Return negative previous-density-weighted complete-path utility.

calibrate_unconditional(data, *, batch_size=None)[source]#

Calibrate population variance and global cost on full training data.

calibrate_density(data, *, batch_size=None)[source]#

Normalize the terminal density using the full training split only.

density()[source]#

Return a frozen self-contained callable for this trained stage.

class quantdata.dysanos.grid.rndysanos.torch_drift_change.RealizedDensity(env, *, action, drift, sqr, previous_density, config, bar_c, n_cost, path_normalizer, cash_offset, tail_cutoff, tail_boundary_fraction)[source]#

Bases: BaseModel

Frozen terminal density produced by one complete-path OCE step.

moments(z, dH)[source]#
costs(z, dH, H)[source]#
path_increment(z, dH, H, excluded_directions=None)[source]#
forward(z, dH, H, excluded_directions=None)[source]#

Forward method.

Parameters:
  • data (dict) – Input data dictionary containing tensors for the model. The expected keys and tensor shapes depend on the specific model implementation.

  • training (bool, default False) – Whether the model is in training mode.

  • return_what (BaseModel.ReturnWhat, default ReturnWhat.LOSS_WEIGHT) – Specifies what the model should return. Options are: - ReturnWhat.LOSS_WEIGHT: return float loss (with gradient) and float weight (without gradient) for training. - ReturnWhat.VALUATION: return loss, weight and a dictionary of additional float metrics. - ReturnWhat.PATHWISE: return pathwise metrics as dictionary.

path_density(z, dH, H, excluded_directions=None)[source]#
log_path_density(z, dH, H, excluded_directions=None)[source]#
class quantdata.dysanos.grid.rndysanos.torch_drift_change.TrainConfig(*, trn_batch_size=1024, val_batch_size=4096, validation_fraction=0.1, optimizer='AdamW', lr=0.001, final_lr=0.001, moment_lr=0.001, moment_final_lr=1e-05, action_initialization_epochs=0, action_initialization_lr=0.001, action_initialization_report=None, action_initialization_max_cap_fraction=0.25, weight_decay=0.0001, clip_grad_norm=None, compile=False, value_seconds=10.0, value_update=100, checkpoint_seconds=60.0, checkpoint_update=500, heavy_output_update=5000, early_stopping=False, minimum_epochs=0, minimum_moment_epochs=0, convergence_points=5, convergence_relative_tolerance=0.005, require_cost_band=False, cost_band_tolerance=0.0, scipy_gradient_tolerance=1e-10, scipy_function_tolerance=0.0, scipy_max_line_search_steps=50, checkpoint_root='~/.cache/rndysanos/oce')[source]#

Bases: object

Operational training configuration; epochs belongs to train().

trn_batch_size: int | None = 1024#
val_batch_size: int | None = 4096#
validation_fraction: float = 0.1#
optimizer: str = 'AdamW'#
lr: float = 0.001#
final_lr: float = 0.001#
moment_lr: float = 0.001#
moment_final_lr: float = 1e-05#
action_initialization_epochs: int = 0#
action_initialization_lr: float = 0.001#
action_initialization_report: str | None = None#
action_initialization_max_cap_fraction: float = 0.25#
weight_decay: float = 0.0001#
clip_grad_norm: float | None = None#
compile: bool = False#
value_seconds: float = 10.0#
value_update: int = 100#
checkpoint_seconds: float = 60.0#
checkpoint_update: int = 500#
heavy_output_update: int = 5000#
early_stopping: bool = False#
minimum_epochs: int = 0#
minimum_moment_epochs: int = 0#
convergence_points: int = 5#
convergence_relative_tolerance: float = 0.005#
require_cost_band: bool = False#
cost_band_tolerance: float = 0.0#
scipy_gradient_tolerance: float = 1e-10#
scipy_function_tolerance: float = 0.0#
scipy_max_line_search_steps: int = 50#
checkpoint_root: str = '~/.cache/rndysanos/oce'#
class quantdata.dysanos.grid.rndysanos.torch_drift_change.TrainingResult(model, density, training, validation, tracker, checkpoint_path, restarted, universe_index)[source]#

Bases: object

Completed model, frozen density, split outputs, and persisted history.

class quantdata.dysanos.grid.rndysanos.torch_drift_change.TrainingTracker(moment_epochs=<factory>, moment_batch_loss=<factory>, moment_drift_batch_loss=<factory>, moment_sqr_batch_loss=<factory>, moment_lr=<factory>, moment_elapsed_seconds=<factory>, moment_valuation_epochs=<factory>, moment_training_values=<factory>, moment_validation_values=<factory>, epochs=<factory>, batch_loss=<factory>, batch_utility=<factory>, lr=<factory>, gradient_norm=<factory>, nonfinite_gradient_count=<factory>, batch_elapsed_seconds=<factory>, valuation_epochs=<factory>, training_values=<factory>, validation_values=<factory>, restart_epochs=<factory>, elapsed_seconds=<factory>, moment_converged_epoch=None, main_converged_epoch=None, action_initialization_completed=False, action_initialization_first_loss=None, action_initialization_final_loss=None, action_initialization=None, deterministic_preprocessing=None, deterministic_optimizer=None)[source]#

Bases: object

Serializable training, valuation, gradient, and restart history.

moment_converged_epoch: int | None = None#
main_converged_epoch: int | None = None#
action_initialization_completed: bool = False#
action_initialization_first_loss: float | None = None#
action_initialization_final_loss: float | None = None#
action_initialization: dict[str, Any] | None = None#
deterministic_preprocessing: dict[str, Any] | None = None#
deterministic_optimizer: dict[str, Any] | None = None#
class quantdata.dysanos.grid.rndysanos.torch_drift_change.UnitDensity(env)[source]#

Bases: BaseModel

First-stage terminal path density, identically one.

forward(z, dH=None, H=None, excluded_directions=None)[source]#

Forward method.

Parameters:
  • data (dict) – Input data dictionary containing tensors for the model. The expected keys and tensor shapes depend on the specific model implementation.

  • training (bool, default False) – Whether the model is in training mode.

  • return_what (BaseModel.ReturnWhat, default ReturnWhat.LOSS_WEIGHT) – Specifies what the model should return. Options are: - ReturnWhat.LOSS_WEIGHT: return float loss (with gradient) and float weight (without gradient) for training. - ReturnWhat.VALUATION: return loss, weight and a dictionary of additional float metrics. - ReturnWhat.PATHWISE: return pathwise metrics as dictionary.

path_density(z, dH=None, H=None, excluded_directions=None)[source]#
log_path_density(z, dH=None, H=None, excluded_directions=None)[source]#
class quantdata.dysanos.grid.rndysanos.torch_drift_change.UniverseGeometry(samples, steps, expiries, strikes, state_variables, include_contract_features=True)[source]#

Bases: object

include_contract_features: bool = True#
property instruments: int#
property state_features: int#
quantdata.dysanos.grid.rndysanos.torch_drift_change.cap_objective_derivative(model, data, *, batch_size)[source]#

Return the full-split OCE-objective derivative by action cap.

The trainable parameter is the unconstrained raw_scale. Dividing its derivative by the softplus Jacobian reports the derivative with respect to the positive cap itself. Batches are weighted by path count so the result equals the derivative of the full-split mean objective.

quantdata.dysanos.grid.rndysanos.torch_drift_change.conditional_variance(drift, sqr)[source]#

Return max(SQR - DRIFT**2, 0) elementwise.

quantdata.dysanos.grid.rndysanos.torch_drift_change.cost_components(*, variance, H, bar_c, n_cost, cost_cond, cost_prop)[source]#

Return conditional, proportional, global, and effective costs.

quantdata.dysanos.grid.rndysanos.torch_drift_change.entropy_log_moment_loss(model, data, *, batch_size)[source]#

Return the stable full-split entropy objective.

Minimizing log E[D_prev exp(-lambda * path_pnl)] / lambda has exactly the same action minimizer as maximizing expected exponential utility. Unlike the raw exponential moment, its scale remains finite during an L-BFGS line search. The log-sum-exp is accumulated across all path batches before differentiation, so this is the exact full-training objective.

quantdata.dysanos.grid.rndysanos.torch_drift_change.initialize_no_arb_action(model, report_path, *, epochs, batch_size, lr, maximum_cap_fraction)[source]#

Warm-start an OCE policy from reference-fitted local basket directions.

quantdata.dysanos.grid.rndysanos.torch_drift_change.instrument_returns_and_values(*, dS, option_dS=None, dC, spot, C, delta, delta_hedged, cash_returns, cash_floor)[source]#

Construct dH and H for all four return/value modes.

Raw spot and option values must be positive. For a delta-hedged option, dH = dC - delta*option_dS is the net P&L while the traded gross notional is H = |C| + |delta*S|. option_dS may contain one spot change per option expiry; legacy one-step universes fall back to dS. Option and hedge notionals must not cancel when computing proportional transaction costs or cash-normalized returns.

quantdata.dysanos.grid.rndysanos.torch_drift_change.lower_tail_weights(values, weights, fraction)[source]#

Select exactly fraction of weight from the lowest sample values.

The returned multipliers are one below the empirical cutoff, zero above it, and a common fractional multiplier for observations tied at the cutoff. Selection is intentionally detached: it is the almost-everywhere gradient of the mechanically trimmed empirical expectation.

quantdata.dysanos.grid.rndysanos.torch_drift_change.oce_objective(*, action, dH, cost, previous_density, utility='powexp', lmbda=1.0, cash_offset=None)[source]#

Return the previous-density-weighted complete-path utility objective.

quantdata.dysanos.grid.rndysanos.torch_drift_change.prepare_universe(universe, *, config, env)[source]#

Validate and copy one prep_experiment() universe to Torch.

quantdata.dysanos.grid.rndysanos.torch_drift_change.scipy_deterministic_optimize(model, data, *, batch_size, maxiter, gradient_tolerance, function_tolerance, max_line_search_steps, objective_step=None)[source]#

Fit correction a in E[u(sum((a+b)*dH))] with SciPy.

quantdata.dysanos.grid.rndysanos.torch_drift_change.scipy_deterministic_preprocess(model, data, *, batch_size, maxiter, gradient_tolerance, function_tolerance, max_line_search_steps)[source]#

Fit every b[t, omega] through sum E[u(b*dH)].

quantdata.dysanos.grid.rndysanos.torch_drift_change.split_training_validation(data, validation_fraction)[source]#

Split paths once; no validation observation enters training calibration.

quantdata.dysanos.grid.rndysanos.torch_drift_change.train(universe_or_experiment, *, config, epochs, train_config=TrainConfig(trn_batch_size=1024, val_batch_size=4096, validation_fraction=0.1, optimizer='AdamW', lr=0.001, final_lr=0.001, moment_lr=0.001, moment_final_lr=1e-05, action_initialization_epochs=0, action_initialization_lr=0.001, action_initialization_report=None, action_initialization_max_cap_fraction=0.25, weight_decay=0.0001, clip_grad_norm=None, compile=False, value_seconds=10.0, value_update=100, checkpoint_seconds=60.0, checkpoint_update=500, heavy_output_update=5000, early_stopping=False, minimum_epochs=0, minimum_moment_epochs=0, convergence_points=5, convergence_relative_tolerance=0.005, require_cost_band=False, cost_band_tolerance=0.0, scipy_gradient_tolerance=1e-10, scipy_function_tolerance=0.0, scipy_max_line_search_steps=50, checkpoint_root='~/.cache/rndysanos/oce'), moment_epochs=None, previous_density=None, restart=False, just_load=False, env=None, universe_index=0, plot_sampler=False)[source]#

Train one model per independently simulated universe.

Passing an RNDysanosExperiment invokes the cached rndysanos.torch_prep.prep_experiment() data pipeline. When env is omitted, one GPU is acquired with DeviceLock for the duration of the complete training call, with a CPU fallback when CUDA is absent. A caller supplying a CUDA environment is responsible for holding its own device lock.

quantdata.dysanos.grid.rndysanos.torch_drift_change.validate_universe(universe)[source]#

Validate all required fields, shapes, floating dtypes, and finiteness.

quantdata.dysanos.grid.rndysanos.torch_drift_change.valuate(model, data, *, batch_size, split)[source]#

Run a full split valuation in path batches.

Standard deviations are population standard deviations. Paths are the independent sampling units, so err_dH divides by sqrt(S_split).

quantdata.dysanos.grid.rndysanos.torch_drift_change.valuate_with_cap_derivative(model, data, *, batch_size, split, include_objective_gradient=False)[source]#

Value a split and attach cap and optional strategy derivatives.

The complete parameter-gradient diagnostic is intentionally reserved for the converged/final epoch because it requires an additional backward pass over every path in the split.

quantdata.dysanos.grid.rndysanos.torch_drift_change.valuate_moments(model, data, *, batch_size, split)[source]#

Value the conditional first/second moments without using OCE costs.