doridata 0.2.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.
- doridata/__init__.py +76 -0
- doridata/archive.py +262 -0
- doridata/backtest.py +69 -0
- doridata/catalog.py +15 -0
- doridata/cli.py +65 -0
- doridata/client.py +485 -0
- doridata/config/__init__.py +5 -0
- doridata/config/control.py +157 -0
- doridata/config/profile.py +241 -0
- doridata/contracts/__init__.py +1 -0
- doridata/contracts/provider.py +103 -0
- doridata/contracts/records.py +86 -0
- doridata/journal.py +154 -0
- doridata/model.py +153 -0
- doridata/providers/__init__.py +1 -0
- doridata/providers/akshare/__init__.py +5 -0
- doridata/providers/akshare/daily.py +47 -0
- doridata/providers/akshare/definition.py +22 -0
- doridata/providers/baostock/__init__.py +5 -0
- doridata/providers/baostock/daily.py +82 -0
- doridata/providers/baostock/definition.py +24 -0
- doridata/providers/baostock/events.py +113 -0
- doridata/providers/eastmoney/__init__.py +5 -0
- doridata/providers/eastmoney/contract.py +5 -0
- doridata/providers/eastmoney/daily.py +49 -0
- doridata/providers/eastmoney/definition.py +21 -0
- doridata/providers/http_daily.py +37 -0
- doridata/providers/qmt/__init__.py +5 -0
- doridata/providers/qmt/daily.py +67 -0
- doridata/providers/qmt/definition.py +24 -0
- doridata/providers/qmt/minute.py +97 -0
- doridata/providers/registry.py +78 -0
- doridata/providers/sdk_frames.py +41 -0
- doridata/providers/sina/__init__.py +5 -0
- doridata/providers/sina/contract.py +5 -0
- doridata/providers/sina/daily.py +38 -0
- doridata/providers/sina/definition.py +24 -0
- doridata/providers/tdx/__init__.py +5 -0
- doridata/providers/tdx/daily.py +74 -0
- doridata/providers/tdx/definition.py +30 -0
- doridata/providers/tencent/__init__.py +5 -0
- doridata/providers/tencent/contract.py +5 -0
- doridata/providers/tencent/daily.py +31 -0
- doridata/providers/tencent/definition.py +28 -0
- doridata/providers/tushare/__init__.py +5 -0
- doridata/providers/tushare/account.py +52 -0
- doridata/providers/tushare/api.py +116 -0
- doridata/providers/tushare/daily.py +65 -0
- doridata/providers/tushare/definition.py +24 -0
- doridata/providers/tushare/fundamentals.py +184 -0
- doridata/providers/tushare/sdk.py +62 -0
- doridata/providers/yahoo/__init__.py +5 -0
- doridata/providers/yahoo/contract.py +3 -0
- doridata/providers/yahoo/daily.py +44 -0
- doridata/providers/yahoo/definition.py +23 -0
- doridata/quota.py +91 -0
- doridata/routing/__init__.py +1 -0
- doridata/routing/collect.py +268 -0
- doridata/routing/facts.py +154 -0
- doridata/routing/plan.py +202 -0
- doridata/runtime.py +231 -0
- doridata/sdk.py +7 -0
- doridata/selection.py +27 -0
- doridata/shared_quota.py +119 -0
- doridata/source.py +132 -0
- doridata/tdx.py +5 -0
- doridata/transport/__init__.py +1 -0
- doridata/transport/http.py +265 -0
- doridata/tushare.py +6 -0
- doridata/version.py +1 -0
- doridata/web.py +9 -0
- doridata-0.2.0.dist-info/METADATA +121 -0
- doridata-0.2.0.dist-info/RECORD +76 -0
- doridata-0.2.0.dist-info/WHEEL +4 -0
- doridata-0.2.0.dist-info/entry_points.txt +2 -0
- doridata-0.2.0.dist-info/licenses/LICENSE +201 -0
doridata/__init__.py
ADDED
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
"""DoriData public daily-bar API."""
|
|
2
|
+
|
|
3
|
+
from .archive import RunArchive
|
|
4
|
+
from .backtest import SessionFacts, doribt_records
|
|
5
|
+
from .catalog import Capability, capabilities
|
|
6
|
+
from .client import Attempt, Client, Difference, Observation, Policy, Result
|
|
7
|
+
from .config.control import ConfigStore, RevisionConflict
|
|
8
|
+
from .config.profile import ConfigIssue, Configuration, ConfigurationError, Profile
|
|
9
|
+
from .contracts.provider import FieldSpec, Product, ProviderDefinition
|
|
10
|
+
from .contracts.records import DataQuery, DataResult, Fact, FieldOrigin
|
|
11
|
+
from .journal import FactJournal
|
|
12
|
+
from .model import Bar, Query, SourceError
|
|
13
|
+
from .providers.registry import ProviderRegistry
|
|
14
|
+
from .quota import Budget, RateLimiter
|
|
15
|
+
from .runtime import ConfiguredClient
|
|
16
|
+
from .sdk import QMT, AKShare, BaoStock
|
|
17
|
+
from .selection import FallbackState
|
|
18
|
+
from .shared_quota import SQLiteRateLimiter
|
|
19
|
+
from .source import Artifact, Capture, EvidenceError, Provider
|
|
20
|
+
from .tdx import TongdaXin
|
|
21
|
+
from .tushare import Tushare, TushareAccount, parse_tushare_daily
|
|
22
|
+
from .version import __version__
|
|
23
|
+
from .web import Eastmoney, Sina, Tencent, Yahoo
|
|
24
|
+
|
|
25
|
+
__all__ = [
|
|
26
|
+
"QMT",
|
|
27
|
+
"AKShare",
|
|
28
|
+
"Artifact",
|
|
29
|
+
"Attempt",
|
|
30
|
+
"BaoStock",
|
|
31
|
+
"Bar",
|
|
32
|
+
"Budget",
|
|
33
|
+
"Capability",
|
|
34
|
+
"Capture",
|
|
35
|
+
"Client",
|
|
36
|
+
"ConfigIssue",
|
|
37
|
+
"ConfigStore",
|
|
38
|
+
"Configuration",
|
|
39
|
+
"ConfigurationError",
|
|
40
|
+
"ConfiguredClient",
|
|
41
|
+
"DataQuery",
|
|
42
|
+
"DataResult",
|
|
43
|
+
"Difference",
|
|
44
|
+
"Eastmoney",
|
|
45
|
+
"EvidenceError",
|
|
46
|
+
"Fact",
|
|
47
|
+
"FactJournal",
|
|
48
|
+
"FallbackState",
|
|
49
|
+
"FieldOrigin",
|
|
50
|
+
"FieldSpec",
|
|
51
|
+
"Observation",
|
|
52
|
+
"Policy",
|
|
53
|
+
"Product",
|
|
54
|
+
"Profile",
|
|
55
|
+
"Provider",
|
|
56
|
+
"ProviderDefinition",
|
|
57
|
+
"ProviderRegistry",
|
|
58
|
+
"Query",
|
|
59
|
+
"RateLimiter",
|
|
60
|
+
"Result",
|
|
61
|
+
"RevisionConflict",
|
|
62
|
+
"RunArchive",
|
|
63
|
+
"SQLiteRateLimiter",
|
|
64
|
+
"SessionFacts",
|
|
65
|
+
"Sina",
|
|
66
|
+
"SourceError",
|
|
67
|
+
"Tencent",
|
|
68
|
+
"TongdaXin",
|
|
69
|
+
"Tushare",
|
|
70
|
+
"TushareAccount",
|
|
71
|
+
"Yahoo",
|
|
72
|
+
"__version__",
|
|
73
|
+
"capabilities",
|
|
74
|
+
"doribt_records",
|
|
75
|
+
"parse_tushare_daily",
|
|
76
|
+
]
|
doridata/archive.py
ADDED
|
@@ -0,0 +1,262 @@
|
|
|
1
|
+
"""Content-addressed source artifacts and offline replay of a complete selection."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import hashlib
|
|
6
|
+
import json
|
|
7
|
+
import os
|
|
8
|
+
import re
|
|
9
|
+
import tempfile
|
|
10
|
+
from dataclasses import asdict
|
|
11
|
+
from datetime import date, datetime
|
|
12
|
+
from decimal import Decimal
|
|
13
|
+
from pathlib import Path
|
|
14
|
+
|
|
15
|
+
from .client import Attempt, Client, Observation, Policy, Result, run_context, select
|
|
16
|
+
from .model import Bar, Query
|
|
17
|
+
from .providers.registry import ProviderRegistry
|
|
18
|
+
from .source import Artifact, Capture, EvidenceError
|
|
19
|
+
from .version import __version__
|
|
20
|
+
|
|
21
|
+
SCHEMA = "doridata.run.v1"
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def _encode(value: object) -> bytes:
|
|
25
|
+
def scalar(item):
|
|
26
|
+
if isinstance(item, (date, datetime)):
|
|
27
|
+
return item.isoformat()
|
|
28
|
+
if isinstance(item, Decimal):
|
|
29
|
+
return str(item)
|
|
30
|
+
raise TypeError(f"Unsupported recorded value {type(item).__name__}")
|
|
31
|
+
|
|
32
|
+
return json.dumps(
|
|
33
|
+
value, default=scalar, sort_keys=True, separators=(",", ":"), allow_nan=False
|
|
34
|
+
).encode()
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def _artifact(data: dict) -> Artifact:
|
|
38
|
+
return Artifact(**(data | {"observed_at": datetime.fromisoformat(data["observed_at"])}))
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def _observation(data: dict) -> Observation:
|
|
42
|
+
attempt = data["attempt"].copy()
|
|
43
|
+
attempt["started_at"] = datetime.fromisoformat(attempt["started_at"])
|
|
44
|
+
attempt["artifacts"] = tuple(_artifact(a) for a in attempt["artifacts"])
|
|
45
|
+
for key in ("missing", "extra"):
|
|
46
|
+
attempt[key] = tuple(date.fromisoformat(d) for d in attempt[key])
|
|
47
|
+
for key in ("first_session", "last_session"):
|
|
48
|
+
if attempt[key] is not None:
|
|
49
|
+
attempt[key] = date.fromisoformat(attempt[key])
|
|
50
|
+
bars = tuple(Bar(**(b | {"session": date.fromisoformat(b["session"])})) for b in data["bars"])
|
|
51
|
+
return Observation(bars, Attempt(**attempt))
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def _decision(result: Result) -> dict:
|
|
55
|
+
return {
|
|
56
|
+
"status": result.status,
|
|
57
|
+
"selected": result.selected,
|
|
58
|
+
"bars": [asdict(b) for b in result.bars],
|
|
59
|
+
"differences": [asdict(d) for d in result.differences],
|
|
60
|
+
"attempts": [(a.source, a.origin, a.role, a.status, a.missing, a.extra) for a in result.attempts],
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
class RunArchive:
|
|
65
|
+
"""A caller-owned directory. Keep the returned run ID in the host's job or experiment record."""
|
|
66
|
+
|
|
67
|
+
def __init__(self, root: str | Path, *, registry: ProviderRegistry | None = None):
|
|
68
|
+
self.root = Path(root)
|
|
69
|
+
self.registry = registry if registry is not None else ProviderRegistry.builtin()
|
|
70
|
+
|
|
71
|
+
def _path(self, directory: str, digest: str) -> Path:
|
|
72
|
+
if not re.fullmatch(r"[0-9a-f]{64}", digest):
|
|
73
|
+
raise EvidenceError("Invalid SHA-256 reference")
|
|
74
|
+
return self.root / directory / digest[:2] / digest
|
|
75
|
+
|
|
76
|
+
def _read(self, directory: str, digest: str) -> bytes:
|
|
77
|
+
try:
|
|
78
|
+
data = self._path(directory, digest).read_bytes()
|
|
79
|
+
except OSError as exc:
|
|
80
|
+
raise EvidenceError(f"Missing {directory} artifact {digest}") from exc
|
|
81
|
+
if hashlib.sha256(data).hexdigest() != digest:
|
|
82
|
+
raise EvidenceError(f"Modified {directory} artifact {digest}")
|
|
83
|
+
return data
|
|
84
|
+
|
|
85
|
+
def _put(self, directory: str, data: bytes) -> str:
|
|
86
|
+
digest = hashlib.sha256(data).hexdigest()
|
|
87
|
+
target = self._path(directory, digest)
|
|
88
|
+
if target.exists():
|
|
89
|
+
self._read(directory, digest)
|
|
90
|
+
return digest
|
|
91
|
+
target.parent.mkdir(parents=True, exist_ok=True)
|
|
92
|
+
temp = tempfile.NamedTemporaryFile(dir=target.parent, delete=False)
|
|
93
|
+
try:
|
|
94
|
+
with temp:
|
|
95
|
+
temp.write(data)
|
|
96
|
+
temp.flush()
|
|
97
|
+
os.fsync(temp.fileno())
|
|
98
|
+
os.replace(temp.name, target)
|
|
99
|
+
finally:
|
|
100
|
+
Path(temp.name).unlink(missing_ok=True)
|
|
101
|
+
return digest
|
|
102
|
+
|
|
103
|
+
def keep(self, receipt: Artifact, body: bytes) -> None:
|
|
104
|
+
"""Evidence sink for configured collection. Raw artifacts are content-addressed."""
|
|
105
|
+
if len(body) != receipt.size or hashlib.sha256(body).hexdigest() != receipt.sha256:
|
|
106
|
+
raise EvidenceError("Evidence receipt mismatch")
|
|
107
|
+
self._put("objects", body)
|
|
108
|
+
|
|
109
|
+
def inputs(self, receipts):
|
|
110
|
+
"""Yield SHA-verified inputs for an offline parser."""
|
|
111
|
+
for artifact in receipts:
|
|
112
|
+
yield artifact, self._read("objects", artifact.sha256)
|
|
113
|
+
|
|
114
|
+
def reparse_product(self, result):
|
|
115
|
+
"""Verify normalized selected facts against the original SDK or HTTP payload, offline."""
|
|
116
|
+
from .routing.facts import event_versions
|
|
117
|
+
|
|
118
|
+
if (
|
|
119
|
+
result.source is None
|
|
120
|
+
or result.query.dataset.endswith(".daily")
|
|
121
|
+
or result.query.as_of is not None
|
|
122
|
+
):
|
|
123
|
+
raise EvidenceError("Expected a selected live minute, fundamental or event result")
|
|
124
|
+
name = result.source
|
|
125
|
+
attempt = next(
|
|
126
|
+
(
|
|
127
|
+
a
|
|
128
|
+
for a in result.attempts
|
|
129
|
+
if a.source == name and a.status in ("ok", "partial", "observed_empty")
|
|
130
|
+
),
|
|
131
|
+
None,
|
|
132
|
+
)
|
|
133
|
+
if attempt is None or not attempt.artifacts:
|
|
134
|
+
raise EvidenceError("Missing product evidence")
|
|
135
|
+
definition = self.registry.get(name)
|
|
136
|
+
if definition.parser_version != attempt.parser_version or definition.origin != attempt.origin:
|
|
137
|
+
raise EvidenceError("Recorded product parser or upstream differs")
|
|
138
|
+
spec = next(
|
|
139
|
+
(
|
|
140
|
+
p
|
|
141
|
+
for p in definition.products
|
|
142
|
+
if p.dataset == result.query.dataset and p.endpoint == attempt.endpoint
|
|
143
|
+
),
|
|
144
|
+
None,
|
|
145
|
+
)
|
|
146
|
+
if spec is None:
|
|
147
|
+
raise EvidenceError("Recorded native product is unavailable")
|
|
148
|
+
recorded_schemas = {origin.schema_version for row in result.rows for origin in row.origins.values()}
|
|
149
|
+
if recorded_schemas and recorded_schemas != {spec.schema_version}:
|
|
150
|
+
raise EvidenceError(f"Raw replay needs the recorded {name}/{spec.endpoint} product schema")
|
|
151
|
+
provider = self.registry.create(name)
|
|
152
|
+
capture = Capture(name, result.query.instrument.symbol, inputs=self.inputs(attempt.artifacts))
|
|
153
|
+
parsed = tuple(provider.read_facts(result.query, spec, capture))
|
|
154
|
+
capture.finish()
|
|
155
|
+
if spec.dataset.endswith(".dividends") and name in ("tushare", "baostock"):
|
|
156
|
+
parsed = tuple(event_versions(parsed, spec))
|
|
157
|
+
fields = result.query.fields or tuple(f.name for f in spec.fields)
|
|
158
|
+
|
|
159
|
+
def normalized(f):
|
|
160
|
+
return (
|
|
161
|
+
f.session,
|
|
162
|
+
f.key,
|
|
163
|
+
f.announced_on,
|
|
164
|
+
{k: f.values[k] for k in fields},
|
|
165
|
+
{k: v for k, v in f.missing.items() if k in fields},
|
|
166
|
+
)
|
|
167
|
+
|
|
168
|
+
if [normalized(f) for f in sorted(parsed, key=lambda f: (f.session, f.key))] != [
|
|
169
|
+
normalized(f) for f in result.rows
|
|
170
|
+
]:
|
|
171
|
+
raise EvidenceError("Reparsed product differs from the selected observation")
|
|
172
|
+
return result.rows
|
|
173
|
+
|
|
174
|
+
def record(
|
|
175
|
+
self, client: Client, query: Query, policy: Policy | None = None, *, policy_id: str = ""
|
|
176
|
+
) -> tuple[Result, str]:
|
|
177
|
+
"""Collect a fresh decision and publish its manifest after retaining all source bytes."""
|
|
178
|
+
policy = policy or Policy()
|
|
179
|
+
origins = {
|
|
180
|
+
name: p.origin
|
|
181
|
+
for name, p in client.providers.items()
|
|
182
|
+
if name in (*policy.sources, *policy.references)
|
|
183
|
+
}
|
|
184
|
+
observations = {}
|
|
185
|
+
options = {}
|
|
186
|
+
requests = {}
|
|
187
|
+
|
|
188
|
+
def keep(receipt: Artifact, data: bytes) -> None:
|
|
189
|
+
if self._put("objects", data) != receipt.sha256:
|
|
190
|
+
raise EvidenceError("Evidence receipt mismatch")
|
|
191
|
+
if client.evidence is not None:
|
|
192
|
+
client.evidence(receipt, data)
|
|
193
|
+
|
|
194
|
+
def read(name: str) -> Observation:
|
|
195
|
+
capture = Capture(name, query.symbol, keep, http=client.http)
|
|
196
|
+
result = client.observe(query, name, require_volume=False, capture=capture)
|
|
197
|
+
requests[name] = capture.requests
|
|
198
|
+
observations[name] = asdict(result)
|
|
199
|
+
provider = client.providers[name]
|
|
200
|
+
if hasattr(provider, "replay_options"):
|
|
201
|
+
options[name] = provider.replay_options()
|
|
202
|
+
return result
|
|
203
|
+
|
|
204
|
+
with client.session(), run_context() as correlation_id:
|
|
205
|
+
result = select(query, policy, origins, read)
|
|
206
|
+
run = {
|
|
207
|
+
"schema": SCHEMA,
|
|
208
|
+
"version": __version__,
|
|
209
|
+
"policy_id": policy_id,
|
|
210
|
+
"run_id": correlation_id,
|
|
211
|
+
"requests": requests,
|
|
212
|
+
"query": asdict(query),
|
|
213
|
+
"policy": asdict(policy),
|
|
214
|
+
"origins": origins,
|
|
215
|
+
"observations": observations,
|
|
216
|
+
"options": options,
|
|
217
|
+
"parsers": {
|
|
218
|
+
d.name: d.parser_version for d in client.registry.definitions if d.name in observations
|
|
219
|
+
},
|
|
220
|
+
"decision": _decision(result),
|
|
221
|
+
}
|
|
222
|
+
return result, self._put("runs", _encode(run))
|
|
223
|
+
|
|
224
|
+
def replay(self, run_id: str, *, reparse: bool = False) -> Result:
|
|
225
|
+
"""Verify every object and repeat selection. Optionally reparse the original built-in inputs."""
|
|
226
|
+
run = json.loads(self._read("runs", run_id))
|
|
227
|
+
if run.get("schema") != SCHEMA:
|
|
228
|
+
raise EvidenceError("Unsupported recording schema")
|
|
229
|
+
if reparse and "parsers" not in run and run["version"] != "0.1.0":
|
|
230
|
+
raise EvidenceError(f"Raw replay needs DoriData {run['version']}")
|
|
231
|
+
query = Query.daily(**run["query"])
|
|
232
|
+
policy = Policy(**run["policy"])
|
|
233
|
+
observations = {name: _observation(value) for name, value in run["observations"].items()}
|
|
234
|
+
decoders = Client([], registry=self.registry)
|
|
235
|
+
for name, observed in observations.items():
|
|
236
|
+
attempt = observed.attempt
|
|
237
|
+
inputs = [(a, self._read("objects", a.sha256)) for a in attempt.artifacts]
|
|
238
|
+
if any(
|
|
239
|
+
a.size != len(body) or a.provider != name or a.symbol != query.symbol for a, body in inputs
|
|
240
|
+
):
|
|
241
|
+
raise EvidenceError("Source identity or size differs from the recording")
|
|
242
|
+
# Transport, quota and permission failures are captured outcomes, not new network requests.
|
|
243
|
+
if reparse and inputs and attempt.status in ("ok", "incomplete", "invalid"):
|
|
244
|
+
try:
|
|
245
|
+
definition = self.registry.get(name)
|
|
246
|
+
except KeyError:
|
|
247
|
+
raise EvidenceError(f"No registered offline parser for {name}") from None
|
|
248
|
+
expected = run.get("parsers", {}).get(name, "1")
|
|
249
|
+
if definition.parser_version != expected or definition.origin != attempt.origin:
|
|
250
|
+
raise EvidenceError(f"Raw replay needs the recorded {name} parser {expected}")
|
|
251
|
+
decoders.providers[name] = self.registry.create(name, **run["options"].get(name, {}))
|
|
252
|
+
capture = Capture(name, query.symbol, inputs=inputs)
|
|
253
|
+
parsed = decoders.observe(query, name, require_volume=False, capture=capture)
|
|
254
|
+
capture.finish()
|
|
255
|
+
if (parsed.bars, parsed.attempt.status) != (observed.bars, attempt.status):
|
|
256
|
+
raise EvidenceError(f"Reparsed observations differ for {name}")
|
|
257
|
+
if reparse and attempt.status == "ok" and not inputs:
|
|
258
|
+
raise EvidenceError(f"No source bytes to reparse for {name}")
|
|
259
|
+
replayed = select(query, policy, run["origins"], observations.__getitem__)
|
|
260
|
+
if _encode(_decision(replayed)) != _encode(run["decision"]):
|
|
261
|
+
raise EvidenceError("Replayed decision differs from the recorded one")
|
|
262
|
+
return replayed
|
doridata/backtest.py
ADDED
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
"""Export DoriBT records from selected prices and separately supplied market rules."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from collections.abc import Iterable
|
|
6
|
+
from dataclasses import dataclass
|
|
7
|
+
from datetime import date
|
|
8
|
+
from decimal import Decimal
|
|
9
|
+
from typing import Literal
|
|
10
|
+
|
|
11
|
+
from .client import Result
|
|
12
|
+
from .model import number
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
@dataclass(frozen=True)
|
|
16
|
+
class SessionFacts:
|
|
17
|
+
symbol: str
|
|
18
|
+
session: date
|
|
19
|
+
upper_limit: Decimal | None
|
|
20
|
+
lower_limit: Decimal | None
|
|
21
|
+
status: Literal["trading", "suspended"] | None = None
|
|
22
|
+
unrestricted: bool = False
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def doribt_records(result: Result, facts: Iterable[SessionFacts]) -> list[dict[str, object]]:
|
|
26
|
+
"""Combine one verified raw-price window with explicitly keyed historical limits and trading status."""
|
|
27
|
+
if not result.calendar_verified or result.query.basis != "unadjusted":
|
|
28
|
+
raise ValueError("DoriBT requires accepted unadjusted bars and explicit sessions")
|
|
29
|
+
rules = {}
|
|
30
|
+
for fact in facts:
|
|
31
|
+
if fact.symbol != result.query.symbol or fact.session in rules:
|
|
32
|
+
raise ValueError("Mismatched symbol or duplicate trading facts")
|
|
33
|
+
if fact.status not in (None, "trading", "suspended"):
|
|
34
|
+
raise ValueError("Unknown trading state")
|
|
35
|
+
if fact.upper_limit is None or fact.lower_limit is None:
|
|
36
|
+
if not (fact.unrestricted and fact.upper_limit is None and fact.lower_limit is None):
|
|
37
|
+
raise ValueError("Supply both price limits, or explicitly confirm an unrestricted session")
|
|
38
|
+
elif fact.unrestricted or not 0 < number(fact.lower_limit) <= number(fact.upper_limit):
|
|
39
|
+
raise ValueError("Invalid price limits")
|
|
40
|
+
rules[fact.session] = fact
|
|
41
|
+
if set(rules) != {b.session for b in result.bars}:
|
|
42
|
+
raise ValueError("Historical trading facts must cover the same sessions as the selected prices")
|
|
43
|
+
rows = []
|
|
44
|
+
for bar in result.bars:
|
|
45
|
+
fact = rules[bar.session]
|
|
46
|
+
state = fact.status or bar.state
|
|
47
|
+
if state == "unknown" or (bar.state != "unknown" and state != bar.state):
|
|
48
|
+
raise ValueError(f"{bar.session}: missing or contradictory trading state")
|
|
49
|
+
if bar.volume is None or (state == "suspended" and bar.volume != 0):
|
|
50
|
+
raise ValueError(f"{bar.session}: missing volume or turnover during suspension")
|
|
51
|
+
if fact.upper_limit is not None and not (
|
|
52
|
+
number(fact.lower_limit) <= bar.low <= bar.high <= number(fact.upper_limit)
|
|
53
|
+
):
|
|
54
|
+
raise ValueError(f"{bar.session}: prices exceed the supplied historical limits")
|
|
55
|
+
rows.append(
|
|
56
|
+
{
|
|
57
|
+
"session": bar.session.isoformat(),
|
|
58
|
+
"symbol": fact.symbol,
|
|
59
|
+
"status": state,
|
|
60
|
+
"open": bar.open,
|
|
61
|
+
"high": bar.high,
|
|
62
|
+
"low": bar.low,
|
|
63
|
+
"close": bar.close,
|
|
64
|
+
"volume": bar.volume,
|
|
65
|
+
"upper_limit": fact.upper_limit,
|
|
66
|
+
"lower_limit": fact.lower_limit,
|
|
67
|
+
}
|
|
68
|
+
)
|
|
69
|
+
return rows
|
doridata/catalog.py
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
"""Machine-readable contracts of the registered sources."""
|
|
2
|
+
|
|
3
|
+
from .contracts.provider import Capability
|
|
4
|
+
from .model import Query
|
|
5
|
+
from .providers.registry import ProviderRegistry
|
|
6
|
+
|
|
7
|
+
CAPABILITIES = ProviderRegistry.builtin().capabilities()
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
def capabilities(
|
|
11
|
+
query: Query | None = None, *, registry: ProviderRegistry | None = None
|
|
12
|
+
) -> tuple[Capability, ...]:
|
|
13
|
+
if registry is not None:
|
|
14
|
+
return registry.capabilities(query)
|
|
15
|
+
return tuple(c for c in CAPABILITIES if query is None or c.matches(query))
|
doridata/cli.py
ADDED
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
"""JSON CLI for capability discovery, offline configuration and explicit live probes."""
|
|
2
|
+
|
|
3
|
+
import argparse
|
|
4
|
+
import json
|
|
5
|
+
import sys
|
|
6
|
+
from contextlib import redirect_stdout
|
|
7
|
+
from dataclasses import asdict, is_dataclass
|
|
8
|
+
|
|
9
|
+
from .config.profile import Configuration, ConfigurationError, Profile
|
|
10
|
+
from .contracts.records import DataQuery
|
|
11
|
+
from .model import Query
|
|
12
|
+
from .providers.registry import ProviderRegistry
|
|
13
|
+
from .routing.plan import describe
|
|
14
|
+
from .runtime import ConfiguredClient
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def main(argv=None):
|
|
18
|
+
parser = argparse.ArgumentParser(prog="doridata")
|
|
19
|
+
commands = parser.add_subparsers(dest="command", required=True)
|
|
20
|
+
info = commands.add_parser("describe")
|
|
21
|
+
info.add_argument("--source")
|
|
22
|
+
for command in ("validate", "plan", "doctor"):
|
|
23
|
+
p = commands.add_parser(command)
|
|
24
|
+
p.add_argument("--config", required=command == "validate")
|
|
25
|
+
p.add_argument("--profile", default="free")
|
|
26
|
+
if command != "validate":
|
|
27
|
+
p.add_argument("--source", required=command == "doctor")
|
|
28
|
+
p.add_argument("--symbol", required=True)
|
|
29
|
+
p.add_argument("--asset", choices=("stock", "etf"), required=True)
|
|
30
|
+
p.add_argument("--start", required=True)
|
|
31
|
+
p.add_argument("--end", required=True)
|
|
32
|
+
p.add_argument("--dataset")
|
|
33
|
+
p.add_argument("--fields", nargs="+")
|
|
34
|
+
args = parser.parse_args(argv)
|
|
35
|
+
try:
|
|
36
|
+
if args.command == "describe":
|
|
37
|
+
out = describe(ProviderRegistry.builtin(), args.source)
|
|
38
|
+
else:
|
|
39
|
+
profile = Configuration.load(args.config).profiles[args.profile] if args.config else Profile()
|
|
40
|
+
client = ConfiguredClient(profile)
|
|
41
|
+
if args.command == "validate":
|
|
42
|
+
out = {"status": "ok", "revision": profile.revision}
|
|
43
|
+
else:
|
|
44
|
+
q = Query.daily(args.symbol, args.start, args.end, asset=args.asset)
|
|
45
|
+
request = DataQuery(
|
|
46
|
+
q, args.dataset or "cn." + args.asset + ".daily", tuple(args.fields or ())
|
|
47
|
+
)
|
|
48
|
+
if args.command == "doctor":
|
|
49
|
+
# Vendor SDKs may print session banners. Preserve JSON-only stdout for CLI consumers.
|
|
50
|
+
with redirect_stdout(sys.stderr):
|
|
51
|
+
out = client.doctor(request, args.source)
|
|
52
|
+
else:
|
|
53
|
+
out = client.plan(request, sources=(args.source,) if args.source else None)
|
|
54
|
+
except ConfigurationError as exc:
|
|
55
|
+
print(json.dumps({"status": "invalid", "issues": [asdict(i) for i in exc.issues]}), file=sys.stderr)
|
|
56
|
+
return 2
|
|
57
|
+
except (ValueError, KeyError, OSError) as exc:
|
|
58
|
+
print(json.dumps({"status": "invalid", "message": str(exc)}), file=sys.stderr)
|
|
59
|
+
return 2
|
|
60
|
+
print(json.dumps(out, ensure_ascii=True, default=lambda v: asdict(v) if is_dataclass(v) else str(v)))
|
|
61
|
+
return 0 if args.command != "doctor" or out["status"] in ("ok", "observed_empty") else 1
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
if __name__ == "__main__":
|
|
65
|
+
sys.exit(main())
|