Skip to content

Trading guard: an online model that stops when the market jumps

← Finance

A desk watches a stock index at every tick. An online model predicts the next return from the last one, and a guard stops it when the last tick moved more than 3%: the model does not learn from that tick and answers a fallback of zero, which means no order. The orders that remain go to a pre-trade checker that refuses a size, a price, a duplicate, a rate or a notional that is out of its limits. A robot controller whose joint speed jumps is handled the same way, in the last section.

The ticks flagged by the guard on a stock index with three shocks, for 25 guard thresholds and 25 shock sizes: a guard at 3% flags only the ticks after the big jumps.

1. A first example: four ticks of a stock index

Four returns of a stock index arrive one tick at a time. The guard stops the model when a return is above 3%.

from dense_armor.roles.safety import SafeEstimator
from dense_armor.core.online.linear.glm import LinearRegression
from dense_armor.core.online.optim import SGD

model = LinearRegression(optimizer=SGD(lr=0.1), feature_keys=["ret_n"])
safe = SafeEstimator(model=model, guard=lambda x: abs(x["ret"]) > 0.03, fallback=0.0)
for ret in (0.004, -0.002, 0.05, 0.003):
    x = {"ret": ret, "ret_n": ret / 0.01}
    print(safe.is_flagged(x), round(safe.predict_one(x), 4))
    safe.learn_one(x, ret / 0.01)
print(safe.n_blocked_)
False 0.0
False 0.0736
True 0.0
False 0.0382
2

Count by hand. The returns 0.4%, −0.2% and 0.3% are below 3%: the guard does not flag them and the model predicts (0.0 on the first tick, because it has not learned yet) and learns. The return 5% is above 3%: the guard flags the tick, the prediction is the fallback 0.0 and the model does not learn from it. n_blocked_ is 2 because the flagged tick was stopped twice, once in predict_one and once in learn_one.

2. Tick by tick: predict, order, learn

On 300 ticks the index follows its last return (a momentum of 0.3) plus a small noise, and three jumps hit it at ticks 80, 170 and 240. At each tick the model predicts the next return from the last one, the guard looks at the last return, the pre-trade checker validates the order, and then the model learns from the return that arrived.

import random
from dense_armor.roles.safety import SafeEstimator, HealthMonitor
from dense_armor.core.online.linear.glm import LinearRegression
from dense_armor.core.online.optim import SGD
from dense_armor.core.finance import PreTradeChecker
from dense_armor.core.signals.stats.moments import RunningMoments

rng, norm = random.Random(42), RunningMoments(feature="ret")
model = LinearRegression(optimizer=SGD(lr=5e-3), l2=1e-3, intercept=True, feature_keys=["ret_n"])
safe = SafeEstimator(model=model, guard=lambda x: abs(x["ret"]) > 0.03, fallback=0.0, monitor=HealthMonitor(window=50, warmup=20))
checker = PreTradeChecker(max_notional=100_000.0, max_size=0.5, price_band=0.02, max_orders=40, window_s=60.0, duplicate_window_s=1.0)
shocks, prev, ref, last, flagged, reasons = {80: 0.06, 170: -0.05, 240: 0.04}, 100.0, 100.0, 0.0, [], {}
for i in range(300):
    std = norm.std if norm.std > 1e-6 else 1.0
    x = {"ret": last, "ret_n": last / std}
    pred = safe.predict_one(x)
    if safe.is_flagged(x):
        flagged.append(i)
    elif abs(pred) > 0.2:
        d = checker.check("acct1", "buy" if pred > 0 else "sell", min(abs(pred), 0.5), prev, ref, t=float(i))
        reasons[d.reason] = reasons.get(d.reason, 0) + 1
    ret = 0.3 * last + rng.gauss(0, 0.004) + shocks.get(i, 0.0)
    price = prev * (1 + ret)
    safe.learn_one(x, ret / std, t=float(i))
    norm.update({"ret": ret})
    ref, prev, last = 0.9 * ref + 0.1 * price, price, ret
