-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathcli.py
More file actions
226 lines (182 loc) · 7.03 KB
/
Copy pathcli.py
File metadata and controls
226 lines (182 loc) · 7.03 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
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
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
"""young-stock-cli command line interface."""
from __future__ import annotations
import dataclasses
import json
import subprocess
import sys
from typing import Any
import click
from . import __version__, _core
@click.group(
context_settings={"help_option_names": ["-h", "--help"]},
help="A-share & global market after-hours CLI. No login, no scraping tricks.",
)
@click.version_option(__version__, "-V", "--version", message="young-stock-cli %(version)s")
def cli() -> None:
pass
def _json_default(value: Any) -> Any:
if dataclasses.is_dataclass(value):
return dataclasses.asdict(value)
if hasattr(value, "to_dict"):
return value.to_dict()
raise TypeError(f"Object of type {type(value).__name__} is not JSON serializable")
def _echo_json(payload: Any) -> None:
click.echo(json.dumps(payload, ensure_ascii=False, default=_json_default))
def _run(market: str, date: str | None, refresh: bool, as_json: bool = False) -> None:
if refresh:
_core.NO_CACHE = True
_core.cache_clear_old(days=7)
date_str = date or _core.nearest_trade_date()
if as_json:
if market == "a":
_echo_json(_a_share_payload(date_str))
elif market == "hk":
_echo_json(_hk_market_payload(date_str))
elif market == "us":
_echo_json(_us_market_payload(date_str))
elif market == "global":
_echo_json(_global_market_payload(date_str))
else:
click.echo(f"unknown market: {market}", err=True)
sys.exit(1)
return
if market == "a":
_core.run_a_share(date_str)
elif market == "hk":
_core.run_hk_market(date_str)
elif market == "us":
_core.run_us_market(date_str)
elif market == "global":
_core.run_global_market(date_str)
else:
click.echo(f"unknown market: {market}", err=True)
sys.exit(1)
_date_opt = click.option("--date", "-d", default=None, help="Trade date YYYYMMDD (default: nearest trade day).")
_refresh_opt = click.option("--refresh", is_flag=True, help="Skip cache and force re-fetch.")
_json_opt = click.option("--json", "as_json", is_flag=True, help="Output raw data as JSON.")
def _a_share_payload(date_str: str) -> dict[str, Any]:
zt = _core.get_zt_pool(date_str)
dt = _core.get_dt_pool(date_str)
zb = _core.get_zb_pool(date_str)
return {
"date": date_str,
"indices": _core.get_index(date_str),
"zt_pool": zt,
"dt_pool": dt,
"zb_pool": zb,
"flow": _core.get_fund_flow(date_str),
}
def _zt_payload(date_str: str) -> dict[str, Any]:
return {
"date": date_str,
"zt_pool": _core.get_zt_pool(date_str),
"dt_pool": _core.get_dt_pool(date_str),
"zb_pool": _core.get_zb_pool(date_str),
}
def _us_market_payload(date_str: str) -> dict[str, Any]:
symbols = {"^GSPC": "标普 500", "^IXIC": "纳斯达克"}
return {"date": date_str, "indices": _core.fetch_us_indices_sina(symbols, date_str)}
def _hk_market_payload(date_str: str) -> dict[str, Any]:
symbols = {"^HSI": "恒生指数", "^HSCE": "国企指数", "HSTECH.HK": "恒生科技指数"}
return {"date": date_str, "indices": _core.fetch_hk_indices_tencent(symbols, date_str)}
def _global_market_payload(date_str: str) -> dict[str, Any]:
return {
"date": date_str,
"a": _core.get_index(date_str),
"hk": _hk_market_payload(date_str)["indices"],
"us": _us_market_payload(date_str)["indices"],
}
@cli.command(help="A-share after-hours dashboard: indices, ZT/DT pool, fund flow, boards.")
@_date_opt
@_refresh_opt
@_json_opt
@click.option("--zt", is_flag=True, help="Only show limit-up/down pool data.")
def a(date: str | None, refresh: bool, as_json: bool, zt: bool) -> None:
if refresh:
_core.NO_CACHE = True
date_str = date or _core.nearest_trade_date()
if zt:
payload = _zt_payload(date_str)
if as_json:
_echo_json(payload)
else:
_core.print_zt_analysis(payload["zt_pool"], payload["dt_pool"], payload["zb_pool"])
return
_run("a", date, refresh, as_json=as_json)
@cli.command(help="Hong Kong market after-hours snapshot.")
@_date_opt
@_refresh_opt
@_json_opt
def hk(date: str | None, refresh: bool, as_json: bool) -> None:
_run("hk", date, refresh, as_json=as_json)
@cli.command(help="US market after-hours snapshot.")
@_date_opt
@_refresh_opt
@_json_opt
def us(date: str | None, refresh: bool, as_json: bool) -> None:
_run("us", date, refresh, as_json=as_json)
@cli.command(name="global", help="Global indices snapshot (A + HK + US).")
@_date_opt
@_refresh_opt
@_json_opt
def global_(date: str | None, refresh: bool, as_json: bool) -> None:
_run("global", date, refresh, as_json=as_json)
@cli.command(help="Update young-stock-cli with the current Python environment.")
@click.option("--pre", is_flag=True, help="Allow pre-release versions.")
@click.option("--user", "user_install", is_flag=True, help="Install to the user site-packages directory.")
def update(pre: bool, user_install: bool) -> None:
cmd = [sys.executable, "-m", "pip", "install", "--upgrade", "young-stock-cli"]
if pre:
cmd.append("--pre")
if user_install:
cmd.append("--user")
click.echo("Running: " + " ".join(cmd))
result = subprocess.run(cmd, check=False)
if result.returncode != 0:
raise click.ClickException(f"update failed with exit code {result.returncode}")
@cli.command(help="Show A-share major indices only.")
@_date_opt
@_refresh_opt
@_json_opt
def indices(date: str | None, refresh: bool, as_json: bool) -> None:
if refresh:
_core.NO_CACHE = True
date_str = date or _core.nearest_trade_date()
data = _core.get_index(date_str)
if as_json:
_echo_json({"date": date_str, "indices": data})
return
_core.print_index(data)
@cli.command(name="zt-pool", help="Show A-share limit-up (涨停) pool.")
@_date_opt
@_refresh_opt
@_json_opt
def zt_pool(date: str | None, refresh: bool, as_json: bool) -> None:
if refresh:
_core.NO_CACHE = True
date_str = date or _core.nearest_trade_date()
payload = _zt_payload(date_str)
if as_json:
_echo_json(payload)
return
_core.print_zt_analysis(payload["zt_pool"], payload["dt_pool"], payload["zb_pool"])
@cli.command(help="Show A-share fund flow (north-bound, main capital).")
@_date_opt
@_refresh_opt
@_json_opt
def flow(date: str | None, refresh: bool, as_json: bool) -> None:
if refresh:
_core.NO_CACHE = True
date_str = date or _core.nearest_trade_date()
flow_data = _core.get_fund_flow(date_str)
if as_json:
_echo_json({"date": date_str, "flow": flow_data})
return
_core.print_fund_flow(flow_data)
@cli.command(help="Clear cached responses older than N days.")
@click.option("--days", default=7, show_default=True, help="Delete cache files older than this many days.")
def cache_clear(days: int) -> None:
_core.cache_clear_old(days=days)
click.echo(f"Cleared cache older than {days} days.")
if __name__ == "__main__":
cli()