quantdata.dysanos.grid.rndysanos#

Risk-neutral Dysanos experiments and OCE measure changes.

class quantdata.dysanos.grid.rndysanos.ConditionalTailConfig(*, label, state_features, instruments, training_paths, group='', user_version='1.0', seed=83771, tail_path_counts=(0.1, 1.0, 2.0, 10.0), network_config=FeedForwardConfig(activation='LeakyReLU', num_depth=2, num_width=200, use_bias=True))[source]#

Bases: object

Logical geometry and tail levels for the conditional quantile model.

tail_path_counts specifies tail masses in units of independent paths. For example, with 50,000 training paths, 10 means a lower-tail probability of 10 / 50_000. Values below one path are retained as requested metadata but use one path as their effective empirical level.

group: str = ''#
user_version: str = '1.0'#
seed: int = 83771#
tail_path_counts: tuple[float, ...] = (0.1, 1.0, 2.0, 10.0)#
network_config: FeedForwardConfig = FeedForwardConfig(activation='LeakyReLU', num_depth=2, num_width=200, use_bias=True)#
property filename: str#
property requested_tail_probabilities: tuple[float, ...]#
property effective_tail_path_counts: tuple[float, ...]#
property effective_tail_probabilities: tuple[float, ...]#
property unique_effective_tail_probabilities: tuple[float, ...]#
property requested_to_unique_level: tuple[int, ...]#
level_metadata()[source]#

Return requested and effective probability conventions.

class quantdata.dysanos.grid.rndysanos.ConditionalTailQuantileModel(env, *, config, state_mean, state_scale)[source]#

Bases: BaseModel

State-only monotone lower quantiles for long and short returns.

unique_quantiles(z)[source]#

Return monotone quantiles at empirically distinct tail levels.

forward(z)[source]#

Return requested levels, tying levels below one empirical path.

loss(z, returns)[source]#

Return joint normalized pinball loss at unique effective levels.

training_loss(z, returns)[source]#

Compiled training kernel after data preparation established invariants.

cvar_scores(z, returns)[source]#

Return requested lower-CVaR scores using effective finite-sample levels.

class quantdata.dysanos.grid.rndysanos.ConditionalTailTracker(epochs=<factory>, batch_loss=<factory>, learning_rate=<factory>, gradient_norm=<factory>, valuation_epochs=<factory>, training_values=<factory>, validation_values=<factory>, restart_epochs=<factory>, converged_epoch=None)[source]#

Bases: object

Compact restartable optimization and full-valuation history.

converged_epoch: int | None = None#
class quantdata.dysanos.grid.rndysanos.ConditionalTailTrainConfig(*, batch_size=512, valuation_batch_size=2048, lr=0.001, final_lr=1e-06, weight_decay=0.0001, compile=True, value_update=5000, checkpoint_update=10000, minimum_epochs=50000, convergence_points=5, convergence_relative_tolerance=0.002, convergence_log_coverage_tolerance=0.1, checkpoint_root='~/.cache/rndysanos/conditional-tail')[source]#

Bases: object

Operational configuration for conditional-tail optimization.

batch_size: int = 512#
valuation_batch_size: int = 2048#
lr: float = 0.001#
final_lr: float = 1e-06#
weight_decay: float = 0.0001#
compile: bool = True#
value_update: int = 5000#
checkpoint_update: int = 10000#
minimum_epochs: int = 50000#
convergence_points: int = 5#
convergence_relative_tolerance: float = 0.002#
convergence_log_coverage_tolerance: float = 0.1#
checkpoint_root: str = '~/.cache/rndysanos/conditional-tail'#
class quantdata.dysanos.grid.rndysanos.ConditionalTailTrainingResult(model, training, validation, tracker, checkpoint_path, restarted)[source]#

Bases: object

Trained model, complete final valuations, and checkpoint metadata.