print(flagged, safe.n_blocked_, reasons)
[81, 171, 241] 6 {'ok': 86, 'price_band': 40, 'rate': 6}

A stock index over 300 ticks with three jumps: the ticks the guard flagged, the orders that were sent and the orders the pre-trade checker refused.

The guard flags exactly the ticks 81, 171 and 241, the tick after each jump: it looks at the last return, so it stops the model one tick after the jump, and n_blocked_ is 6 because each flagged tick is stopped twice (prediction and learning). Of the other orders, 86 were approved by the checker and 46 refused: 40 for price_band (after a jump the reference price, which follows the price slowly, stays more than 2% away for a while) and 6 for rate (more than 40 orders approved in the last 60 seconds).

The picture follows the same 300 ticks for 25 guard thresholds between 0.5% and 8% and 25 sizes of the three shocks between 1% and 10%; each point of the surface is the number of ticks the guard flagged. With the guard at 3.0% the shocks of 5.88% are flagged on 3 ticks and the shocks of 2.12% on none. With the guard at 1.12% and shocks of 5.88% the guard flags 10 ticks, because ordinary ticks now cross it too; with the guard at 0.5% and shocks of 1.0% it flags 65, and with the guard at 8.0% and shocks of 10.0% it flags 3.

3. What each piece does

Component Role
LinearRegression Online model, one gradient step per sample; budget_s = 1e-3, memory_class = "O(1)"
SGD(lr=5e-3) Optimizer with a small learning rate to avoid weight explosion
RunningMoments(feature="ret") Online mean and variance of the return, to normalize the feature
SafeEstimator Wraps the model with a guard and a fallback; if the guard flags a sample, the model does not learn and the output is the fallback
HealthMonitor Health state: warming_up, nominal, drifting, degraded
PreTradeChecker Five pre-order controls in this order (size, price band, duplicate, rate, notional) from SEC Rule 15c3-5 (c)(1)

4. Parameters

SafeEstimator(model, guard=None, fallback=None, monitor=None)

Parameter Meaning Default
model Estimator to wrap none
guard Callable x -> bool, True flags the sample None (no guard)
fallback Value returned while flagged None
monitor Optional HealthMonitor a default HealthMonitor()

PreTradeChecker(max_notional, max_size, price_band, max_orders, window_s, duplicate_window_s)

Parameter Meaning Default
max_notional Maximum open notional per account none
max_size Maximum size per order none
price_band Maximum deviation of the order price from the reference price none
max_orders Maximum orders approved per account in the window none
window_s Time window for the rate, in seconds none
duplicate_window_s Window for the duplicate check, in seconds none

All six parameters of PreTradeChecker are required.

5. The same system on a robot

A joint controller receives the velocity qd of a joint at every sample. An online model predicts the expected movement of the joint; if the sensor shows a jump above 0.5, the guard returns the fallback (zero torque) and the motor does not move.

from dense_armor.roles.safety import SafeEstimator, HealthMonitor
from dense_armor.core.online.linear.glm import LinearRegression
from dense_armor.core.online.optim import SGD

model = LinearRegression(optimizer=SGD(lr=5e-4), intercept=True, feature_keys=["qd_n"])
safe = SafeEstimator(model=model, guard=lambda x: abs(x["qd"]) > 0.5, fallback=0.0,
                     monitor=HealthMonitor(window=50, warmup=20))
print(safe.predict_one({"qd": 0.1, "qd_n": 0.1}), safe.health.value, safe.is_flagged({"qd": 0.9, "qd_n": 0.9}))
0.0 warming_up True

A velocity of 0.1 is below the guard, and the model has not learned yet, so it predicts 0.0 and the monitor is still warming_up. A velocity of 0.9 is above 0.5: the guard flags it.

API reference

SafeEstimator

SafeEstimator(
    model: Any,
    guard: Callable[[Any], bool] | None = None,
    fallback: Any = None,
    monitor: HealthMonitor | None = None,
)

Bases: Estimator

Wrap an estimator with a guard and a fallback.

