Python API Reference¶
Top-level exports¶
balancelab
¶
balancelab - adversarial game economy red-team library.
ConfidenceSequenceState(n, mean, half_width, lower, upper, total_cost, decisive, precision_met, sign_settled)
dataclass
¶
Streaming anytime-valid style bounds on mean value.
Attributes:
| Name | Type | Description |
|---|---|---|
n |
int
|
Number of observations. |
mean |
float
|
Sample mean of values. |
half_width |
float
|
± half-width of the sequence at this n. |
lower |
/ upper
|
mean ± half_width. |
total_cost |
float
|
Sum of observation costs. |
decisive |
bool
|
True when 0 is outside [lower, upper] (sign settled) or half_width ≤ target_precision and n ≥ min_n (precision met). |
precision_met |
bool
|
half_width ≤ target_precision (with enough samples). |
sign_settled |
bool
|
lower > 0 or upper < 0. |
EvalObservation(value, cost=1.0, label='')
dataclass
¶
One paired evaluation outcome (agent A minus agent B, or signed score).
ClosedLoopError
¶
Bases: ValueError
Raised when the economy/signal gate refuses empty or unsafe state.
GateOutcome(ok, verdict, reason, exit_code, rule_count=0, exploit_count=0, max_gain_ratio=None, human_required=False)
dataclass
¶
Result of a closed-loop economy or signal gate.
Attributes:
| Name | Type | Description |
|---|---|---|
ok |
bool
|
True only when ship/run may continue. |
verdict |
str
|
|
reason |
str
|
Always non-empty. |
exit_code |
int
|
0 PASS, 1 FAIL (exploit/signal), 2 FAIL_LOUD (empty). |
rule_count |
int
|
Economy rules examined. |
exploit_count |
int
|
Exploits found. |
max_gain_ratio |
float | None
|
Largest exploit gain if any. |
human_required |
bool
|
True when design review is required. |
EconomyGraph(rules=list())
dataclass
¶
A directed exchange graph of EconomyRules.
add_rule(rule)
¶
Add a rule to the graph.
Note: duplicate rules (same source, target, and quantities) produce the
same content-addressed id and will be stored as separate entries.
Callers that want idempotent insertion should check graph.rules first.
Source code in src/balancelab/economy.py
neighbors(item)
¶
Return [(target_item, rule)] for all rules from item.
items()
¶
EconomyRule(source_item, target_item, source_qty, target_qty, rule_id='', tags=list())
dataclass
¶
ExploitFinder
¶
Find arbitrage exploits using Bellman-Ford on log-weight graph.
find_exploits(graph)
¶
Convert exchange rates to log-weights: weight = -log(rate). Negative cycles in the log-weight graph = positive gain cycles. Use Bellman-Ford to detect negative cycles. Return ExploitReport with all found cycles.
Source code in src/balancelab/economy.py
152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 | |
ExploitPath(path, rules_used, gain_ratio)
dataclass
¶
A circular path that yields net gain.
ExploitReport(graph_item_count, graph_rule_count, exploits, total_found, timestamp=(lambda: time.time())())
dataclass
¶
Report of all exploits found in an economy.
to_dict()
¶
Serialize to dict.
Source code in src/balancelab/economy.py
assert_eval_stopping_ok(observations, **kwargs)
¶
Raise :class:ClosedLoopError unless :func:gate_eval_stopping is ok.
Source code in src/balancelab/av_aivat.py
gate_eval_stopping(observations, *, decision, target_precision=DEFAULT_TARGET_PRECISION, z=DEFAULT_Z, min_n=2, sample_sd=None, max_total_cost=None, require_observations=True)
¶
Refuse wasteful continue or premature stop (AV-AIVAT class).
Rules:
- No observations when required → FAIL_LOUD
decision=continuewhile sequence is decisive → FAIL (keep paying after result settled - paper failure mode)decision=stopwhile sequence is not decisive → FAIL (stop before agents can be told apart / precision unmet)max_total_costexceeded and still continuing → FAIL- continue while not decisive (and under budget) → PASS
- stop while decisive → PASS
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
observations
|
Sequence[EvalObservation | dict[str, Any] | float | int] | None
|
Stream of paired eval values so far. |
required |
decision
|
Decision
|
Proposed next action for the evaluation loop. |
required |
target_precision
|
float
|
Half-width goal (paper ±1 BB class). |
DEFAULT_TARGET_PRECISION
|
z
|
float
|
Critical value for the plug-in CS half-width. |
DEFAULT_Z
|
min_n
|
int
|
Minimum samples before precision_met can fire. |
2
|
sample_sd
|
float | None
|
Optional known SD (else sample). |
None
|
max_total_cost
|
float | None
|
Optional hard budget ceiling on continue. |
None
|
require_observations
|
bool
|
Empty stream → FAIL_LOUD when True. |
True
|
Source code in src/balancelab/av_aivat.py
178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 | |
summarize_confidence_sequence(observations, *, target_precision=DEFAULT_TARGET_PRECISION, z=DEFAULT_Z, min_n=2, sample_sd=None)
¶
Compute a streaming Gaussian-style confidence sequence snapshot.
Uses half_width = z * s / sqrt(n) with sample SD (or provided
sample_sd). This is a gate-facing plug-in CS, not a claim of
exact AV-AIVAT AIVAT corrections - those reduce variance upstream; the
gate consumes the resulting stream of values.
Source code in src/balancelab/av_aivat.py
gate_binary_signal(direction, yes_price, no_price=None, *, down_uses_no_token=True)
¶
Gate binary market signal mapping (SIGNAL-INVERT farm case).
Farm failure: BTC DOWN used DOWN mid as YES price on the DOWN contract - inverted directional signal.
For a DOWN signal on a market where YES = "price goes down": * correct: use YES price of the DOWN contract * invert trap: treating "DOWN mid" as if it were the UP/YES without checking token polarity
This gate checks that for direction=down, yes_price is the
probability mass for the DOWN outcome (typically lower when market is
bullish). When both yes and no are provided, they must sum ~1 and
direction must pick the cheaper/correct side consistently.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
direction
|
str
|
|
required |
yes_price
|
float
|
Price used as YES for the trade decision. |
required |
no_price
|
float | None
|
Optional NO price for consistency check. |
None
|
down_uses_no_token
|
bool
|
If True, direction=down must not use a yes_price that is mislabeled - when no_price given and direction=down, the traded token price should be yes_price only if YES means down; we require yes_price + no_price ≈ 1 and 0 < prices < 1. |
True
|
Source code in src/balancelab/closed_loop.py
gate_economy(graph, *, finder=None, max_allowed_gain=1.0, min_rules=1)
¶
Scan economy for exploits - load-bearing ship/no-ship gate.
- Empty rules → FAIL_LOUD
- Any exploit with gain_ratio > max_allowed_gain → FAIL (no-ship)
- Clean graph → PASS
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
graph
|
EconomyGraph
|
Economy exchange graph. |
required |
finder
|
ExploitFinder | None
|
Optional ExploitFinder (default new instance). |
None
|
max_allowed_gain
|
float
|
Gains strictly above this fail (default 1.0 = any profit). |
1.0
|
min_rules
|
int
|
Minimum rules required. |
1
|
Source code in src/balancelab/closed_loop.py
gate_kill_switch(trade_pnls, loss_limit, *, paper_mode=False, max_trip_rate=0.5)
¶
Gate kill-switch configuration (KILL-SWITCH farm case).
Farm failure: loss-limit tripped on every paper fill (worst-case spread model) - strategy could not be evaluated.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
trade_pnls
|
Sequence[float]
|
Per-trade PnL series (negative = loss). |
required |
loss_limit
|
float
|
Absolute loss that trips the switch (positive number). |
required |
paper_mode
|
bool
|
If True, apply stricter trip-rate limits. |
False
|
max_trip_rate
|
float
|
Fail if fraction of trades that would trip exceeds this. |
0.5
|
Source code in src/balancelab/closed_loop.py
gate_price_book(bids, asks, *, order='best-first')
¶
Gate bid/ask arrays for PRICE-BOOK-ORDER (Polymarket worst-to-best trap).
Farm failure: API returns worst-to-best; .first() took worst price.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
bids
|
Sequence[float]
|
Bid prices (best bid should be highest). |
required |
asks
|
Sequence[float]
|
Ask prices (best ask should be lowest). |
required |
order
|
str
|
|
'best-first'
|
Source code in src/balancelab/closed_loop.py
recommend_fixes(report)
¶
For each exploit found, suggest the minimum change to neutralize it.
Source code in src/balancelab/fixes.py
critical_path(graph)
¶
Find the sequence of nodes with highest economic throughput (most rules flow through).
Source code in src/balancelab/sensitivity.py
sensitivity_analysis(graph, report)
¶
Rank all nodes by how much they impact the economy balance, descending by impact_score.
Source code in src/balancelab/sensitivity.py
simulate(graph, initial_levels, n_steps=100, agent_strategy='greedy')
¶
Run economy simulation. 'exploit' strategy finds and uses exploits.
Source code in src/balancelab/simulation.py
28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 | |