class quantdata.dysanos.grid.rndysanos.DirectArbitrageConfig(*, label, state_features, instruments, group='', user_version='0.1', epsilon=0.01, delta=0.01, numerical_tolerance=0.0001, smooth_temperature=0.0025, tail_fraction=0.01, downside_weight=10.0, tail_weight=100.0, overlap_weight=1.0, mean_reward_weight=0.1, discovery_fraction=0.05, constraint_ramp_fraction=0.45, initial_trade_fraction=0.01, mask_arbitrage_candidates=False, objective='simplex-soft-hit', cap_weight=1.0, seed=70771, network_config=FeedForwardConfig(activation='LeakyReLU', num_depth=2, num_width=100, use_bias=True))[source]#

Bases: object

Logical policy, economic threshold, and constrained-loss configuration.

group: str = ''#
user_version: str = '0.1'#
epsilon: float = 0.01#
delta: float = 0.01#
numerical_tolerance: float = 0.0001#
smooth_temperature: float = 0.0025#
tail_fraction: float = 0.01#
downside_weight: float = 10.0#
tail_weight: float = 100.0#
overlap_weight: float = 1.0#
mean_reward_weight: float = 0.1#
discovery_fraction: float = 0.05#
constraint_ramp_fraction: float = 0.45#
initial_trade_fraction: float = 0.01#
mask_arbitrage_candidates: bool = False#
objective: str = 'simplex-soft-hit'#
cap_weight: float = 1.0#
seed: int = 70771#
network_config: FeedForwardConfig = FeedForwardConfig(activation='LeakyReLU', num_depth=2, num_width=100, use_bias=True)#
property filename: str#
class quantdata.dysanos.grid.rndysanos.DirectArbitrageTrainConfig(*, batch_size=1024, valuation_batch_size=4096, lr=0.001, final_lr=1e-06, weight_decay=0.0001, compile=True, value_update=10000, checkpoint_update=10000, checkpoint_root='~/.cache/rndysanos/direct-arbitrage')[source]#

Bases: object

Operational configuration for direct-policy optimization.

batch_size: int = 1024#
valuation_batch_size: int = 4096#
lr: float = 0.001#
final_lr: float = 1e-06#
weight_decay: float = 0.0001#
compile: bool = True#
value_update: int = 10000#
checkpoint_update: int = 10000#
checkpoint_root: str = '~/.cache/rndysanos/direct-arbitrage'#
class quantdata.dysanos.grid.rndysanos.DirectArbitrageTrainingResult(policy, training, validation, tracker, checkpoint_path, restarted)[source]#

Bases: object

Trained policy, complete valuations, and restart metadata.

class quantdata.dysanos.grid.rndysanos.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.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.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.LongShortSimplexPolicy(env, *, config, state_mean, state_scale)[source]#

Bases: BaseModel

State-only long/short direction and independent scalar exposure gate.