Every sample is scored first. If the guard flags it, the wrapped model does not learn from the sample and the output is the fallback value.

The wrapped model can be any estimator: a regressor, a classifier, a transformer, an anomaly detector. Only the methods the model actually exposes are called; the rest pass through as None. The health residual is |y - y_hat| for a model without predict_proba_one and the 0/1 error y_hat != y for a classifier.

Parameters:

Name Type Description Default
model Any

the estimator to wrap.

required
guard Callable[[Any], bool] | None

callable x -> bool returning True for a flagged sample. None disables guarding.

None
fallback Any

value returned while flagged. None means "hold the last good prediction".

None
monitor HealthMonitor | None

optional :class:HealthMonitor; a default one is created when not given.

None

Examples:

>>> from dense_armor.roles.safety import SafeEstimator
>>> from dense_armor.core.signals.stats.moments import RunningMoments
>>> guard = lambda s: s["x"] > 1e6
>>> safe = SafeEstimator(RunningMoments(), guard=guard, fallback=0.0)
>>> _ = safe.learn_one({"x": 1.0}, 0.0)
>>> safe.is_flagged({"x": 1e7})
True
>>> safe.health.value
'warming_up'
Source code in dense_armor/roles/safety.py
def __init__(
    self,
    model: Any,
    guard: Callable[[Any], bool] | None = None,
    fallback: Any = None,
    monitor: HealthMonitor | None = None,
) -> None:
    self.model = model
    self.guard = guard
    self.fallback = fallback
    self.monitor = monitor if monitor is not None else HealthMonitor()
    self._last_good_: Any = fallback
    self.n_blocked_ = 0

health property

health: Health

Current :class:Health state.

budget_s property

budget_s: float | None

Latency of learn_one: a predict_one and a learn_one of the model.

The guard and the health monitor are not counted: they are a few comparisons. None if the model declares no budget_s.

memory_class property

memory_class: str

The memory class of the wrapped model.

is_flagged

is_flagged(x: Any) -> bool

Return True if the guard flags x.

Source code in dense_armor/roles/safety.py
def is_flagged(self, x: Any) -> bool:
    """Return ``True`` if the guard flags ``x``."""
    if self.guard is None:
        return False
    return bool(self.guard(x))

learn_one

learn_one(x: Any, y: Any = None, t: float | None = None)

Learn from (x, y) unless the guard flags x.

When y is given and the model has predict_one, the model predicts before it learns, because the residual (or the miss, for a classifier) is what the health monitor reads. A call therefore costs one predict_one and one learn_one of the wrapped model, about twice its learn_one. The budget_s of the wrapper accounts for this cost (two budgets of the model), and it is None when the model declares none, in which case a :class:~dense_armor.roles.realtime.RealtimePipeline with require_budget=True refuses the wrapper.

Source code in dense_armor/roles/safety.py
def learn_one(self, x: Any, y: Any = None, t: float | None = None):
    """Learn from ``(x, y)`` unless the guard flags ``x``.

    When ``y`` is given and the model has ``predict_one``, the model
    predicts before it learns, because the residual (or the miss, for a
    classifier) is what the health monitor reads. A call therefore costs
    one ``predict_one`` and one ``learn_one`` of the wrapped model, about
    twice its ``learn_one``. The ``budget_s`` of the wrapper accounts for
    this cost (two budgets of the model), and it is ``None`` when the
    model declares none, in which case a
    :class:`~dense_armor.roles.realtime.RealtimePipeline` with
    ``require_budget=True`` refuses the wrapper.
    """
    self._time_step(t)
    if self.is_flagged(x):
        self.n_blocked_ += 1
        return self
    m = self.model
    if hasattr(m, "predict_one") and y is not None:
        yhat = call_with_t(m.predict_one, x, t=t)
        if yhat is not None:
            if hasattr(m, "predict_proba_one"):
                self.monitor.update(float(yhat != y))
            else:
                try:
                    self.monitor.update(abs(float(y) - float(yhat)))
                except (TypeError, ValueError):
                    pass
    if hasattr(m, "learn_one"):
        call_learn_one(m.learn_one, x, y, t=t)
    return self

