financecalendar 0.1.8__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.
- financecalendar/__init__.py +17 -0
- financecalendar/cli.py +502 -0
- financecalendar/client.py +546 -0
- financecalendar/py.typed +0 -0
- financecalendar-0.1.8.dist-info/METADATA +458 -0
- financecalendar-0.1.8.dist-info/RECORD +9 -0
- financecalendar-0.1.8.dist-info/WHEEL +4 -0
- financecalendar-0.1.8.dist-info/entry_points.txt +2 -0
- financecalendar-0.1.8.dist-info/licenses/LICENSE +21 -0
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
"""Python client for Finance Calendar paid data and Free Developer schedule JSON.
|
|
2
|
+
|
|
3
|
+
Connect source-aware release data with an account key. Starter bills annually.
|
|
4
|
+
Current pricing and source terms: https://www.financecalendar.com/pricing/.
|
|
5
|
+
The public browser calendar is free to browse.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from .client import (
|
|
9
|
+
DEFAULT_BASE,
|
|
10
|
+
MAX_RANGE_DAYS,
|
|
11
|
+
Client,
|
|
12
|
+
FinanceCalendarError,
|
|
13
|
+
to_dataframe,
|
|
14
|
+
)
|
|
15
|
+
|
|
16
|
+
__version__ = "0.1.8"
|
|
17
|
+
__all__ = ["Client", "FinanceCalendarError", "to_dataframe", "DEFAULT_BASE", "MAX_RANGE_DAYS", "__version__"]
|
financecalendar/cli.py
ADDED
|
@@ -0,0 +1,502 @@
|
|
|
1
|
+
"""financecalendar command line: the economic calendar in your terminal."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import argparse
|
|
6
|
+
import functools
|
|
7
|
+
import json
|
|
8
|
+
import re
|
|
9
|
+
import sys
|
|
10
|
+
from datetime import datetime, timezone
|
|
11
|
+
from typing import Any, Callable
|
|
12
|
+
from zoneinfo import ZoneInfo, ZoneInfoNotFoundError
|
|
13
|
+
|
|
14
|
+
import httpx
|
|
15
|
+
|
|
16
|
+
from .client import Client, FinanceCalendarError, __version__
|
|
17
|
+
|
|
18
|
+
ZONE_LABELS = {"America/New_York": "ET", "America/Chicago": "CT", "America/Los_Angeles": "PT", "UTC": "UTC", "Etc/UTC": "UTC"}
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def local_zone(tz: str | None):
|
|
22
|
+
if tz:
|
|
23
|
+
return ZoneInfo(tz)
|
|
24
|
+
return datetime.now().astimezone().tzinfo or timezone.utc
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def format_when(event: dict[str, Any], tz=None) -> str:
|
|
28
|
+
if event.get("date_window_start") and event.get("date_window_end"):
|
|
29
|
+
return f"{event['date_window_start']}–{event['date_window_end']} (estimated window)"
|
|
30
|
+
window = _format_window(event.get("time_window_start"), event.get("time_window_end"), tz or local_zone(None))
|
|
31
|
+
if window:
|
|
32
|
+
return window
|
|
33
|
+
if not event.get("release_at_utc") or event.get("all_day"):
|
|
34
|
+
d = event.get("date")
|
|
35
|
+
if not d:
|
|
36
|
+
return ""
|
|
37
|
+
timing = "all day" if event.get("category") == "market-holidays" else "time unknown"
|
|
38
|
+
return datetime.fromisoformat(d).strftime("%a %d %b") + f" {timing}"
|
|
39
|
+
zone = tz or local_zone(None)
|
|
40
|
+
dt = datetime.fromisoformat(event["release_at_utc"].replace("Z", "+00:00")).astimezone(zone)
|
|
41
|
+
name = getattr(zone, "key", None) or ""
|
|
42
|
+
label = ZONE_LABELS.get(name) or dt.tzname() or name
|
|
43
|
+
return dt.strftime("%a %d %b %H:%M") + f" {label}"
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def _format_window(start: Any, end: Any, zone) -> str | None:
|
|
47
|
+
if not isinstance(start, str) or not isinstance(end, str):
|
|
48
|
+
return None
|
|
49
|
+
try:
|
|
50
|
+
first = datetime.fromisoformat(start.replace("Z", "+00:00"))
|
|
51
|
+
last = datetime.fromisoformat(end.replace("Z", "+00:00"))
|
|
52
|
+
if first.tzinfo is None or last.tzinfo is None or last < first:
|
|
53
|
+
return None
|
|
54
|
+
first, last = first.astimezone(zone), last.astimezone(zone)
|
|
55
|
+
except ValueError:
|
|
56
|
+
return None
|
|
57
|
+
key = getattr(zone, "key", None) or ""
|
|
58
|
+
same_offset = first.utcoffset() == last.utcoffset()
|
|
59
|
+
label = ZONE_LABELS.get(key) or first.tzname() or key
|
|
60
|
+
if first.date() == last.date() and same_offset:
|
|
61
|
+
return first.strftime("%a %d %b %H:%M") + "–" + last.strftime("%H:%M") + f" {label}"
|
|
62
|
+
date_format = "%a %d %b %Y %H:%M" if first.year != last.year else "%a %d %b %H:%M"
|
|
63
|
+
def endpoint(value):
|
|
64
|
+
return value.strftime(date_format) + " " + ((ZONE_LABELS.get(key) if same_offset else None) or value.tzname() or key)
|
|
65
|
+
return endpoint(first) + "–" + endpoint(last)
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def format_event(event: dict[str, Any], tz=None) -> str:
|
|
69
|
+
name = event.get("name") or event.get("title") or ""
|
|
70
|
+
area = event.get("country")
|
|
71
|
+
if not area and event.get("category") == "crypto":
|
|
72
|
+
assets = "/".join(a.get("symbol") or a.get("id") or "" for a in event.get("assets") or [])
|
|
73
|
+
area = f"{assets} · Global" if assets else "Global"
|
|
74
|
+
bits = [format_when(event, tz), name + (f" ({area})" if area else "")]
|
|
75
|
+
activation = (event.get("crypto") or {}).get("activation_status")
|
|
76
|
+
if activation:
|
|
77
|
+
bits.append(f"activation {activation}")
|
|
78
|
+
environment = (event.get("crypto") or {}).get("environment")
|
|
79
|
+
if environment and not _contains_detail(name, environment):
|
|
80
|
+
bits.append(environment)
|
|
81
|
+
if event.get("time_role") == "auction-close" and not _contains_detail(name, "auction close"):
|
|
82
|
+
bits.append("auction close")
|
|
83
|
+
if event.get("period") and not _contains_detail(name, event["period"]):
|
|
84
|
+
bits.append(f"period {event['period']}")
|
|
85
|
+
if event.get("release_stage") and not _contains_detail(name, event["release_stage"]):
|
|
86
|
+
stage = re.sub(r"[-_]+", " ", str(event["release_stage"]))
|
|
87
|
+
bits.append(f"stage {stage}")
|
|
88
|
+
if event.get("consensus") is not None and event.get("consensus") != "":
|
|
89
|
+
bits.append(f"cons. {event['consensus']}")
|
|
90
|
+
if event.get("prior") is not None and event.get("prior") != "":
|
|
91
|
+
bits.append(f"prior {event['prior']}")
|
|
92
|
+
if event.get("actual") is not None and event.get("actual") != "":
|
|
93
|
+
bits.append(f"actual {event['actual']}")
|
|
94
|
+
if event.get("holiday_status") == "early_close" and event.get("close_time_local"):
|
|
95
|
+
bits.append(f"closes {event['close_time_local']} local")
|
|
96
|
+
line = " ".join(b for b in bits if b)
|
|
97
|
+
lines = [line]
|
|
98
|
+
if event.get("url"):
|
|
99
|
+
lines.append(event["url"])
|
|
100
|
+
if event.get("data_stale"):
|
|
101
|
+
lines.append("Stale source data" + (f" since {event['stale_since']}" if event.get("stale_since") else ""))
|
|
102
|
+
if event.get("observation_status") == "stale":
|
|
103
|
+
lines.append("Official observation data stale; calendar freshness is reported separately.")
|
|
104
|
+
for observation in event.get("observations") or []:
|
|
105
|
+
if not isinstance(observation, dict):
|
|
106
|
+
continue
|
|
107
|
+
role = observation.get("role") or "value"
|
|
108
|
+
value = str(observation["value"]) if observation.get("value") is not None else "unknown"
|
|
109
|
+
unit = " " + str(observation["unit"]) if observation.get("unit") else ""
|
|
110
|
+
lines.append(f"Official {role}: {value}{unit} · reference period {observation.get('reference_period') or 'unknown'} · current observed vintage")
|
|
111
|
+
if role == "prior":
|
|
112
|
+
lines.append("Prior is the previous reference period at the current observed vintage, not the original first print.")
|
|
113
|
+
if observation.get("data_stale"):
|
|
114
|
+
lines.append(f"Stale official {role} observation; schedule freshness is independent.")
|
|
115
|
+
if observation.get("known_at"):
|
|
116
|
+
lines.append(f"Value observed by Finance Calendar: {observation['known_at']}; not the publisher's first-print timestamp.")
|
|
117
|
+
if observation.get("revision_history"):
|
|
118
|
+
lines.append(f"Recorded value revisions: {len(observation['revision_history'])} (observed by Finance Calendar).")
|
|
119
|
+
if observation.get("source_url"):
|
|
120
|
+
lines.append(f"Observation source: {observation['source_url']}")
|
|
121
|
+
license_info = observation.get("source_license")
|
|
122
|
+
if isinstance(license_info, dict):
|
|
123
|
+
credit = " · " + license_info["attribution"] if license_info.get("attribution") else ""
|
|
124
|
+
lines.append(f"Observation licence: {license_info.get('spdx') or license_info.get('id') or ''}{credit}")
|
|
125
|
+
if license_info.get("url"):
|
|
126
|
+
lines.append(license_info["url"])
|
|
127
|
+
if license_info.get("notice"):
|
|
128
|
+
lines.append(license_info["notice"])
|
|
129
|
+
rights = observation.get("source_rights")
|
|
130
|
+
if isinstance(rights, dict):
|
|
131
|
+
if rights.get("attribution"):
|
|
132
|
+
lines.append(rights["attribution"])
|
|
133
|
+
if rights.get("url"):
|
|
134
|
+
lines.append(f"Publisher rights policy: {rights['url']}")
|
|
135
|
+
if rights.get("vintage_notice"):
|
|
136
|
+
lines.append(rights["vintage_notice"])
|
|
137
|
+
if event.get("verification_url"):
|
|
138
|
+
lines.append(f"Verification: {event['verification_url']}")
|
|
139
|
+
if event.get("manually_reviewed_at"):
|
|
140
|
+
lines.append(f"Manually reviewed: {event['manually_reviewed_at']}")
|
|
141
|
+
if (event.get("crypto") or {}).get("event_type") == "supply-projection":
|
|
142
|
+
lines.append("Issuer supply projection; not a confirmed unlock or observed circulating supply.")
|
|
143
|
+
if (event.get("crypto") or {}).get("event_type") == "governance-vote":
|
|
144
|
+
lines.append("Governance voting deadline; not a proposal outcome or execution.")
|
|
145
|
+
if event.get("source_license"):
|
|
146
|
+
license_info = event["source_license"]
|
|
147
|
+
adapted = " · adapted by Finance Calendar" if license_info.get("adapted") else ""
|
|
148
|
+
lines.append(f"Original source: {license_info.get('attribution') or event.get('source_name') or ''} · {license_info.get('spdx') or license_info.get('id') or ''}{adapted}")
|
|
149
|
+
if event.get("source_url"):
|
|
150
|
+
lines.append(event["source_url"])
|
|
151
|
+
if license_info.get("attribution_url"):
|
|
152
|
+
lines.append(f"Attribution: {license_info['attribution_url']}")
|
|
153
|
+
if license_info.get("url"):
|
|
154
|
+
lines.append(license_info["url"])
|
|
155
|
+
if license_info.get("terms_url"):
|
|
156
|
+
lines.append(f"Publisher terms: {license_info['terms_url']}")
|
|
157
|
+
if license_info.get("notice"):
|
|
158
|
+
lines.append(license_info["notice"])
|
|
159
|
+
if event.get("source_rights"):
|
|
160
|
+
rights = event["source_rights"]
|
|
161
|
+
lines.append(f"Factual source: {rights.get('attribution') or event.get('source_name') or ''}")
|
|
162
|
+
if event.get("source_url") and not event.get("source_license"):
|
|
163
|
+
lines.append(event["source_url"])
|
|
164
|
+
if rights.get("source_url") and rights["source_url"] != event.get("source_url"):
|
|
165
|
+
lines.append(f"Rights evidence: {rights['source_url']}")
|
|
166
|
+
if rights.get("basis"):
|
|
167
|
+
lines.append(f"Rights basis: {rights['basis']}; not a publisher copyright licence.")
|
|
168
|
+
if rights.get("access_basis"):
|
|
169
|
+
lines.append(f"Source access: {rights['access_basis']}")
|
|
170
|
+
if rights.get("terms_url"):
|
|
171
|
+
lines.append(f"Publisher terms: {rights['terms_url']}")
|
|
172
|
+
if rights.get("notice"):
|
|
173
|
+
lines.append(rights["notice"])
|
|
174
|
+
if event.get("discovery_url"):
|
|
175
|
+
lines.append(f"Discovery (not verification): {event['discovery_url']}")
|
|
176
|
+
return "\n".join(lines)
|
|
177
|
+
|
|
178
|
+
|
|
179
|
+
def _contains_detail(name: str, detail: Any) -> bool:
|
|
180
|
+
def words(value: Any) -> str:
|
|
181
|
+
return re.sub(r"[^a-z0-9]+", " ", str(value).casefold()).strip()
|
|
182
|
+
normalized = words(detail)
|
|
183
|
+
return bool(normalized and f" {normalized} " in f" {words(name)} ")
|
|
184
|
+
|
|
185
|
+
|
|
186
|
+
def format_events(events: list[dict[str, Any]], tz=None) -> str:
|
|
187
|
+
return "\n".join(format_event(e, tz) for e in events)
|
|
188
|
+
|
|
189
|
+
|
|
190
|
+
def format_holiday(h: dict[str, Any]) -> str:
|
|
191
|
+
status = "closed" if h.get("status") != "early_close" else f"early close {h.get('close_time_local') or h.get('close_time_et') or ''}".strip()
|
|
192
|
+
exch = f"{h['exchange'].upper()} " if h.get("exchange") else ""
|
|
193
|
+
return f"{h['date']} {h['name']} {exch}{status}"
|
|
194
|
+
|
|
195
|
+
|
|
196
|
+
def format_series(s: dict[str, Any]) -> str:
|
|
197
|
+
start, end = s.get("next_date_window_start"), s.get("next_date_window_end")
|
|
198
|
+
if start and end:
|
|
199
|
+
nxt = f"next target {start}–{end} (estimated window)"
|
|
200
|
+
elif start or end:
|
|
201
|
+
nxt = "next target window tbc"
|
|
202
|
+
else:
|
|
203
|
+
nxt = f"next {s['next_date']}" if s.get("next_date") else "next tbc"
|
|
204
|
+
return f"{s['code']:<24} {s.get('name') or '':<44} {s.get('country') or ('Global' if s.get('category') == 'crypto' else '--'):<3} {s.get('impact') or '':<7} {nxt}"
|
|
205
|
+
|
|
206
|
+
|
|
207
|
+
def format_change(c: dict[str, Any]) -> str:
|
|
208
|
+
def value(v):
|
|
209
|
+
if v is None:
|
|
210
|
+
return "-"
|
|
211
|
+
return json.dumps(v, separators=(",", ":"), ensure_ascii=False) if isinstance(v, (dict, list, bool)) else str(v)
|
|
212
|
+
what = f" {c['field']}: {value(c.get('old'))} -> {value(c.get('new'))}" if c.get("field") else ""
|
|
213
|
+
return f"{c['at']} {c['change']:<7} {c['series_code']:<16} {c['id']}{what}"
|
|
214
|
+
|
|
215
|
+
|
|
216
|
+
def build_parser() -> argparse.ArgumentParser:
|
|
217
|
+
p = argparse.ArgumentParser(prog="financecalendar", description="Economic calendar in your terminal. Starter bills annually and includes 1,000/day, 25,000/month. Ongoing Free Developer: schedule JSON, 100 successful responses/month, 10/day, one key after approval, no card. Only today/calendar schedule JSON within seven UTC dates, at most 20 records; other routes/formats require paid access. Do not add timezone or pagination flags to Free calls. https://www.financecalendar.com/pricing/")
|
|
218
|
+
p.add_argument("--version", action="version", version=f"financecalendar {__version__}")
|
|
219
|
+
|
|
220
|
+
def add_global_options(parser: argparse.ArgumentParser, default: Any) -> None:
|
|
221
|
+
# The top-level parser carries the real defaults; subparsers use SUPPRESS so the
|
|
222
|
+
# options are accepted before or after the command without overwriting each other.
|
|
223
|
+
parser.add_argument("--json", action="store_true", default=default if default is not None else False, help="print the raw API response")
|
|
224
|
+
parser.add_argument("--tz", default=default, help="IANA zone for displayed times (default: your local zone)")
|
|
225
|
+
parser.add_argument("--api-key", default=default, help="API key (default: FC_API_KEY)")
|
|
226
|
+
parser.add_argument("--base-url", default=default, help="API base URL (default: FC_API_BASE or production)")
|
|
227
|
+
|
|
228
|
+
add_global_options(p, None)
|
|
229
|
+
common = argparse.ArgumentParser(add_help=False)
|
|
230
|
+
add_global_options(common, argparse.SUPPRESS)
|
|
231
|
+
subparsers = p.add_subparsers(dest="cmd", required=True)
|
|
232
|
+
|
|
233
|
+
class _Sub:
|
|
234
|
+
def add_parser(self, name: str, **kw: Any) -> argparse.ArgumentParser:
|
|
235
|
+
return subparsers.add_parser(name, parents=[common], **kw)
|
|
236
|
+
|
|
237
|
+
sub = _Sub()
|
|
238
|
+
|
|
239
|
+
s = sub.add_parser("next", help="next occurrence of a series")
|
|
240
|
+
s.add_argument("series")
|
|
241
|
+
s.add_argument("--country")
|
|
242
|
+
s.add_argument("--asset", help="canonical crypto asset ID, e.g. ethereum (not ETH)")
|
|
243
|
+
s.add_argument("--category")
|
|
244
|
+
|
|
245
|
+
s = sub.add_parser("today", help="today's releases; paid access also includes NYSE status")
|
|
246
|
+
s.add_argument("--country")
|
|
247
|
+
s.add_argument("--asset", help="canonical crypto asset ID, e.g. ethereum (not ETH)")
|
|
248
|
+
s.add_argument("--category")
|
|
249
|
+
|
|
250
|
+
s = sub.add_parser("week", help="this week, Monday to Sunday")
|
|
251
|
+
s.add_argument("--next", action="store_true", help="next week instead")
|
|
252
|
+
s.add_argument("--category")
|
|
253
|
+
s.add_argument("--country")
|
|
254
|
+
s.add_argument("--asset", help="canonical crypto asset ID, e.g. ethereum (not ETH)")
|
|
255
|
+
s.add_argument("--impact")
|
|
256
|
+
s.add_argument("--series")
|
|
257
|
+
|
|
258
|
+
s = sub.add_parser("calendar", help="events in a date range (paid: max 92 days; Free: seven UTC dates)")
|
|
259
|
+
s.add_argument("--from", dest="from_")
|
|
260
|
+
s.add_argument("--to")
|
|
261
|
+
s.add_argument("--country")
|
|
262
|
+
s.add_argument("--asset", help="canonical crypto asset ID, e.g. ethereum (not ETH)")
|
|
263
|
+
s.add_argument("--impact")
|
|
264
|
+
s.add_argument("--category")
|
|
265
|
+
s.add_argument("--series")
|
|
266
|
+
s.add_argument("--holidays", action="store_true", help="include exchange holiday rows")
|
|
267
|
+
s.add_argument("--status", help="confirmed, estimated or released; comma-separated")
|
|
268
|
+
s.add_argument("--limit", type=int, help="rows to return, 1 to 500")
|
|
269
|
+
s.add_argument("--offset", type=int, help="skip this many rows (paging)")
|
|
270
|
+
s.add_argument("--csv", action="store_true", help="print the API's CSV")
|
|
271
|
+
|
|
272
|
+
s = sub.add_parser("series", help="list every series")
|
|
273
|
+
s.add_argument("--country")
|
|
274
|
+
s.add_argument("--asset", help="canonical crypto asset ID, e.g. ethereum (not ETH)")
|
|
275
|
+
s.add_argument("--category")
|
|
276
|
+
s.add_argument("--kind", choices=["instance", "holiday"])
|
|
277
|
+
|
|
278
|
+
s = sub.add_parser("show", help="one series in detail")
|
|
279
|
+
s.add_argument("code")
|
|
280
|
+
s.add_argument("--asset")
|
|
281
|
+
|
|
282
|
+
s = sub.add_parser("history", help="past releases of a series")
|
|
283
|
+
s.add_argument("series")
|
|
284
|
+
s.add_argument("--asset")
|
|
285
|
+
s.add_argument("--from", dest="from_")
|
|
286
|
+
s.add_argument("--to")
|
|
287
|
+
s.add_argument("--limit", type=int)
|
|
288
|
+
|
|
289
|
+
for command, label in (("archive-observations", "reference-period start"), ("archive-releases", "publisher publication"), ("history-coverage", None), ("historic-editions", "source-edition publication"), ("historic-forecasts", "forecast issue-period start index"), ("vintage-coverage", None)):
|
|
290
|
+
s = sub.add_parser(command, help="historical archive JSON by " + label + " date" if label else "measured historical coverage JSON")
|
|
291
|
+
s.add_argument("--metric-id", help="exact reviewed metric ID")
|
|
292
|
+
s.add_argument("--series-code", help="exact public series code")
|
|
293
|
+
s.add_argument("--source-id", help="original-source identifier")
|
|
294
|
+
s.add_argument("--limit", type=int, default=100, help="rows per page, 1 to 500")
|
|
295
|
+
s.add_argument("--cursor", help="repeat original filters and limit with the returned opaque cursor")
|
|
296
|
+
s.add_argument("--all", action="store_true", help="buffer every pinned page and print only a complete export")
|
|
297
|
+
if label:
|
|
298
|
+
s.add_argument("--from", dest="from_", help=f"inclusive {label} date YYYY-MM-DD")
|
|
299
|
+
s.add_argument("--to", help=f"inclusive {label} date YYYY-MM-DD")
|
|
300
|
+
s.add_argument("--order", choices=["asc", "desc"])
|
|
301
|
+
s.add_argument("--as-of", help="FC durable-evidence receipt cutoff in UTC, not original market availability")
|
|
302
|
+
if command in {"historic-editions", "historic-forecasts"}:
|
|
303
|
+
s.add_argument("--available-before", help="strict exact UTC source-availability cutoff; excludes unknown/date-only clocks")
|
|
304
|
+
else:
|
|
305
|
+
s.add_argument("--kind", choices=["editions", "forecasts"] if command == "vintage-coverage" else ["observations", "releases"])
|
|
306
|
+
|
|
307
|
+
s = sub.add_parser("holidays", help="exchange holidays")
|
|
308
|
+
s.add_argument("exchange", nargs="?", default="nyse")
|
|
309
|
+
s.add_argument("year", nargs="?", type=int)
|
|
310
|
+
|
|
311
|
+
s = sub.add_parser("status", help="is the exchange open right now?")
|
|
312
|
+
s.add_argument("exchange", nargs="?", default="nyse")
|
|
313
|
+
|
|
314
|
+
s = sub.add_parser("changes", help="what changed in the calendar")
|
|
315
|
+
s.add_argument("--since")
|
|
316
|
+
s.add_argument("--cursor", help="next_cursor from a prior page; omit since/series/change when continuing")
|
|
317
|
+
s.add_argument("--series")
|
|
318
|
+
s.add_argument("--change", choices=["added", "updated", "removed"])
|
|
319
|
+
s.add_argument("--limit", type=int, help="rows to return, 1 to 500")
|
|
320
|
+
|
|
321
|
+
sub.add_parser("countries", help="countries covered")
|
|
322
|
+
sub.add_parser("health", help="API health (snapshot age and counts)")
|
|
323
|
+
return p
|
|
324
|
+
|
|
325
|
+
|
|
326
|
+
def run(args: argparse.Namespace, client: Client, out: Callable[[str], None]) -> int:
|
|
327
|
+
tz = args.tz
|
|
328
|
+
# Resolved on first use, after the request, so an invalid tz sent to the API gets the API's own error.
|
|
329
|
+
zone = functools.lru_cache(maxsize=None)(lambda: local_zone(tz))
|
|
330
|
+
fmt = lambda events: format_events(events, zone()) # noqa: E731
|
|
331
|
+
cmd = args.cmd
|
|
332
|
+
|
|
333
|
+
if cmd == "next":
|
|
334
|
+
data = client.next(args.series, country=args.country, asset=args.asset, category=args.category, tz=tz)
|
|
335
|
+
return _emit(args, out, data, lambda: format_event(data["next"], zone()))
|
|
336
|
+
if cmd == "today":
|
|
337
|
+
data = client.today(country=args.country, asset=args.asset, category=args.category, tz=tz)
|
|
338
|
+
|
|
339
|
+
def human() -> str:
|
|
340
|
+
lines = []
|
|
341
|
+
m = data.get("market")
|
|
342
|
+
if m:
|
|
343
|
+
lines.append(f"{data['date']} {m['label']}" + (f" ({m['holiday']})" if m.get("holiday") else ""))
|
|
344
|
+
lines.append(fmt(data["events"]) if data.get("events") else "No scheduled releases today.")
|
|
345
|
+
if data.get("market_holidays"):
|
|
346
|
+
lines += ["", "Exchange closures today:", fmt(data["market_holidays"])]
|
|
347
|
+
return "\n".join(lines)
|
|
348
|
+
|
|
349
|
+
return _emit(args, out, data, human)
|
|
350
|
+
if cmd == "week":
|
|
351
|
+
data = client.week("next" if args.next else "this", country=args.country, impact=args.impact, asset=args.asset, category=args.category, series=args.series, tz=tz)
|
|
352
|
+
label = "Next week" if args.next else "This week"
|
|
353
|
+
return _emit(args, out, data, lambda: f"{label}, {data['from']} to {data['to']} ({data.get('total', data['count'])} events)\n\n" + (fmt(data["events"]) if data.get("events") else "No scheduled releases."))
|
|
354
|
+
if cmd == "calendar":
|
|
355
|
+
params = dict(from_=args.from_, to=args.to, country=args.country, impact=args.impact, category=args.category, asset=args.asset, series=args.series, include_holidays=args.holidays, status=args.status, tz=tz, limit=args.limit, offset=args.offset)
|
|
356
|
+
if args.csv:
|
|
357
|
+
out(client.calendar_csv(**params).rstrip("\n"))
|
|
358
|
+
return 0
|
|
359
|
+
data = client.calendar(**params)
|
|
360
|
+
return _emit(args, out, data, lambda: f"{data['from']} to {data['to']}: {data['count']} of {data['total']} events\n\n" + (fmt(data["events"]) if data.get("events") else "No scheduled releases in that range."))
|
|
361
|
+
if cmd == "series":
|
|
362
|
+
data = client.series(country=args.country, category=args.category, asset=args.asset, kind=args.kind)
|
|
363
|
+
return _emit(args, out, data, lambda: "\n".join(format_series(s) for s in data["series"]))
|
|
364
|
+
if cmd == "show":
|
|
365
|
+
data = client.series_detail(args.code, asset=args.asset, tz=tz)
|
|
366
|
+
|
|
367
|
+
def human() -> str:
|
|
368
|
+
s = data["series"]
|
|
369
|
+
lines = [f"{s['name']} ({s['code']}) {s.get('country') or ('Global' if s.get('category') == 'crypto' else '')} {s['category']} impact {s['impact'] if s['impact'] is not None else 'unrated'} {s.get('recurrence') or ''}".rstrip()]
|
|
370
|
+
if s.get("aliases"):
|
|
371
|
+
lines.append("aliases: " + ", ".join(s["aliases"]))
|
|
372
|
+
if s.get("publisher"):
|
|
373
|
+
lines.append(f"publisher: {s['publisher']}" + (f" {s['source_url']}" if s.get("source_url") else ""))
|
|
374
|
+
if s.get("hub"):
|
|
375
|
+
lines.append(f"hub: {s['hub']}")
|
|
376
|
+
lines.append("")
|
|
377
|
+
lines.append("Next:\n" + format_event(data["next"], zone()) if data.get("next") else "Next: none scheduled")
|
|
378
|
+
if data.get("last"):
|
|
379
|
+
lines.append("\nLast:\n" + format_event(data["last"], zone()))
|
|
380
|
+
if len(data.get("upcoming") or []) > 1:
|
|
381
|
+
lines += ["", f"Upcoming ({len(data['upcoming'])}):", fmt(data["upcoming"][:8])]
|
|
382
|
+
return "\n".join(lines)
|
|
383
|
+
|
|
384
|
+
return _emit(args, out, data, human)
|
|
385
|
+
if cmd == "history":
|
|
386
|
+
data = client.history(args.series, from_=args.from_, to=args.to, limit=args.limit, asset=args.asset, tz=tz)
|
|
387
|
+
return _emit(args, out, data, lambda: f"{data.get('series_code') or args.series}: {data['count']} releases, {data['from']} to {data['to']}\n\n" + (fmt(data["events"]) if data.get("events") else "No past releases in that range."))
|
|
388
|
+
if cmd in {"archive-observations", "archive-releases", "history-coverage", "historic-editions", "historic-forecasts", "vintage-coverage"}:
|
|
389
|
+
if not 1 <= args.limit <= 500:
|
|
390
|
+
raise ValueError("Archive --limit must be from 1 to 500")
|
|
391
|
+
if args.tz is not None:
|
|
392
|
+
raise ValueError("Archive date filters retain their documented basis; --tz is not supported")
|
|
393
|
+
coverage = cmd in {"history-coverage", "vintage-coverage"}
|
|
394
|
+
if not coverage and not (args.metric_id or args.series_code):
|
|
395
|
+
raise ValueError(f"{cmd} needs --metric-id ID or --series-code CODE")
|
|
396
|
+
if args.all and args.cursor:
|
|
397
|
+
raise ValueError("--all starts at the first page; omit --cursor")
|
|
398
|
+
params = dict(metric_id=args.metric_id, series_code=args.series_code, source_id=args.source_id, limit=args.limit, cursor=args.cursor)
|
|
399
|
+
if coverage:
|
|
400
|
+
params["kind"] = args.kind
|
|
401
|
+
read = client.vintage_coverage if cmd == "vintage-coverage" else client.history_coverage
|
|
402
|
+
else:
|
|
403
|
+
params.update(from_=args.from_, to=args.to, order=args.order, as_of=args.as_of)
|
|
404
|
+
if cmd in {"historic-editions", "historic-forecasts"}:
|
|
405
|
+
params["available_before"] = args.available_before
|
|
406
|
+
read = {"archive-observations": client.archive_observations, "archive-releases": client.archive_releases,
|
|
407
|
+
"historic-editions": client.archive_editions, "historic-forecasts": client.archive_forecasts}[cmd]
|
|
408
|
+
out(json.dumps(_archive_output(read, params, complete=args.all), indent=2))
|
|
409
|
+
return 0
|
|
410
|
+
if cmd == "holidays":
|
|
411
|
+
data = client.holidays(args.exchange, year=args.year)
|
|
412
|
+
return _emit(args, out, data, lambda: f"{data['exchange'].upper()} holidays ({data['count']})\n\n" + "\n".join(format_holiday(h) for h in data["holidays"]))
|
|
413
|
+
if cmd == "status":
|
|
414
|
+
data = client.market_status(args.exchange)
|
|
415
|
+
|
|
416
|
+
def human() -> str:
|
|
417
|
+
lines = [f"{data['label']} ({data.get('local_time') or data.get('time_utc')})"]
|
|
418
|
+
sess = data.get("session")
|
|
419
|
+
if sess:
|
|
420
|
+
lines.append(f"session {sess['open']}-{sess['close']}" + (f" (break {sess['break']})" if sess.get("break") else "") + f" {data.get('tz') or ''}".rstrip())
|
|
421
|
+
if data.get("holiday_today"):
|
|
422
|
+
lines.append(f"holiday today: {data['holiday_today']}")
|
|
423
|
+
nh = data.get("next_holiday")
|
|
424
|
+
if nh:
|
|
425
|
+
lines.append(f"next holiday: {nh['date']} {nh['name']} {nh['status']}")
|
|
426
|
+
return "\n".join(lines)
|
|
427
|
+
|
|
428
|
+
return _emit(args, out, data, human)
|
|
429
|
+
if cmd == "changes":
|
|
430
|
+
data = client.changes(since=args.since, series=args.series, change=args.change, limit=args.limit, cursor=args.cursor)
|
|
431
|
+
more = (f"\nMore changes: rerun changes --cursor '{data['next_cursor']}'. Complete all pages before advancing since."
|
|
432
|
+
if data.get("has_more") else "")
|
|
433
|
+
return _emit(args, out, data, lambda: f"{data['count']} changes since {data['since']}\n\n" + ("\n".join(format_change(c) for c in data["changes"]) if data.get("changes") else "No changes.") + more)
|
|
434
|
+
if cmd == "countries":
|
|
435
|
+
data = client.countries()
|
|
436
|
+
return _emit(args, out, data, lambda: "\n".join(f"{c['code']} {c.get('name') or '':<16} {c['series']:>3} series {c['events']:>5} events" for c in data["countries"]))
|
|
437
|
+
if cmd == "health":
|
|
438
|
+
data = client.status()
|
|
439
|
+
return _emit(args, out, data, lambda: json.dumps(data, indent=2))
|
|
440
|
+
raise SystemExit(f"Unknown command {cmd}")
|
|
441
|
+
|
|
442
|
+
|
|
443
|
+
def _emit(args: argparse.Namespace, out: Callable[[str], None], data: Any, human: Callable[[], str]) -> int:
|
|
444
|
+
out(json.dumps(data, indent=2) if args.json else human())
|
|
445
|
+
return 0
|
|
446
|
+
|
|
447
|
+
|
|
448
|
+
def _archive_output(read: Callable[..., dict[str, Any]], params: dict[str, Any], *, complete: bool) -> dict[str, Any]:
|
|
449
|
+
"""Retain page metadata and never print a partial multi-page success."""
|
|
450
|
+
collected: list[dict[str, Any]] = []
|
|
451
|
+
seen: set[str] = set()
|
|
452
|
+
first: dict[str, Any] | None = None
|
|
453
|
+
for page_number in range(10000):
|
|
454
|
+
page = read(**params)
|
|
455
|
+
rows, revision, cursor = page.get("rows"), page.get("archive_revision"), page.get("next_cursor")
|
|
456
|
+
if (not isinstance(rows, list) or any(not isinstance(row, dict) for row in rows)
|
|
457
|
+
or not isinstance(revision, int) or isinstance(revision, bool) or revision < 0
|
|
458
|
+
or page.get("count") != len(rows) or not isinstance(page.get("has_more"), bool)
|
|
459
|
+
or cursor is not None and (not isinstance(cursor, str) or not cursor or len(cursor) > 2048)
|
|
460
|
+
or page["has_more"] != (cursor is not None) or cursor is not None and not rows):
|
|
461
|
+
raise FinanceCalendarError(502, "Malformed historical archive page; export is incomplete")
|
|
462
|
+
if first is None:
|
|
463
|
+
first = page
|
|
464
|
+
if revision != first["archive_revision"]:
|
|
465
|
+
raise FinanceCalendarError(409, "Historical archive changed; discard the partial export and restart")
|
|
466
|
+
if not complete:
|
|
467
|
+
return page
|
|
468
|
+
collected.extend(rows)
|
|
469
|
+
if cursor is None:
|
|
470
|
+
return {**first, "rows": collected, "count": len(collected), "has_more": False, "next_cursor": None, "pages": page_number + 1}
|
|
471
|
+
if cursor in seen or cursor == params.get("cursor"):
|
|
472
|
+
raise FinanceCalendarError(502, "Historical archive cursor repeated; export is incomplete")
|
|
473
|
+
seen.add(cursor)
|
|
474
|
+
params = {**params, "cursor": cursor}
|
|
475
|
+
raise FinanceCalendarError(502, "Historical archive traversal exceeded 10000 pages; no complete export was produced")
|
|
476
|
+
|
|
477
|
+
|
|
478
|
+
def main(argv: list[str] | None = None, client: Client | None = None, out: Callable[[str], None] = print) -> int:
|
|
479
|
+
args = build_parser().parse_args(argv)
|
|
480
|
+
own = client is None
|
|
481
|
+
client = client or Client(base_url=args.base_url, api_key=args.api_key)
|
|
482
|
+
try:
|
|
483
|
+
return run(args, client, out)
|
|
484
|
+
except FinanceCalendarError as exc:
|
|
485
|
+
print(f"Error: {exc}", file=sys.stderr)
|
|
486
|
+
return 1
|
|
487
|
+
except httpx.HTTPError as exc:
|
|
488
|
+
print(f"Error: could not reach {client.base_url}: {exc.__class__.__name__}: {exc}", file=sys.stderr)
|
|
489
|
+
return 1
|
|
490
|
+
except ZoneInfoNotFoundError as exc:
|
|
491
|
+
print(f"Error: unknown timezone {exc.args[0] if exc.args else args.tz}; use an IANA name such as Europe/London", file=sys.stderr)
|
|
492
|
+
return 2
|
|
493
|
+
except ValueError as exc:
|
|
494
|
+
print(f"Error: {exc}", file=sys.stderr)
|
|
495
|
+
return 2
|
|
496
|
+
finally:
|
|
497
|
+
if own:
|
|
498
|
+
client.close()
|
|
499
|
+
|
|
500
|
+
|
|
501
|
+
if __name__ == "__main__": # pragma: no cover
|
|
502
|
+
sys.exit(main())
|