forward(z, 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.

class quantdata.dysanos.grid.rndysanos.RadialL1Policy(env, *, config, state_mean, state_scale)[source]#

Bases: BaseModel

V2.0 policy with one unbounded signed output and radial L1 clipping.

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

Return the feasible signed action and feasible raw L1 norm.

class quantdata.dysanos.grid.rndysanos.LocalArbitrageConfig(*, neighbors=10240, query_batch_size=2048, instrument_batch_size=10, roundoff_multiplier=32.0, state_scale_floor=1e-06)[source]#

Bases: object

Logical and batching configuration for the exact local mask.

neighbors: int = 10240#
query_batch_size: int = 2048#
instrument_batch_size: int = 10#
roundoff_multiplier: float = 32.0#
state_scale_floor: float = 1e-06#
class quantdata.dysanos.grid.rndysanos.LocalArbitrageProgress(*, split, processed_states, total_states, long_only_candidate_states, short_only_candidate_states, both_direction_candidate_states)[source]#

Bases: object

Cumulative disjoint candidate-state counts during mask valuation.

class quantdata.dysanos.grid.rndysanos.LocalTailConfig(*, state_mode, neighbors=1024, instrument_candidate_neighbors=8192, tail_ranks=(1, 2, 10, 20, 50), signal_thresholds=(2.0, 3.0), query_batch_size=3584, instrument_batch_size=20, roundoff_multiplier=32.0, state_scale_floor=1e-06)[source]#

Bases: object

Configuration for an exact uniform adaptive-neighbour estimator.

neighbors: int = 1024#
instrument_candidate_neighbors: int = 8192#
tail_ranks: tuple[int, ...] = (1, 2, 10, 20, 50)#
signal_thresholds: tuple[float, ...] = (2.0, 3.0)#
query_batch_size: int = 3584#
instrument_batch_size: int = 20#
roundoff_multiplier: float = 32.0#
state_scale_floor: float = 1e-06#
property local_tail_probabilities: tuple[float, ...]#
property zero_event_upper_probability_95: float#

Exact iid binomial upper bound after zero events in neighbors draws.

class quantdata.dysanos.grid.rndysanos.LocalTailProgress(*, split, processed_states, total_states, states_with_any_long_candidate, states_with_any_short_candidate, long_only_candidate_states, short_only_candidate_states, both_direction_candidate_states)[source]#

Bases: object

Cumulative one-sided-support counts for a valuation in progress.

class quantdata.dysanos.grid.rndysanos.RNDysanosExperiment(grid_strikes=100, num_nms=20, num_alpha=5, use_matrix_exp=False, bandwidth=0.2, num_steps=10, num_samples=100000, pcnt_validation=0.1, clip_grad_norm=None, cnt_universe=1, universe_seed_offset=0)[source]#

Bases: object

grid_strikes: int = 100#

The number of strikes per expiry we are matching the market with

num_nms: int = 20#

The nunber of strikes per expiry we are simulating

num_alpha: int | None = 5#
use_matrix_exp: bool = False#
bandwidth: float = 0.2#
num_steps: int = 10#
num_samples: int = 100000#
pcnt_validation: float = 0.1#
clip_grad_norm: float | None = None#
cnt_universe: int = 1#
universe_seed_offset: int = 0#
class quantdata.dysanos.grid.rndysanos.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.SignAccumulator(instruments)[source]#

Bases: object

Streaming per-instrument signs and path-clustered moments.

update(values, tolerance)[source]#

Accumulate one path batch with shape (S, TAU, J).

arrays()[source]#

Return complete per-instrument arrays using population moments.

class quantdata.dysanos.grid.rndysanos.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.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.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.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.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.apply_direction_mask(action, excluded_directions)[source]#

Zero long/short action components excluded by arb(z; omega).

quantdata.dysanos.grid.rndysanos.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.conditional_variance(drift, sqr)[source]#

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

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

Return conditional, proportional, global, and effective costs.

quantdata.dysanos.grid.rndysanos.cost_adjusted_direction_candidates(neighbor_returns, query_cost, neighbor_roundoff)[source]#

Return long/short candidate flags with shape (B, 2, J).

quantdata.dysanos.grid.rndysanos.delta_hedged_option_returns(*, dC, delta, dS)[source]#

Return dC - delta*dS without including the spot instrument.

quantdata.dysanos.grid.rndysanos.delta_hedged_option_cost_notionals(*, C, delta, spot)[source]#

Return gross traded notionals |C| + |delta*spot| for options.

quantdata.dysanos.grid.rndysanos.delta_hedged_roundoff_band(*, C, dC, delta, dS, multiplier=32.0)[source]#

Return a conservative absolute error band for float32 hedged returns.

dC was itself formed by subtracting two float32 option values. The scale therefore includes both reconstructed endpoint values and the hedge term, rather than the possibly cancellation-dominated final dH.

quantdata.dysanos.grid.rndysanos.direct_arbitrage_loss(*, long, short, dH, cost, config, penalty_scale=1.0)[source]#

Reward threshold hits while heavily penalizing mean and tail downside.

quantdata.dysanos.grid.rndysanos.effective_cost(data, *, bar_c, cost_prop, conditional_variance_model, n_cost, batch_size)[source]#

Materialize max(c_cond, bar_c, c_prop) without retaining gradients.

quantdata.dysanos.grid.rndysanos.empirical_lower_cvar(values, *, tail_probability, dim=0)[source]#

Return exact lower expected shortfall of an empirical distribution.

Fractional probability mass at the boundary order statistic is included. Therefore every level at or below 1 / observations is exactly the sample minimum; a fractional observation cannot reveal a lower value.

quantdata.dysanos.grid.rndysanos.entropy_diagonal_mean_variance_action(*, drift, variance, cost, lmbda, cap, variance_floor)[source]#

Return the diagonal-Gaussian entropy/Kelly strategy approximation.

For conditionally Gaussian, cross-instrument independent returns, the entropy-OCE certainty equivalent for one instrument is a*mu - abs(a)*cost - lmbda*a**2*variance/2. Its optimizer is the cost-soft-thresholded ratio of conditional mean to conditional variance.

quantdata.dysanos.grid.rndysanos.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.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.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.initialize_entropy_action(model, data, *, epochs, batch_size, lr)[source]#

Fit the action network to the conditional diagonal entropy solution.

quantdata.dysanos.grid.rndysanos.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.lower_cvar_score(*, quantiles, returns, tail_probabilities)[source]#

Return the lower-CVaR variational score per observation and output.

Conditional expectation of this score is maximized by a lower quantile; at that optimum it equals lower expected shortfall.

quantdata.dysanos.grid.rndysanos.lower_quantile_pinball(*, quantiles, returns, tail_probabilities, normalize_levels=True)[source]#

Return normalized pinball loss and its direction/level/instrument means.

Parameters:
  • quantiles (Tensor) – Shape (..., 2, L, J) with long/short as the direction axis.

  • returns (Tensor) – Shape (..., J). Long and short targets are constructed internally.

  • tail_probabilities (Tensor) – One-dimensional tensor of the L effective lower-tail levels.

  • normalize_levels (bool) – Divide each level by its tail probability. This does not change any population minimizer, but prevents the least-extreme level from mechanically dominating all rarer levels in a joint model.

quantdata.dysanos.grid.rndysanos.local_neighbor_statistics(neighbor_returns, neighbor_roundoff, *, tail_ranks, neighbor_log_weights=None)[source]#

Return positive/negative parts and signed lower-tail order statistics.

Inputs have shape (queries, neighbours, instruments). Direction zero is the long return and direction one is the negated return.

quantdata.dysanos.grid.rndysanos.local_state_normalization(training_state, *, scale_floor, path_weights=None)#

Return training-only weighted population location and scale.

quantdata.dysanos.grid.rndysanos.moment_signal_statistics(drift, second_moment, *, g=3.0)[source]#

Measure sampled states satisfying abs(mu) > g * sigma.

The variance is the population conditional variance max(E[Y**2|z] - E[Y|z]**2, 0). Zero predicted variance is reported separately because an infinite signal ratio can indicate inconsistent moment-network outputs rather than an economic opportunity.

quantdata.dysanos.grid.rndysanos.net_return(*, long, short, dH, cost)[source]#

Return net P&L for separate long and short allocations.

quantdata.dysanos.grid.rndysanos.net_return_roundoff_band(values, cost, *, multiplier=32.0)[source]#

Return a float32 arithmetic band for +/- values - cost.

quantdata.dysanos.grid.rndysanos.normalize_state(state, *, mean, scale)[source]#

Normalize a state array without changing its shape or float32 dtype.

quantdata.dysanos.grid.rndysanos.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.objective_gradient_diagnostics(model, data, *, batch_size)[source]#

Return the exact full-split OCE gradient at the current strategy.

Path batches are weighted by their fraction of the split, so the result is the gradient of the full path-level mean rather than a mean of batch norms. A nonzero cap derivative can be a boundary/KKT effect while the complete action-parameter gradient directly measures stationarity of the fitted strategy.

quantdata.dysanos.grid.rndysanos.population_standard_error(total, total_sqr, observations)[source]#

Return population standard deviation divided by sqrt(observations).

quantdata.dysanos.grid.rndysanos.pack_direction_mask(mask)[source]#

Pack the option axis of a bool (..., 2, J) candidate mask.

quantdata.dysanos.grid.rndysanos.prepare_raw_option_tail_data(universe, *, env)[source]#

Prepare state, raw option price changes, values, and roundoff bands.

quantdata.dysanos.grid.rndysanos.prepare_delta_hedged_local_data(universe, *, roundoff_multiplier=32.0)[source]#

Return delta-hedged option returns, roundoff bands, and state fields.

quantdata.dysanos.grid.rndysanos.prep_experiment(experiment, *, plot_sampler=True)[source]#
quantdata.dysanos.grid.rndysanos.prepare_universe(universe, *, config, env)[source]#

Validate and copy one prep_experiment() universe to Torch.

quantdata.dysanos.grid.rndysanos.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.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.rank_imbalance(accumulator, *, strikes, count=20)[source]#

Return options with the largest requested raw imbalance count.

quantdata.dysanos.grid.rndysanos.rank_no_arbitrage_candidates(long, short, *, strikes, count=20)[source]#

Rank directions by fewest losses, then largest lower mean bound.

quantdata.dysanos.grid.rndysanos.reduced_option_state(data, *, geometry, mode, instrument=0)[source]#

Return xstate or one option’s (xstate, log-strike, expiry).

quantdata.dysanos.grid.rndysanos.shared_instrument_metric_diagnostics(data, *, training_paths, geometry, scale_floor, sample_states=4096)[source]#

Test whether every option produces the same standardized strike metric.

When log strikes differ only by instrument-specific constants, their standardized values are identical. Expiries are constant and therefore have zero distance. In that case one exact neighbour graph is valid for every separately estimated option.

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

Split paths once; no validation observation enters training calibration.

quantdata.dysanos.grid.rndysanos.split_tail_data(data, *, validation_fraction)[source]#

Split paths contiguously so validation never enters normalization/training.

quantdata.dysanos.grid.rndysanos.signed_returns(returns)[source]#

Return explicit long dC and short -dC outcomes.

quantdata.dysanos.grid.rndysanos.state_normalization(data, *, batch_size)[source]#

Return training-only state mean and population standard deviation.

quantdata.dysanos.grid.rndysanos.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.train_conditional_tail(training, validation, *, config, train_config, epochs, env, restart=False, progress=None)[source]#

Fit, checkpoint, and fully value a conditional raw-dC tail model.

quantdata.dysanos.grid.rndysanos.train_direct_policy(training, validation, *, config, train_config, epochs, env, restart=False)[source]#

Train a direct policy and atomically checkpoint resumable optimizer state.

quantdata.dysanos.grid.rndysanos.unconditional_cost(data, *, cost_uncond, batch_size)[source]#

Return the full-training population standard error per instrument.

quantdata.dysanos.grid.rndysanos.unpack_direction_mask(packed, *, instruments)[source]#

Unpack a uint8 (..., 2, ceil(J/8)) mask on its Torch device.

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

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

quantdata.dysanos.grid.rndysanos.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.valuate_conditional_tail(model, data, *, batch_size, split, full=True, example_count=10)[source]#

Value calibration and one-sided lower-tail candidates on a full split.

quantdata.dysanos.grid.rndysanos.valuate_local_tail(*, reference_state, reference_returns, reference_roundoff, reference_log_weights=None, query_state, query_returns, query_roundoff, query_log_weights=None, reference_instrument_feature=None, query_instrument_feature=None, config, split, leave_one_out, leave_one_out_reference_indices=None, progress=None, progress_interval_seconds=30.0)[source]#

Value all query states with an exact adaptive-neighbour box kernel.

quantdata.dysanos.grid.rndysanos.valuate_local_arbitrage_mask(*, reference_state, reference_returns, reference_roundoff, query_state, query_returns, query_cost, query_roundoff, config, split, leave_one_out, candidate_sink=None, progress=None, progress_interval_seconds=30.0)[source]#

Evaluate the training-fitted exact kNN arb(z; omega) function.

quantdata.dysanos.grid.rndysanos.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.valuate_moments(model, data, *, batch_size, split)[source]#

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

quantdata.dysanos.grid.rndysanos.valuate_policy(policy, data, *, batch_size, split)[source]#

Value a policy and conservatively certify it using independent paths.

quantdata.dysanos.grid.rndysanos.v2_arbitrage_loss(*, action, raw_l1, dH, cost, config, penalty_scale=1.0)[source]#

V2.0 mean/downside/CVaR loss with radial-output conditioning penalty.

Modules#