predict_one

predict_one(
    x: Any,
    t: float | None = None,
    return_std: bool = False,
    return_estimate: bool = False,
) -> Any

Predict with the wrapped model, or the fallback if flagged.

Source code in dense_armor/roles/safety.py
def predict_one(
    self,
    x: Any,
    t: float | None = None,
    return_std: bool = False,
    return_estimate: bool = False,
) -> Any:
    """Predict with the wrapped model, or the fallback if flagged."""
    self._time_step(t)
    if self.is_flagged(x):
        self.n_blocked_ += 1
        if self.fallback is not None:
            return self.fallback
        return self._last_good_
    m = self.model
    if not hasattr(m, "predict_one"):
        return None
    out = m.predict_one(x, t=t)
    self._last_good_ = out
    return out

score_one

score_one(x: Any, t: float | None = None) -> float

Delegate score_one to the wrapped model, or NaN if absent.

Source code in dense_armor/roles/safety.py
def score_one(self, x: Any, t: float | None = None) -> float:
    """Delegate ``score_one`` to the wrapped model, or NaN if absent."""
    self._time_step(t)
    m = self.model
    if not hasattr(m, "score_one"):
        return float("nan")
    return float(m.score_one(x, t=t))

save

save(path: str | Path, key: bytes | None = None) -> Path

Save the learned state with format version and SHA-256.

Parameters:

Name Type Description Default
path str | Path

destination file.

required
key bytes | None

optional secret; the digest becomes an HMAC-SHA256.

None

Returns:

Type Description
Path

The path written.

Source code in dense_armor/roles/safety.py
def save(self, path: str | Path, key: bytes | None = None) -> Path:
    """Save the learned state with format version and SHA-256.

    Args:
        path: destination file.
        key: optional secret; the digest becomes an HMAC-SHA256.

    Returns:
        The path written.
    """
    state = {
        "version": CHECKPOINT_VERSION,
        "model_module": type(self.model).__module__,
        "model_class": type(self.model).__name__,
        "timestamp": time.time(),
        "n_blocked": self.n_blocked_,
        "state_dict": self.model.state_dict()
        if hasattr(self.model, "state_dict")
        else {},
    }
    blob = pickle.dumps(state, protocol=pickle.HIGHEST_PROTOCOL)
    digest = self._digest(blob, key)
    payload = {"sha256": digest, "blob": blob}
    p = Path(path)
    p.write_bytes(pickle.dumps(payload, protocol=pickle.HIGHEST_PROTOCOL))
    return p

restore

restore(
    path: str | Path, key: bytes | None = None
) -> SafeEstimator

Restore the learned state from a saved checkpoint.

The envelope is read with an unpickler that refuses every global, and the digest is verified before the model state is unpickled. The state itself is a pickle: restore only trusted checkpoints.

Parameters:

Name Type Description Default
path str | Path

source file.

required
key bytes | None

the secret given to save, if any.

None

Returns:

Type Description
SafeEstimator

self, for chaining.

Raises:

Type Description
ValueError

if the checkpoint format version does not match, or the checksum does not match.

TypeError

if the stored model class does not match.

Source code in dense_armor/roles/safety.py
def restore(self, path: str | Path, key: bytes | None = None) -> "SafeEstimator":
    """Restore the learned state from a saved checkpoint.

    The envelope is read with an unpickler that refuses every global,
    and the digest is verified before the model state is unpickled.
    The state itself is a pickle: restore only trusted checkpoints.

    Args:
        path: source file.
        key: the secret given to ``save``, if any.

    Returns:
        ``self``, for chaining.

    Raises:
        ValueError: if the checkpoint format version does not match,
            or the checksum does not match.
        TypeError: if the stored model class does not match.
    """
    p = Path(path)
    payload = _EnvelopeUnpickler(io.BytesIO(p.read_bytes())).load()
    blob = payload["blob"]
    digest = self._digest(blob, key)
    if not hmac.compare_digest(digest, str(payload["sha256"])):
        raise ValueError(f"checkpoint {p} is corrupted: SHA-256 mismatch")
    state = pickle.loads(blob)
    if state.get("version") != CHECKPOINT_VERSION:
        raise ValueError(
            f"checkpoint version {state.get('version')} "
            f"does not match current {CHECKPOINT_VERSION}"
        )
    if state.get("model_class") != type(self.model).__name__:
        raise TypeError(
            f"checkpoint model class {state.get('model_class')} "
            f"does not match current {type(self.model).__name__}"
        )
    if hasattr(self.model, "load_state_dict"):
        self.model.load_state_dict(state["state_dict"])
    self.n_blocked_ = int(state.get("n_blocked", 0))
    return self

