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:
BaseModelOne unrestricted deterministic action vector for every path time.
base_valueholds an optional per-instrument optimumbin optimizer coordinates.valueis the subsequently optimized correctiona. Their sum is the physical strategy after applyingpreconditioner.- 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
band reset correctiona.
- 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, defaultReturnWhat.LOSS_WEIGHT) – Specifies what the model should return. Options are: -ReturnWhat.LOSS_WEIGHT: return floatloss(with gradient) and floatweight(without gradient) for training. -ReturnWhat.VALUATION: returnloss,weightand 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:
objectLogical OCE model and measure-change configuration.
- 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)#
- class quantdata.dysanos.grid.rndysanos.torch_drift_change.DysanosModel(env, *, geometry, config, previous_density=None)[source]#
Bases:
BaseModelComplete-path expected-utility model with an optional moment phase.
- calibrate_unconditional(data, *, batch_size=None)[source]#
Calibrate population variance and global cost on full training data.
- 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:
BaseModelFrozen terminal density produced by one complete-path OCE step.
- 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, defaultReturnWhat.LOSS_WEIGHT) – Specifies what the model should return. Options are: -ReturnWhat.LOSS_WEIGHT: return floatloss(with gradient) and floatweight(without gradient) for training. -ReturnWhat.VALUATION: returnloss,weightand a dictionary of additional float metrics. -ReturnWhat.PATHWISE: return pathwise metrics as dictionary.
- 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:
objectOperational training configuration;
epochsbelongs totrain().
- class quantdata.dysanos.grid.rndysanos.torch_drift_change.TrainingResult(model, density, training, validation, tracker, checkpoint_path, restarted, universe_index)[source]#
Bases:
objectCompleted 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:
objectSerializable training, valuation, gradient, and restart history.
- class quantdata.dysanos.grid.rndysanos.torch_drift_change.UnitDensity(env)[source]#
Bases:
BaseModelFirst-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, defaultReturnWhat.LOSS_WEIGHT) – Specifies what the model should return. Options are: -ReturnWhat.LOSS_WEIGHT: return floatloss(with gradient) and floatweight(without gradient) for training. -ReturnWhat.VALUATION: returnloss,weightand a dictionary of additional float metrics. -ReturnWhat.PATHWISE: return pathwise metrics as dictionary.
- class quantdata.dysanos.grid.rndysanos.torch_drift_change.UniverseGeometry(samples, steps, expiries, strikes, state_variables, include_contract_features=True)[source]#
Bases:
object
- 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)] / lambdahas 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
dHandHfor all four return/value modes.Raw spot and option values must be positive. For a delta-hedged option,
dH = dC - delta*option_dSis the net P&L while the traded gross notional isH = |C| + |delta*S|.option_dSmay contain one spot change per option expiry; legacy one-step universes fall back todS. 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
fractionof 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
ainE[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]throughsum 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
RNDysanosExperimentinvokes the cachedrndysanos.torch_prep.prep_experiment()data pipeline. Whenenvis omitted, one GPU is acquired withDeviceLockfor 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_dHdivides bysqrt(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.