while25 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- while25/__init__.py +341 -0
- while25/_costs/brokers/alpaca.json +96 -0
- while25/_costs/brokers/binance.json +34 -0
- while25/_costs/brokers/coinbase.json +34 -0
- while25/_costs/brokers/ibkr.json +39 -0
- while25/_costs/brokers/upstox.json +175 -0
- while25/_costs/brokers/zerodha.json +175 -0
- while25/_costs/crypto_alpaca.json +27 -0
- while25/_costs/global_crypto.json +18 -0
- while25/_costs/in_nse_equity.json +238 -0
- while25/_costs/in_nse_etf.json +352 -0
- while25/_costs/in_nse_fo.json +450 -0
- while25/_costs/us_crypto.json +18 -0
- while25/_costs/us_equity.json +175 -0
- while25/_costs/us_options.json +172 -0
- while25/_days.py +123 -0
- while25/_figures.py +233 -0
- while25/_runtime.py +49 -0
- while25/_universes/banknifty.json +80 -0
- while25/_universes/ndx100.json +520 -0
- while25/_universes/nifty50.json +260 -0
- while25/_universes/nifty500.json +2505 -0
- while25/_universes/sp500.json +2525 -0
- while25/assume.py +263 -0
- while25/backtest.py +881 -0
- while25/barline.py +160 -0
- while25/combo_legs.py +238 -0
- while25/errors.py +77 -0
- while25/fonts/IBMPlexMono-Regular.ttf +0 -0
- while25/fonts/IBMPlexMono-SemiBold.ttf +0 -0
- while25/fonts/Inter-Bold.ttf +0 -0
- while25/fonts/Inter-Regular.ttf +0 -0
- while25/fonts/Inter-SemiBold.ttf +0 -0
- while25/fonts/OFL-IBMPlexMono.txt +93 -0
- while25/fonts/OFL-Inter.txt +93 -0
- while25/future_pick.py +77 -0
- while25/inputs.py +215 -0
- while25/instruments.py +488 -0
- while25/modules.py +397 -0
- while25/money.py +24 -0
- while25/option_pick.py +221 -0
- while25/plots.py +147 -0
- while25/report.py +644 -0
- while25/ui.py +680 -0
- while25/universes.py +70 -0
- while25-0.1.0.dist-info/METADATA +3194 -0
- while25-0.1.0.dist-info/RECORD +50 -0
- while25-0.1.0.dist-info/WHEEL +5 -0
- while25-0.1.0.dist-info/licenses/LICENSE +201 -0
- while25-0.1.0.dist-info/top_level.txt +1 -0
while25/assume.py
ADDED
|
@@ -0,0 +1,263 @@
|
|
|
1
|
+
"""What a backtest assumes: costs, slippage, fills, same-bar order, risk-free
|
|
2
|
+
rate, capital, and where each came from.
|
|
3
|
+
|
|
4
|
+
The parent snapshots the user's defaults (BacktestDefaults on run / eval /
|
|
5
|
+
start) when the run arrives; a script reads that snapshot with
|
|
6
|
+
backtest.defaults() and layers its own choices with backtest.assume(). Every
|
|
7
|
+
value carries its source: `built-in`, `your default` or `this backtest`. A
|
|
8
|
+
script can never produce `your default`: only the parent's snapshot does.
|
|
9
|
+
"""
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
import json
|
|
13
|
+
import re
|
|
14
|
+
import threading
|
|
15
|
+
from dataclasses import dataclass, field, replace
|
|
16
|
+
from decimal import Decimal
|
|
17
|
+
from types import MappingProxyType
|
|
18
|
+
from typing import Mapping
|
|
19
|
+
|
|
20
|
+
from . import _runtime
|
|
21
|
+
from .backtest import Slippage
|
|
22
|
+
from .errors import While25Error
|
|
23
|
+
from .instruments import _as_decimal
|
|
24
|
+
|
|
25
|
+
BUILT_IN, YOURS, THIS = "built-in", "your default", "this backtest"
|
|
26
|
+
SOURCES = (BUILT_IN, YOURS, THIS)
|
|
27
|
+
#: The assumptions that carry a source (custom_flat / custom_pct ride costs').
|
|
28
|
+
NAMES = ("costs", "slippage", "fills", "same_bar", "risk_free", "capital")
|
|
29
|
+
FIELDS = ("costs", "custom_flat", "custom_pct", "slippage", "fills", "same_bar",
|
|
30
|
+
"risk_free", "capital")
|
|
31
|
+
_OVERRIDABLE = FIELDS[:-1] # capital is backtest_block(capital=)
|
|
32
|
+
_CHOICES = {"costs": ("real", "zero", "custom"), "fills": ("touch", "through"),
|
|
33
|
+
"same_bar": ("stop_first", "target_first")}
|
|
34
|
+
_PLAIN = re.compile(r"[0-9]+(\.[0-9]+)?")
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def _bad(p: str, name: str, value, why: str) -> While25Error:
|
|
38
|
+
return While25Error(f"{p} {name} {value!r} {why}", "BAD_INPUT")
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def _plain(d):
|
|
42
|
+
# Normalized: one value, one spelling ("6.50" and "6.5" fingerprint alike);
|
|
43
|
+
# "f" keeps it plain (100 is "100", never "1E+2").
|
|
44
|
+
return None if d is None else format(d.normalize(), "f")
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def _slip(s: Slippage) -> str:
|
|
48
|
+
return "none" if s.kind == "none" else f"{s.kind}:{_plain(s.n)}"
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
@dataclass(frozen=True)
|
|
52
|
+
class Assumptions:
|
|
53
|
+
costs: str = "real"
|
|
54
|
+
custom_flat: "Decimal | None" = None
|
|
55
|
+
custom_pct: "Decimal | None" = None
|
|
56
|
+
slippage: Slippage = Slippage()
|
|
57
|
+
fills: str = "touch"
|
|
58
|
+
same_bar: str = "stop_first"
|
|
59
|
+
risk_free: Decimal = Decimal(0) # percent per year
|
|
60
|
+
capital: "Decimal | None" = None
|
|
61
|
+
sources: Mapping[str, str] = field(
|
|
62
|
+
default_factory=lambda: MappingProxyType(dict.fromkeys(NAMES, BUILT_IN)))
|
|
63
|
+
|
|
64
|
+
def __post_init__(self) -> None:
|
|
65
|
+
"""A hand-built (or replace()d) one is held to from_defaults' rules:
|
|
66
|
+
BAD_INPUT naming the field, never a figure made under it."""
|
|
67
|
+
p = "backtest.Assumptions"
|
|
68
|
+
for name, choices in _CHOICES.items():
|
|
69
|
+
if getattr(self, name) not in choices:
|
|
70
|
+
raise _bad(p, name, getattr(self, name), f"is not one of {', '.join(choices)}")
|
|
71
|
+
if not isinstance(self.slippage, Slippage):
|
|
72
|
+
raise _bad(p, "slippage", self.slippage, "must be a backtest.Slippage")
|
|
73
|
+
for name, optional, positive, hi in (("custom_flat", True, False, None),
|
|
74
|
+
("custom_pct", True, False, None),
|
|
75
|
+
("risk_free", False, False, 100),
|
|
76
|
+
("capital", True, True, None)):
|
|
77
|
+
x = getattr(self, name)
|
|
78
|
+
if x is None and optional:
|
|
79
|
+
continue
|
|
80
|
+
if (not isinstance(x, Decimal) or not x.is_finite() or x < 0
|
|
81
|
+
or (positive and x == 0) or (hi is not None and x > hi)):
|
|
82
|
+
limit = ("above 0" if positive else "0 or more") + (f", {hi} or less" if hi else "")
|
|
83
|
+
raise _bad(p, name, x, f"must be a finite Decimal {limit}")
|
|
84
|
+
figures = (self.custom_flat, self.custom_pct)
|
|
85
|
+
if self.costs == "custom" and None in figures:
|
|
86
|
+
raise _bad(p, "costs", self.costs, "needs both custom_flat and custom_pct")
|
|
87
|
+
if self.costs != "custom" and figures != (None, None):
|
|
88
|
+
n = "custom_flat" if self.custom_flat is not None else "custom_pct"
|
|
89
|
+
raise _bad(p, n, getattr(self, n), f"applies only when costs is custom, not {self.costs!r}")
|
|
90
|
+
src = self.sources
|
|
91
|
+
if (not isinstance(src, Mapping) or set(src) != set(NAMES)
|
|
92
|
+
or any(v not in SOURCES for v in src.values())):
|
|
93
|
+
raise _bad(p, "sources", src, f"must give each of {', '.join(NAMES)} "
|
|
94
|
+
f"one of {', '.join(SOURCES)}")
|
|
95
|
+
|
|
96
|
+
def as_dict(self) -> dict:
|
|
97
|
+
"""Wire strings: plain decimals (no exponent), None when unset."""
|
|
98
|
+
return {"costs": self.costs, "custom_flat": _plain(self.custom_flat),
|
|
99
|
+
"custom_pct": _plain(self.custom_pct), "slippage": _slip(self.slippage),
|
|
100
|
+
"fills": self.fills, "same_bar": self.same_bar,
|
|
101
|
+
"risk_free": _plain(self.risk_free), "capital": _plain(self.capital),
|
|
102
|
+
"sources": dict(self.sources)}
|
|
103
|
+
|
|
104
|
+
def fingerprint(self) -> str:
|
|
105
|
+
"""Values AND sources, as stable JSON."""
|
|
106
|
+
return json.dumps(self.as_dict(), sort_keys=True, separators=(",", ":"))
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
_BUILT_INS = Assumptions()
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
def _num(p: str, name: str, x, wire: bool, *, positive=False, hi=None) -> Decimal:
|
|
113
|
+
if wire:
|
|
114
|
+
if not isinstance(x, str) or not _PLAIN.fullmatch(x):
|
|
115
|
+
raise _bad(p, name, x, "is not a plain decimal (digits, an optional point)")
|
|
116
|
+
d = Decimal(x)
|
|
117
|
+
else:
|
|
118
|
+
try:
|
|
119
|
+
d = _as_decimal(x, name)
|
|
120
|
+
except (ValueError, TypeError):
|
|
121
|
+
raise _bad(p, name, x, "is not a number") from None
|
|
122
|
+
if not d.is_finite():
|
|
123
|
+
raise _bad(p, name, x, "must be finite")
|
|
124
|
+
if d < 0 or (positive and d == 0):
|
|
125
|
+
raise _bad(p, name, x, "must be above 0" if positive else "must be 0 or more")
|
|
126
|
+
if hi is not None and d > hi:
|
|
127
|
+
raise _bad(p, name, x, f"must be {hi} or less")
|
|
128
|
+
return d.copy_abs() # -0 reads 0
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
def _slippage(p: str, x, wire: bool) -> Slippage:
|
|
132
|
+
if not wire:
|
|
133
|
+
if not isinstance(x, Slippage):
|
|
134
|
+
raise _bad(p, "slippage", x, "must be a backtest.Slippage "
|
|
135
|
+
"(Slippage.none(), Slippage.bps(n) or Slippage.ticks(n))")
|
|
136
|
+
return x
|
|
137
|
+
kind, _, n = x.partition(":") if isinstance(x, str) else ("", "", "")
|
|
138
|
+
if x != "none" and not (kind in ("bps", "ticks") and _PLAIN.fullmatch(n)):
|
|
139
|
+
raise _bad(p, "slippage", x, "is not none, bps:<n> or ticks:<n>")
|
|
140
|
+
try:
|
|
141
|
+
return Slippage.parse(x)
|
|
142
|
+
except While25Error as exc:
|
|
143
|
+
raise _bad(p, "slippage", x, exc.message) from None
|
|
144
|
+
|
|
145
|
+
|
|
146
|
+
def _values(get, p: str, wire: bool) -> dict:
|
|
147
|
+
"""The fields `get` names (None = absent), each validated."""
|
|
148
|
+
out = {}
|
|
149
|
+
for name in FIELDS:
|
|
150
|
+
x = get(name)
|
|
151
|
+
if x is None:
|
|
152
|
+
continue
|
|
153
|
+
if name in _CHOICES:
|
|
154
|
+
if not isinstance(x, str) or x not in _CHOICES[name]:
|
|
155
|
+
raise _bad(p, name, x, f"is not one of {', '.join(_CHOICES[name])}")
|
|
156
|
+
out[name] = x
|
|
157
|
+
elif name == "slippage":
|
|
158
|
+
out[name] = _slippage(p, x, wire)
|
|
159
|
+
else:
|
|
160
|
+
out[name] = _num(p, name, x, wire, positive=name == "capital",
|
|
161
|
+
hi=100 if name == "risk_free" else None)
|
|
162
|
+
return out
|
|
163
|
+
|
|
164
|
+
|
|
165
|
+
def _layer(base: Assumptions, vals: dict, source: str, p: str, *, stray_ok: bool) -> Assumptions:
|
|
166
|
+
costs = vals.get("costs", base.costs)
|
|
167
|
+
figures = {"custom_flat", "custom_pct"} & vals.keys()
|
|
168
|
+
if costs == "custom":
|
|
169
|
+
flat = vals.get("custom_flat", base.custom_flat)
|
|
170
|
+
pct = vals.get("custom_pct", base.custom_pct)
|
|
171
|
+
if flat is None or pct is None:
|
|
172
|
+
raise _bad(p, "costs", costs, "needs both custom_flat and custom_pct")
|
|
173
|
+
else:
|
|
174
|
+
if figures and not stray_ok:
|
|
175
|
+
n = sorted(figures)[0]
|
|
176
|
+
raise _bad(p, n, vals[n], f"applies only when costs is custom, not {costs!r}")
|
|
177
|
+
flat = pct = None # remembered figures that do not apply
|
|
178
|
+
sources = dict(base.sources)
|
|
179
|
+
for name in NAMES:
|
|
180
|
+
if name in vals or (name == "costs" and costs == "custom" and figures):
|
|
181
|
+
sources[name] = source
|
|
182
|
+
return Assumptions(
|
|
183
|
+
costs=costs, custom_flat=flat, custom_pct=pct,
|
|
184
|
+
slippage=vals.get("slippage", base.slippage), fills=vals.get("fills", base.fills),
|
|
185
|
+
same_bar=vals.get("same_bar", base.same_bar),
|
|
186
|
+
risk_free=vals.get("risk_free", base.risk_free),
|
|
187
|
+
capital=vals.get("capital", base.capital), sources=MappingProxyType(sources))
|
|
188
|
+
|
|
189
|
+
|
|
190
|
+
def from_defaults(msg) -> Assumptions:
|
|
191
|
+
"""The user's BacktestDefaults (proto or dict of wire strings) as a
|
|
192
|
+
snapshot: set fields `your default`, the rest `built-in`. None or absent
|
|
193
|
+
reads all built-in. Malformed: BAD_INPUT naming the field."""
|
|
194
|
+
p = "backtest default"
|
|
195
|
+
if msg is None:
|
|
196
|
+
return Assumptions()
|
|
197
|
+
if isinstance(msg, Mapping):
|
|
198
|
+
if extra := sorted(set(msg) - set(FIELDS)):
|
|
199
|
+
raise _bad(p, extra[0], msg[extra[0]], f"is not one of {', '.join(FIELDS)}")
|
|
200
|
+
get = msg.get
|
|
201
|
+
else:
|
|
202
|
+
def get(n):
|
|
203
|
+
return getattr(msg, n) if msg.HasField(n) else None
|
|
204
|
+
return _layer(_BUILT_INS, _values(get, p, wire=True), YOURS, p, stray_ok=True)
|
|
205
|
+
|
|
206
|
+
|
|
207
|
+
def from_dict(d) -> Assumptions:
|
|
208
|
+
"""as_dict()'s inverse, validated like from_defaults, keeping the recorded
|
|
209
|
+
sources. What the parent rebuilds from a trade's record."""
|
|
210
|
+
p = "recorded assumptions"
|
|
211
|
+
if not isinstance(d, Mapping):
|
|
212
|
+
raise While25Error(f"{p} must be a mapping, not {type(d).__name__}", "BAD_INPUT")
|
|
213
|
+
if extra := sorted(set(d) - set(FIELDS) - {"sources"}):
|
|
214
|
+
raise _bad(p, extra[0], d[extra[0]], f"is not one of {', '.join(FIELDS)}")
|
|
215
|
+
src = d.get("sources")
|
|
216
|
+
if (not isinstance(src, Mapping) or set(src) != set(NAMES)
|
|
217
|
+
or any(v not in SOURCES for v in src.values())):
|
|
218
|
+
raise _bad(p, "sources", src, f"must give each of {', '.join(NAMES)} "
|
|
219
|
+
f"one of {', '.join(SOURCES)}")
|
|
220
|
+
a = _layer(_BUILT_INS, _values(d.get, p, wire=True), YOURS, p, stray_ok=False)
|
|
221
|
+
for name in NAMES:
|
|
222
|
+
if src[name] == BUILT_IN and getattr(a, name) != getattr(_BUILT_INS, name):
|
|
223
|
+
raise _bad(p, name, d.get(name), "is not the built-in value its source claims")
|
|
224
|
+
return replace(a, sources=MappingProxyType(dict(src)))
|
|
225
|
+
|
|
226
|
+
|
|
227
|
+
# ---- the script's read-only copy ---------------------------------------------
|
|
228
|
+
|
|
229
|
+
_cache: tuple = (None, None) # (ctx, Assumptions): one fetch per running module
|
|
230
|
+
_lock = threading.Lock()
|
|
231
|
+
|
|
232
|
+
|
|
233
|
+
def defaults() -> Assumptions:
|
|
234
|
+
"""The run's snapshot of the user's defaults, asked of the parent once and
|
|
235
|
+
kept. With no parent link (the parent itself, a plain import) all built-in."""
|
|
236
|
+
global _cache
|
|
237
|
+
try:
|
|
238
|
+
ctx = _runtime.current()
|
|
239
|
+
except RuntimeError:
|
|
240
|
+
return Assumptions()
|
|
241
|
+
call = getattr(ctx, "_call", None)
|
|
242
|
+
if call is None:
|
|
243
|
+
return Assumptions()
|
|
244
|
+
with _lock:
|
|
245
|
+
if _cache[0] is not ctx:
|
|
246
|
+
reply = call("backtest_defaults", {})
|
|
247
|
+
_cache = (ctx, from_dict(reply.get("assumptions")))
|
|
248
|
+
return _cache[1]
|
|
249
|
+
|
|
250
|
+
|
|
251
|
+
def assume(**overrides) -> Assumptions:
|
|
252
|
+
"""defaults() with this backtest's own choices on top; each overridden
|
|
253
|
+
assumption reads `this backtest`. Keys: costs, custom_flat, custom_pct,
|
|
254
|
+
slippage (a Slippage), fills, same_bar, risk_free. Capital is
|
|
255
|
+
backtest_block(capital=)."""
|
|
256
|
+
p = "backtest.assume"
|
|
257
|
+
for k, v in overrides.items():
|
|
258
|
+
if k not in _OVERRIDABLE:
|
|
259
|
+
raise _bad(p, k, v, f"is not an assumption ({', '.join(_OVERRIDABLE)}; "
|
|
260
|
+
f"capital is backtest_block(capital=))")
|
|
261
|
+
if v is None:
|
|
262
|
+
raise _bad(p, k, v, "must be a value; leave it out to keep the default")
|
|
263
|
+
return _layer(defaults(), _values(overrides.get, p, wire=False), THIS, p, stray_ok=False)
|