PreTradeChecker

PreTradeChecker(
    max_notional: float,
    max_size: float,
    price_band: float,
    max_orders: int,
    window_s: float,
    duplicate_window_s: float,
)

Accept or reject one order with the five controls of (c)(1).

The controls run in this order and the first one that fails gives the reason; an approved order has reason == "ok":

  1. "size": size > max_size (SEC 15c3-5 (c)(1)(ii), size parameters, PDF page 128).
  2. "price_band": abs(price / ref_price - 1) > price_band ((c)(1)(ii), price parameters, PDF page 128).
  3. "duplicate": an approved order with the same account, side, size and price was approved in the last duplicate_window_s seconds ((c)(1)(ii), duplicative orders, PDF page 128).
  4. "rate": max_orders or more orders of the account were approved in the last window_s seconds ((c)(1)(ii), over a short period of time, PDF page 128).
  5. "notional": the open notional of the account plus size * price is above max_notional ((c)(1)(i), pre-set credit or capital thresholds, in the aggregate for each customer, PDF page 128).

A rejected order does not change the open notional, the rate window, the duplicate window or the time of the last approved sample. An approved order records its timestamp as the new _last_t, adds its entry to the rate and duplicate windows, adds size * price to the open notional, and returns Decision(True, "ok"). A t smaller than the last approved t raises ValueError before the five controls run: the sequence of approved timestamps is monotone, but the sequence of timestamps of all orders, rejected ones included, is not. The windows are filtered to the alive entries on every check call, so an entry that is older than the window is never counted and never written back. Every approved order calls _prune, which drops the entries of every account that are older than the two windows; a rejected order never calls it. The cost of an approved order is O(accounts with entries in the rate or duplicate lists, plus the entries that survive); a rejected one costs O(entries of its own account). The open notional map is never pruned: an account that stops trading keeps its last notional until release brings it back to zero. The value exactly at a limit is approved; one tick above is rejected. Only approved orders count for the rate and for the duplicates: that is our choice, the rule does not say it.

The notional control is per account, not aggregated across accounts for the broker or dealer. Rule 15c3-5 (c)(1)(i) requires the aggregate limit for each customer and the broker or dealer; the broker-wide aggregate is not implemented. This is a declared limit, not a deviation from the rule: the class does not replace the broker's own controls.

Parameters:

Name Type Description Default
max_notional float

the largest open notional an account can carry, in the currency of the prices; strictly positive. This is the per-account limit; the aggregate for the broker is not implemented (see above).

required
max_size float

the largest size of one order, in shares; strictly positive.

required
price_band float

the largest relative distance of the price from the reference price, as a fraction; strictly positive.

required
max_orders int

the number of approved orders in window_s after which the account is rejected; at least 1.

required
window_s float

the length of the rate window, in seconds; strictly positive.

required
duplicate_window_s float

the length of the duplicate window, in seconds; strictly positive.

required

Raises:

Type Description
ValueError

if a limit is not strictly positive.

Examples:

>>> c = PreTradeChecker(max_notional=1e6, max_size=10.0,
...                     price_band=0.01, max_orders=5,
...                     window_s=1.0, duplicate_window_s=0.1)
>>> c.check("a", "buy", 10.0, 100.0, 100.0, t=0.0)
Decision(approved=True, reason='ok')
>>> c.check("a", "buy", 10.01, 100.0, 100.0, t=0.1).reason
'size'
>>> c.open_notional("a")
1000.0
References

SEC Release 34-63241, Rule 15c3-5 (c)(1)(i) and (c)(1)(ii), PDF page 128: pre-set credit or capital thresholds in the aggregate for each customer; price or size parameters, over a short period of time, duplicative orders.

Source code in dense_armor/core/finance/pretrade.py
def __init__(
    self,
    max_notional: float,
    max_size: float,
    price_band: float,
    max_orders: int,
    window_s: float,
    duplicate_window_s: float,
) -> None:
    for name, v in (
        ("max_notional", max_notional),
        ("max_size", max_size),
        ("price_band", price_band),
        ("window_s", window_s),
        ("duplicate_window_s", duplicate_window_s),
    ):
        fv = float(v)
        if not (math.isfinite(fv) and fv > 0.0):
            raise ValueError(
                f"{name} must be a finite number strictly positive, got {v}"
            )
    if int(max_orders) < 1:
        raise ValueError(f"max_orders must be >= 1, got {max_orders}")
    self.max_notional = float(max_notional)
    self.max_size = float(max_size)
    self.price_band = float(price_band)
    self.max_orders = int(max_orders)
    self.window_s = float(window_s)
    self.duplicate_window_s = float(duplicate_window_s)
    self._open: dict[str, float] = {}
    self._rate: dict[str, list[float]] = {}
    self._dup: dict[str, list[tuple[float, float, float, float, str]]] = {}
    self._last_t = -float("inf")

check

check(
    account: str,
    side: str,
    size: float,
    price: float,
    ref_price: float,
    t: float,
) -> Decision

Decide one order. A rejected order leaves the state unchanged.

Source code in dense_armor/core/finance/pretrade.py
def check(
    self,
    account: str,
    side: str,
    size: float,
    price: float,
    ref_price: float,
    t: float,
) -> Decision:
    """Decide one order. A rejected order leaves the state unchanged."""
    if side not in ("buy", "sell"):
        raise ValueError(f'side must be "buy" or "sell", got {side!r}')
    sz = float(size)
    px = float(price)
    rpx = float(ref_price)
    tf = float(t)
    for name, v in (("size", sz), ("price", px), ("ref_price", rpx), ("t", tf)):
        if not math.isfinite(v):
            raise ValueError(f"{name} must be a finite number, got {v}")
    if not sz > 0.0:
        raise ValueError(f"size must be positive, got {size}")
    if not px > 0.0:
        raise ValueError(f"price must be positive, got {price}")
    if not rpx > 0.0:
        raise ValueError(f"ref_price must be positive, got {ref_price}")
    if tf < self._last_t:
        raise ValueError(f"t must be >= the previous t ({self._last_t}), got {t}")
    rate_alive = [u for u in self._rate.get(account, []) if u >= tf - self.window_s]
    dup_alive = [
        r
        for r in self._dup.get(account, [])
        if r[0] >= tf - self.duplicate_window_s
    ]
    if sz > self.max_size:
        return Decision(False, "size")
    rel = abs(px / rpx - 1.0)
    if rel > self.price_band:
        return Decision(False, "price_band")
    for r in dup_alive:
        if r[1] == sz and r[2] == px and r[4] == side:
            return Decision(False, "duplicate")
    if len(rate_alive) >= self.max_orders:
        return Decision(False, "rate")
    open_now = self._open.get(account, 0.0)
    add = sz * px
    if open_now + add > self.max_notional:
        return Decision(False, "notional")
    self._last_t = tf
    self._open[account] = open_now + add
    self._prune(tf)
    rate_alive.append(tf)
    dup_alive.append((tf, sz, px, rpx, side))
    self._rate[account] = rate_alive
    self._dup[account] = dup_alive
    return Decision(True, "ok")

release

release(account: str, notional: float) -> None

Subtract a notional after a fill or a cancel.

Parameters:

Name Type Description Default
account str

the account whose open notional is reduced.

required
notional float

the notional to release, a finite number > 0 and <= the current open notional of the account.

required

Raises:

Type Description
ValueError

if notional is not finite, if it is not > 0, or if it is larger than the open notional of the account by more than 1e-9 of the open notional (or 1e-9 in absolute value, whichever is larger). This tolerance covers the floating point residue of a sequence of approvals and releases that cancel each other; an exact equality in float would raise a spurious ValueError after such a sequence.

Source code in dense_armor/core/finance/pretrade.py
def release(self, account: str, notional: float) -> None:
    """Subtract a notional after a fill or a cancel.

    Args:
        account: the account whose open notional is reduced.
        notional: the notional to release, a finite number ``> 0`` and
            ``<=`` the current open notional of the account.

    Raises:
        ValueError: if ``notional`` is not finite, if it is not ``> 0``,
            or if it is larger than the open notional of the account by
            more than ``1e-9`` of the open notional (or ``1e-9`` in
            absolute value, whichever is larger). This tolerance covers
            the floating point residue of a sequence of approvals and
            releases that cancel each other; an exact equality in float
            would raise a spurious ``ValueError`` after such a sequence.
    """
    cur = self._open.get(account, 0.0)
    n = float(notional)
    tol = 1e-9 * max(abs(cur), 1.0)
    if not math.isfinite(n) or not (0.0 < n <= cur + tol):
        raise ValueError(
            f"release of {notional} is not allowed: open notional is {cur}"
        )
    self._open[account] = max(cur - n, 0.0)

open_notional

open_notional(account: str) -> float

The open notional of the account.

Source code in dense_armor/core/finance/pretrade.py
def open_notional(self, account: str) -> float:
    """The open notional of the account."""
    return float(self._open.get(account, 0.0))

References

  • Page, E. S. (1954). Continuous inspection schemes. Biometrika 41, 100-114. (cited in the docstring of the module dense_armor.roles.safety, where SafeEstimator is)
  • SEC Release 34-63241, Rule 15c3-5 (c)(1): pre-trade controls (cited in the docstring of PreTradeChecker)
  • Orabona, F. (2019). A Modern Introduction to Online Learning. (cited in the docstring of the module of LinearRegression)
  • Welford, B. P. (1962). Technometrics 4(3), 419-420. (cited in the docstring of RunningMoments)

Details

Choices stated explicitly

  • The guard reads the last return: x carries both ret (read by the guard) and ret_n (the only feature of the model). The guard stops the model on the tick after a jump, not on the tick of the jump, because the order of the tick is decided before its return is known.
  • fallback=0.0 means "no order": a flagged tick gives a prediction of zero, which is below the threshold of 0.2 (in units of the standard deviation) that the loop needs to send an order. None would keep the last good prediction instead.
  • budget_s of the wrapper sums components: SafeEstimator declares budget_s = sum_budgets([(2.0, model)]) because each learn_one costs one predict_one and one learn_one of the model.
  • The figures are drawn from the code of the loop: make_trading_guard_figures.py runs the same loop with SafeEstimator and PreTradeChecker. The surface runs it 625 times (25 thresholds, 25 shock sizes); the second figure is the run of section 2.

Declared limits

  • The data is synthetic (a momentum of 0.3, noise of 0.4% and three scheduled jumps), not a real market feed. Not a forecast, not investment advice.
  • PreTradeChecker does not replace a broker's controls nor full Rule 15c3-5 (missing paragraph (c)(2) and restricted lists).
  • The orders of the loop are never closed, so the open notional only grows; the limit max_notional of 100,000 is not reached in 300 ticks.
  • The guard looks at the last return only: it does not see a jump of the tick that is being decided, and the model does not measure its own uncertainty or its latency here.
  • HealthMonitor uses a fixed window; it does not adapt to long-period volatility changes.
  • PreTradeChecker is single-process in-memory; no shared state across processes.
  • No order is actually sent to an exchange: checker.check returns a Decision, it does not execute.