rifterm 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.
- rifterm/__init__.py +8 -0
- rifterm/cache.py +90 -0
- rifterm/cli.py +212 -0
- rifterm/client.py +87 -0
- rifterm/config.py +41 -0
- rifterm/render.py +193 -0
- rifterm-0.2.0.dist-info/METADATA +112 -0
- rifterm-0.2.0.dist-info/RECORD +11 -0
- rifterm-0.2.0.dist-info/WHEEL +4 -0
- rifterm-0.2.0.dist-info/entry_points.txt +2 -0
- rifterm-0.2.0.dist-info/licenses/LICENSE +21 -0
rifterm/__init__.py
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
"""rifterm — le marché, dans votre terminal.
|
|
2
|
+
|
|
3
|
+
CLI open source (MIT) de rif : Heat Index, pépites et rapports quotidiens,
|
|
4
|
+
directement en ligne de commande. Les données RIF sont servies par
|
|
5
|
+
https://lerif.ca (abonnement PRO+, clé API).
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
__version__ = "0.2.0"
|
rifterm/cache.py
ADDED
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
"""Cache local TTL — économise le quota quotidien (1000 appels par clé).
|
|
2
|
+
|
|
3
|
+
Les réponses sont stockées en JSON dans ``<dossier de config>/cache/`` : une
|
|
4
|
+
entrée par (endpoint + paramètres), TTL court (5 min par défaut). Un échec
|
|
5
|
+
d'écriture ou de lecture est silencieux — le cache est un plus, jamais un
|
|
6
|
+
blocage.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import hashlib
|
|
12
|
+
import json
|
|
13
|
+
import time
|
|
14
|
+
from pathlib import Path
|
|
15
|
+
from typing import Any
|
|
16
|
+
|
|
17
|
+
import httpx
|
|
18
|
+
|
|
19
|
+
from rifterm.client import RifApiError, get
|
|
20
|
+
from rifterm.config import config_path
|
|
21
|
+
|
|
22
|
+
CACHE_TTL_SECONDS = 300
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def cache_dir() -> Path:
|
|
26
|
+
"""Dossier du cache : à côté du fichier de config (``RIFTERM_CONFIG`` respecté)."""
|
|
27
|
+
return config_path().parent / "cache"
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def cache_key(path: str, params: dict[str, object] | None) -> str:
|
|
31
|
+
"""Clé stable pour un (endpoint + paramètres), indépendante de l'ordre."""
|
|
32
|
+
normalise = json.dumps(params or {}, sort_keys=True, separators=(",", ":"))
|
|
33
|
+
return hashlib.sha256(f"{path}?{normalise}".encode()).hexdigest()
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def cache_get(path: str, params: dict[str, object] | None) -> dict[str, Any] | None:
|
|
37
|
+
"""Payload en cache si le TTL est valide, sinon ``None`` (entrée expirée supprimée)."""
|
|
38
|
+
fichier = cache_dir() / f"{cache_key(path, params)}.json"
|
|
39
|
+
try:
|
|
40
|
+
entree = json.loads(fichier.read_text(encoding="utf-8"))
|
|
41
|
+
except (OSError, ValueError):
|
|
42
|
+
return None
|
|
43
|
+
if not isinstance(entree, dict) or time.time() >= float(entree.get("expires", 0)):
|
|
44
|
+
try:
|
|
45
|
+
fichier.unlink(missing_ok=True)
|
|
46
|
+
except OSError:
|
|
47
|
+
pass
|
|
48
|
+
return None
|
|
49
|
+
payload = entree.get("payload")
|
|
50
|
+
return payload if isinstance(payload, dict) else None
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def cache_put(path: str, params: dict[str, object] | None, payload: dict[str, Any]) -> None:
|
|
54
|
+
"""Écrit le payload dans le cache avec un TTL ; échec silencieux."""
|
|
55
|
+
dossier = cache_dir()
|
|
56
|
+
fichier = dossier / f"{cache_key(path, params)}.json"
|
|
57
|
+
entree = {"expires": time.time() + CACHE_TTL_SECONDS, "payload": payload}
|
|
58
|
+
try:
|
|
59
|
+
dossier.mkdir(parents=True, exist_ok=True)
|
|
60
|
+
fichier.write_text(json.dumps(entree, ensure_ascii=False), encoding="utf-8")
|
|
61
|
+
except OSError:
|
|
62
|
+
pass
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def fetch(
|
|
66
|
+
path: str,
|
|
67
|
+
*,
|
|
68
|
+
api_key: str | None = None,
|
|
69
|
+
params: dict[str, object] | None = None,
|
|
70
|
+
use_cache: bool = True,
|
|
71
|
+
transport: httpx.BaseTransport | None = None,
|
|
72
|
+
) -> tuple[dict[str, Any], httpx.Response | None]:
|
|
73
|
+
"""``GET`` avec cache TTL : ``(payload, réponse)`` — ``réponse`` est ``None`` en cache hit.
|
|
74
|
+
|
|
75
|
+
Lève :py:class:`RifApiError` sur erreur API (401/403/429/5xx, réseau)
|
|
76
|
+
ou corps JSON illisible.
|
|
77
|
+
"""
|
|
78
|
+
if use_cache:
|
|
79
|
+
cached = cache_get(path, params)
|
|
80
|
+
if cached is not None:
|
|
81
|
+
return cached, None
|
|
82
|
+
resp = get(path, api_key=api_key, params=params, transport=transport)
|
|
83
|
+
try:
|
|
84
|
+
payload = resp.json()
|
|
85
|
+
except ValueError as exc:
|
|
86
|
+
raise RifApiError("Réponse inattendue de l'API RIF (JSON invalide).") from exc
|
|
87
|
+
if not isinstance(payload, dict):
|
|
88
|
+
raise RifApiError("Réponse inattendue de l'API RIF (payload inattendu).")
|
|
89
|
+
cache_put(path, params, payload)
|
|
90
|
+
return payload, resp
|
rifterm/cli.py
ADDED
|
@@ -0,0 +1,212 @@
|
|
|
1
|
+
"""CLI rifterm — le marché, dans votre terminal."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
|
|
8
|
+
import typer
|
|
9
|
+
from rich.console import Console
|
|
10
|
+
|
|
11
|
+
from rifterm import __version__
|
|
12
|
+
from rifterm.cache import fetch
|
|
13
|
+
from rifterm.client import RifApiError, get
|
|
14
|
+
from rifterm.config import config_path, load_api_key, save_api_key
|
|
15
|
+
from rifterm.render import render_heat, render_pepites, report_markdown
|
|
16
|
+
|
|
17
|
+
app = typer.Typer(help="rifterm — le marché, dans votre terminal.", no_args_is_help=True)
|
|
18
|
+
console = Console()
|
|
19
|
+
err_console = Console(stderr=True)
|
|
20
|
+
|
|
21
|
+
_JSON_HELP = "Sortie JSON brute (sans styles ni emoji) — pour scripts et pipes."
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def _print_version(value: bool) -> None:
|
|
25
|
+
if value:
|
|
26
|
+
console.print(f"rifterm {__version__} (open source · MIT)")
|
|
27
|
+
raise typer.Exit()
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def _json_mode(ctx: typer.Context, local: bool) -> bool:
|
|
31
|
+
"""Mode JSON : ``--json`` avant (global) ou après la commande."""
|
|
32
|
+
return local or bool((ctx.obj or {}).get("json"))
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def _load_key_or_exit() -> str:
|
|
36
|
+
"""Clé API locale, ou message guidé ``rifterm login`` (sans consommer le quota)."""
|
|
37
|
+
api_key = load_api_key()
|
|
38
|
+
if not api_key:
|
|
39
|
+
err_console.print("[red]Pas de clé sauvegardée — [bold]rifterm login <clé>[/bold][/red]")
|
|
40
|
+
raise typer.Exit(code=1)
|
|
41
|
+
return api_key
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def _fetch_or_exit(path: str, api_key: str, params: dict[str, object], use_cache: bool) -> dict:
|
|
45
|
+
"""Appel API via le cache TTL ; lève une sortie 1 avec le message d'erreur FR."""
|
|
46
|
+
try:
|
|
47
|
+
payload, _resp = fetch(path, api_key=api_key, params=params, use_cache=use_cache)
|
|
48
|
+
except RifApiError as exc:
|
|
49
|
+
err_console.print(f"[red]{exc}[/red]")
|
|
50
|
+
raise typer.Exit(code=1) from exc
|
|
51
|
+
return payload
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def write_text_or_exit(path: str, content: str) -> None:
|
|
55
|
+
"""Export fichier avec une erreur lisible si le chemin est indisponible."""
|
|
56
|
+
try:
|
|
57
|
+
Path(path).write_text(content, encoding="utf-8", newline="\n")
|
|
58
|
+
except OSError as exc:
|
|
59
|
+
err_console.print(f"[red]Écriture impossible dans {path} — {exc}[/red]")
|
|
60
|
+
raise typer.Exit(code=1) from exc
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
@app.callback()
|
|
64
|
+
def main(
|
|
65
|
+
ctx: typer.Context,
|
|
66
|
+
version: bool = typer.Option(
|
|
67
|
+
False,
|
|
68
|
+
"--version",
|
|
69
|
+
callback=_print_version,
|
|
70
|
+
is_eager=True,
|
|
71
|
+
help="Affiche la version et quitte.",
|
|
72
|
+
),
|
|
73
|
+
json_output: bool = typer.Option(False, "--json", help=_JSON_HELP),
|
|
74
|
+
) -> None:
|
|
75
|
+
"""rifterm — CLI open source de rif. Données RIF sur lerif.ca (clé PRO+)."""
|
|
76
|
+
ctx.obj = {"json": json_output}
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
@app.command()
|
|
80
|
+
def login(
|
|
81
|
+
api_key: str = typer.Argument(..., help="Ta clé API RIF (format rif_…)."),
|
|
82
|
+
) -> None:
|
|
83
|
+
"""Sauvegarde ta clé API RIF localement (permissions 600)."""
|
|
84
|
+
if not api_key.startswith("rif_"):
|
|
85
|
+
err_console.print("[red]Clé invalide — format attendu : rif_…[/red]")
|
|
86
|
+
raise typer.Exit(code=1)
|
|
87
|
+
path = save_api_key(api_key)
|
|
88
|
+
console.print(f"[green]✓[/green] Clé sauvegardée dans {path} (permissions 600).")
|
|
89
|
+
console.print(f"Teste-la avec [bold]rifterm status[/bold] — config : {config_path()}")
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
@app.command()
|
|
93
|
+
def status() -> None:
|
|
94
|
+
"""Vérifie ta clé contre l'API et affiche ton quota quotidien."""
|
|
95
|
+
api_key = load_api_key()
|
|
96
|
+
if not api_key:
|
|
97
|
+
err_console.print("[red]Pas de clé sauvegardée — [bold]rifterm login <clé>[/bold][/red]")
|
|
98
|
+
raise typer.Exit(code=1)
|
|
99
|
+
try:
|
|
100
|
+
resp = get("/cli/heat", api_key=api_key, params={"days": 1, "limit": 1})
|
|
101
|
+
except RifApiError as exc:
|
|
102
|
+
err_console.print(f"[red]{exc}[/red]")
|
|
103
|
+
raise typer.Exit(code=1) from exc
|
|
104
|
+
remaining = resp.headers.get("X-RateLimit-Remaining", "?")
|
|
105
|
+
console.print("[green]✓[/green] Clé valide — API RIF joignable.")
|
|
106
|
+
console.print(f" Quota : [bold]{remaining}[/bold] appels restants aujourd'hui.")
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
@app.command()
|
|
110
|
+
def heat(
|
|
111
|
+
ctx: typer.Context,
|
|
112
|
+
days: int = typer.Option(
|
|
113
|
+
1, "--days", min=1, max=30, help="Fenêtre en jours (défaut 1, max 30)."
|
|
114
|
+
),
|
|
115
|
+
no_cache: bool = typer.Option(
|
|
116
|
+
False, "--no-cache", help="Force l'appel API (ignore le cache local de 5 min)."
|
|
117
|
+
),
|
|
118
|
+
json_local: bool = typer.Option(False, "--json", help=_JSON_HELP),
|
|
119
|
+
) -> None:
|
|
120
|
+
"""Heat Index quotidien — score global + tickers les plus chauds."""
|
|
121
|
+
api_key = _load_key_or_exit()
|
|
122
|
+
payload = _fetch_or_exit("/cli/heat", api_key, params={"days": days}, use_cache=not no_cache)
|
|
123
|
+
render_heat(console, payload, json_mode=_json_mode(ctx, json_local))
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
@app.command()
|
|
127
|
+
def pepites(
|
|
128
|
+
ctx: typer.Context,
|
|
129
|
+
days: int = typer.Option(
|
|
130
|
+
1, "--days", min=1, max=30, help="Fenêtre en jours (défaut 1, max 30)."
|
|
131
|
+
),
|
|
132
|
+
no_cache: bool = typer.Option(
|
|
133
|
+
False, "--no-cache", help="Force l'appel API (ignore le cache local de 5 min)."
|
|
134
|
+
),
|
|
135
|
+
json_local: bool = typer.Option(False, "--json", help=_JSON_HELP),
|
|
136
|
+
) -> None:
|
|
137
|
+
"""Pépites récentes — ticker, score, heat et signaux."""
|
|
138
|
+
api_key = _load_key_or_exit()
|
|
139
|
+
payload = _fetch_or_exit("/cli/pepites", api_key, params={"days": days}, use_cache=not no_cache)
|
|
140
|
+
render_pepites(console, payload, json_mode=_json_mode(ctx, json_local))
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
@app.command()
|
|
144
|
+
def report(
|
|
145
|
+
ctx: typer.Context,
|
|
146
|
+
days: int = typer.Option(
|
|
147
|
+
1, "--days", min=1, max=30, help="Fenêtre en jours (défaut 1, max 30)."
|
|
148
|
+
),
|
|
149
|
+
no_cache: bool = typer.Option(
|
|
150
|
+
False, "--no-cache", help="Force l'appel API (ignore le cache local de 5 min)."
|
|
151
|
+
),
|
|
152
|
+
out: str | None = typer.Option(
|
|
153
|
+
None, "--out", help="Fichier d'export (.md ou .json) au lieu de la sortie terminal."
|
|
154
|
+
),
|
|
155
|
+
json_local: bool = typer.Option(False, "--json", help=_JSON_HELP),
|
|
156
|
+
) -> None:
|
|
157
|
+
"""Agrégat heat + pépites, export Markdown/JSON.
|
|
158
|
+
|
|
159
|
+
Côté CLI seulement : l'endpoint serveur ``/cli/report`` n'est pas encore
|
|
160
|
+
branché, donc les données viennent des endpoints ``heat`` et ``pepites``.
|
|
161
|
+
"""
|
|
162
|
+
suffix = ""
|
|
163
|
+
if out is not None:
|
|
164
|
+
suffix = out.rsplit(".", 1)[-1].lower() if "." in out else ""
|
|
165
|
+
if suffix not in {"json", "md"} or not Path(out).parent.is_dir():
|
|
166
|
+
err_console.print(
|
|
167
|
+
"[red]--out attend un dossier existant et le format .md ou .json.[/red]"
|
|
168
|
+
)
|
|
169
|
+
raise typer.Exit(code=1)
|
|
170
|
+
|
|
171
|
+
api_key = _load_key_or_exit()
|
|
172
|
+
heat_payload = _fetch_or_exit(
|
|
173
|
+
"/cli/heat",
|
|
174
|
+
api_key,
|
|
175
|
+
params={"days": days},
|
|
176
|
+
use_cache=not no_cache,
|
|
177
|
+
)
|
|
178
|
+
pepites_payload = _fetch_or_exit(
|
|
179
|
+
"/cli/pepites",
|
|
180
|
+
api_key,
|
|
181
|
+
params={"days": days},
|
|
182
|
+
use_cache=not no_cache,
|
|
183
|
+
)
|
|
184
|
+
payload = {
|
|
185
|
+
"report_version": 1,
|
|
186
|
+
"days": days,
|
|
187
|
+
"heat": heat_payload,
|
|
188
|
+
"pepites": pepites_payload,
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
if out is None:
|
|
192
|
+
if _json_mode(ctx, json_local):
|
|
193
|
+
print(json.dumps(payload, ensure_ascii=False))
|
|
194
|
+
else:
|
|
195
|
+
console.rule("Rapport rifterm")
|
|
196
|
+
console.print("[dim]Endpoint serveur /cli/report non branché — agrégat local.[/dim]")
|
|
197
|
+
render_heat(console, heat_payload, json_mode=False)
|
|
198
|
+
console.print()
|
|
199
|
+
render_pepites(console, pepites_payload, json_mode=False)
|
|
200
|
+
return
|
|
201
|
+
|
|
202
|
+
content = (
|
|
203
|
+
json.dumps(payload, ensure_ascii=False) + "\n"
|
|
204
|
+
if suffix == "json"
|
|
205
|
+
else report_markdown(payload)
|
|
206
|
+
)
|
|
207
|
+
write_text_or_exit(out, content)
|
|
208
|
+
console.print(f"[green]✓[/green] Rapport écrit dans [bold]{out}[/bold].")
|
|
209
|
+
|
|
210
|
+
|
|
211
|
+
if __name__ == "__main__":
|
|
212
|
+
app()
|
rifterm/client.py
ADDED
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
"""Client HTTP vers l'API RIF — header ``X-API-Key`` et erreurs lisibles."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import os
|
|
6
|
+
from datetime import UTC, datetime
|
|
7
|
+
|
|
8
|
+
import httpx
|
|
9
|
+
|
|
10
|
+
from rifterm import __version__
|
|
11
|
+
|
|
12
|
+
DEFAULT_BASE_URL = "https://lerif.ca"
|
|
13
|
+
API_PREFIX = "/api/v1"
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
class RifApiError(Exception):
|
|
17
|
+
"""Erreur d'appel API, avec un message prêt à afficher en français."""
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def base_url() -> str:
|
|
21
|
+
"""URL de base de l'API (override via ``RIFTERM_API_URL``, utile en dev)."""
|
|
22
|
+
return os.environ.get("RIFTERM_API_URL", DEFAULT_BASE_URL).rstrip("/")
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def rate_reset_local(headers: httpx.Headers) -> str | None:
|
|
26
|
+
"""Heure locale (``HH:MM``) de réinitialisation du quota.
|
|
27
|
+
|
|
28
|
+
Calculée depuis ``X-RateLimit-Reset`` — l'epoch de minuit UTC côté
|
|
29
|
+
serveur. ``None`` si l'en-tête est absent ou illisible.
|
|
30
|
+
"""
|
|
31
|
+
raw = headers.get("X-RateLimit-Reset")
|
|
32
|
+
if not raw:
|
|
33
|
+
return None
|
|
34
|
+
try:
|
|
35
|
+
epoch = int(raw)
|
|
36
|
+
except (TypeError, ValueError):
|
|
37
|
+
return None
|
|
38
|
+
reset = datetime.fromtimestamp(epoch, tz=UTC).astimezone()
|
|
39
|
+
return reset.strftime("%H:%M")
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def get(
|
|
43
|
+
path: str,
|
|
44
|
+
*,
|
|
45
|
+
api_key: str | None = None,
|
|
46
|
+
params: dict[str, object] | None = None,
|
|
47
|
+
transport: httpx.BaseTransport | None = None,
|
|
48
|
+
) -> httpx.Response:
|
|
49
|
+
"""``GET {base}/api/v1{path}`` avec ``X-API-Key`` si fournie.
|
|
50
|
+
|
|
51
|
+
Lève :py:class:`RifApiError` (message en français) sur 401/403/429/5xx
|
|
52
|
+
ou erreur réseau. Retourne la réponse brute — le quota restant est dans
|
|
53
|
+
les en-têtes ``X-RateLimit-*``.
|
|
54
|
+
"""
|
|
55
|
+
headers = {"User-Agent": f"rifterm/{__version__}"}
|
|
56
|
+
if api_key:
|
|
57
|
+
headers["X-API-Key"] = api_key
|
|
58
|
+
url = f"{base_url()}{API_PREFIX}{path}"
|
|
59
|
+
try:
|
|
60
|
+
with httpx.Client(timeout=15, transport=transport, headers=headers) as client:
|
|
61
|
+
resp = client.get(url, params=params)
|
|
62
|
+
except httpx.HTTPError as exc:
|
|
63
|
+
raise RifApiError(f"Impossible de joindre l'API RIF ({exc}).") from exc
|
|
64
|
+
|
|
65
|
+
if resp.status_code == 401:
|
|
66
|
+
raise RifApiError(
|
|
67
|
+
"Clé API invalide ou révoquée — rifterm login <clé> pour enregistrer une nouvelle clé."
|
|
68
|
+
)
|
|
69
|
+
if resp.status_code == 403:
|
|
70
|
+
raise RifApiError(
|
|
71
|
+
"L'accès API nécessite un abonnement PRO+ — abonne-toi sur lerif.ca/rifterm."
|
|
72
|
+
)
|
|
73
|
+
if resp.status_code == 429:
|
|
74
|
+
reset = rate_reset_local(resp.headers)
|
|
75
|
+
if reset:
|
|
76
|
+
raise RifApiError(
|
|
77
|
+
"Quota quotidien atteint (1000 appels/jour) — "
|
|
78
|
+
f"réinitialisation à {reset} heure locale (minuit UTC)."
|
|
79
|
+
)
|
|
80
|
+
raise RifApiError(
|
|
81
|
+
"Quota quotidien atteint (1000 appels/jour) — réinitialisation à minuit UTC."
|
|
82
|
+
)
|
|
83
|
+
if resp.status_code >= 500:
|
|
84
|
+
raise RifApiError(f"L'API RIF a un souci (HTTP {resp.status_code}) — réessaie plus tard.")
|
|
85
|
+
if resp.status_code != 200:
|
|
86
|
+
raise RifApiError(f"Appel API échoué (HTTP {resp.status_code}).")
|
|
87
|
+
return resp
|
rifterm/config.py
ADDED
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
"""Configuration locale de rifterm — stockage de la clé API.
|
|
2
|
+
|
|
3
|
+
La clé est écrite dans un TOML minimal sous ``~/.config/rifterm/config.toml``
|
|
4
|
+
(ou ``$RIFTERM_CONFIG``), avec permissions 0600 : une clé API est un secret.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import os
|
|
10
|
+
import tomllib
|
|
11
|
+
from pathlib import Path
|
|
12
|
+
|
|
13
|
+
DEFAULT_CONFIG_DIR = Path.home() / ".config" / "rifterm"
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def config_path() -> Path:
|
|
17
|
+
"""Chemin du fichier de config (override via ``RIFTERM_CONFIG``)."""
|
|
18
|
+
env = os.environ.get("RIFTERM_CONFIG")
|
|
19
|
+
return Path(env) if env else DEFAULT_CONFIG_DIR / "config.toml"
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def save_api_key(raw_key: str) -> Path:
|
|
23
|
+
"""Écrit la clé dans la config avec permissions 0600. Retourne le chemin."""
|
|
24
|
+
path = config_path()
|
|
25
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
26
|
+
path.write_text(f'api_key = "{raw_key}"\n', encoding="utf-8")
|
|
27
|
+
path.chmod(0o600)
|
|
28
|
+
return path
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def load_api_key() -> str | None:
|
|
32
|
+
"""Lit la clé sauvegardée, ou ``None`` si absente/illisible."""
|
|
33
|
+
path = config_path()
|
|
34
|
+
if not path.is_file():
|
|
35
|
+
return None
|
|
36
|
+
try:
|
|
37
|
+
data = tomllib.loads(path.read_text(encoding="utf-8"))
|
|
38
|
+
except (tomllib.TOMLDecodeError, OSError):
|
|
39
|
+
return None
|
|
40
|
+
key = data.get("api_key")
|
|
41
|
+
return key if isinstance(key, str) and key else None
|
rifterm/render.py
ADDED
|
@@ -0,0 +1,193 @@
|
|
|
1
|
+
"""Rendu des données RIF — tableau rich en terminal, JSON brut en pipe.
|
|
2
|
+
|
|
3
|
+
Deux sorties par commande :
|
|
4
|
+
- ``--json`` : le payload de l'API, tel quel, sans ANSI ni emoji ;
|
|
5
|
+
- sinon : rendu rich — les styles sont désactivés automatiquement quand
|
|
6
|
+
stdout n'est pas un TTY (rich détecte), les tableaux restent lisibles.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import json
|
|
12
|
+
from statistics import fmean
|
|
13
|
+
from typing import Any
|
|
14
|
+
|
|
15
|
+
from rich.console import Console
|
|
16
|
+
from rich.table import Table
|
|
17
|
+
|
|
18
|
+
# Valeurs de heat_level observées côté API (normalisées en minuscules).
|
|
19
|
+
_LEVEL_STYLES = {"tres hot": "bold red", "hot": "red", "warm": "yellow"}
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def _dump_json(payload: dict[str, Any]) -> None:
|
|
23
|
+
"""JSON compact sur stdout brut — jq/pipes, aucun style."""
|
|
24
|
+
print(json.dumps(payload, ensure_ascii=False))
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def _rows(payload: dict[str, Any], score_key: str) -> list[dict[str, Any]]:
|
|
28
|
+
"""Lignes ``data`` triées par score décroissant (sans compter sur le tri serveur)."""
|
|
29
|
+
rows = [row for row in payload.get("data", []) if isinstance(row, dict)]
|
|
30
|
+
return sorted(rows, key=lambda row: float(row.get(score_key) or 0), reverse=True)
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def _signals(row: dict[str, Any]) -> str:
|
|
34
|
+
"""Signaux lisibles : jusqu'à 3, suffixe ``(+N)`` au-delà."""
|
|
35
|
+
signaux = [str(signal) for signal in (row.get("signals") or [])]
|
|
36
|
+
if not signaux:
|
|
37
|
+
count = row.get("signal_count")
|
|
38
|
+
return f"{count} signal" if isinstance(count, int) and count else "-"
|
|
39
|
+
affiches = ", ".join(signaux[:3])
|
|
40
|
+
if len(signaux) > 3:
|
|
41
|
+
affiches += f" (+{len(signaux) - 3})"
|
|
42
|
+
return affiches
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def global_heat(payload: dict[str, Any]) -> float | None:
|
|
46
|
+
"""Score global : moyenne du ``heat_index`` du dernier jour (calculée côté client)."""
|
|
47
|
+
rows = _rows(payload, "heat_index")
|
|
48
|
+
if not rows:
|
|
49
|
+
return None
|
|
50
|
+
dernier_jour = max(str(row.get("date", "")) for row in rows)
|
|
51
|
+
lignes_du_jour = [row for row in rows if str(row.get("date")) == dernier_jour]
|
|
52
|
+
return round(fmean(float(row.get("heat_index") or 0) for row in lignes_du_jour), 1)
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def render_heat(console: Console, payload: dict[str, Any], *, json_mode: bool) -> None:
|
|
56
|
+
"""Heat Index : score global + tableau des tickers, ou payload JSON."""
|
|
57
|
+
if json_mode:
|
|
58
|
+
_dump_json(payload)
|
|
59
|
+
return
|
|
60
|
+
rows = _rows(payload, "heat_index")
|
|
61
|
+
if not rows:
|
|
62
|
+
console.print("Aucune donnée heat disponible pour cette période.")
|
|
63
|
+
return
|
|
64
|
+
dernier_jour = max(str(row.get("date", "")) for row in rows)
|
|
65
|
+
score = global_heat(payload)
|
|
66
|
+
count = payload.get("count", len(rows))
|
|
67
|
+
console.print(
|
|
68
|
+
f"[bold]Heat Index[/bold] — {dernier_jour} · "
|
|
69
|
+
f"score global [bold]{score}[/bold] · {count} lignes"
|
|
70
|
+
)
|
|
71
|
+
console.print("[dim]Score global = moyenne du heat_index du dernier jour.[/dim]")
|
|
72
|
+
table = Table()
|
|
73
|
+
table.add_column("Ticker", style="bold")
|
|
74
|
+
table.add_column("Date")
|
|
75
|
+
table.add_column("Heat", justify="right")
|
|
76
|
+
table.add_column("Niveau")
|
|
77
|
+
table.add_column("Type")
|
|
78
|
+
table.add_column("Conviction", justify="right")
|
|
79
|
+
table.add_column("Signaux")
|
|
80
|
+
for row in rows:
|
|
81
|
+
heat = row.get("heat_index")
|
|
82
|
+
conviction = row.get("conviction_score")
|
|
83
|
+
niveau = str(row.get("heat_level") or "-")
|
|
84
|
+
table.add_row(
|
|
85
|
+
str(row.get("ticker") or "?"),
|
|
86
|
+
str(row.get("date") or "-"),
|
|
87
|
+
f"{float(heat):.1f}" if heat is not None else "-",
|
|
88
|
+
niveau,
|
|
89
|
+
str(row.get("market_type") or "-"),
|
|
90
|
+
f"{float(conviction):.1f}" if conviction is not None else "-",
|
|
91
|
+
_signals(row),
|
|
92
|
+
style=_LEVEL_STYLES.get(niveau.lower(), ""),
|
|
93
|
+
)
|
|
94
|
+
console.print(table)
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
def render_pepites(console: Console, payload: dict[str, Any], *, json_mode: bool) -> None:
|
|
98
|
+
"""Pépites : ticker / score / heat / signaux, ou payload JSON."""
|
|
99
|
+
if json_mode:
|
|
100
|
+
_dump_json(payload)
|
|
101
|
+
return
|
|
102
|
+
rows = _rows(payload, "pepite_score")
|
|
103
|
+
if not rows:
|
|
104
|
+
console.print("Aucune pépite détectée sur la période.")
|
|
105
|
+
return
|
|
106
|
+
count = payload.get("count", len(rows))
|
|
107
|
+
console.print(f"[bold]Pépites[/bold] — {count} lignes sur la période")
|
|
108
|
+
table = Table()
|
|
109
|
+
table.add_column("Ticker", style="bold")
|
|
110
|
+
table.add_column("Score", justify="right")
|
|
111
|
+
table.add_column("Heat", justify="right")
|
|
112
|
+
table.add_column("Signaux")
|
|
113
|
+
table.add_column("Date")
|
|
114
|
+
for row in rows:
|
|
115
|
+
score = row.get("pepite_score")
|
|
116
|
+
heat = row.get("heat_index")
|
|
117
|
+
table.add_row(
|
|
118
|
+
str(row.get("ticker") or "?"),
|
|
119
|
+
f"{float(score):.1f}" if score is not None else "-",
|
|
120
|
+
f"{float(heat):.1f}" if heat is not None else "-",
|
|
121
|
+
_signals(row),
|
|
122
|
+
str(row.get("date") or "-"),
|
|
123
|
+
)
|
|
124
|
+
console.print(table)
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
def report_markdown(payload: dict[str, Any]) -> str:
|
|
128
|
+
"""Rapport Markdown : agrégat heat + pépites, sans styles ni ANSI.
|
|
129
|
+
|
|
130
|
+
Côté CLI pour l'instant : l'endpoint serveur ``/cli/report`` n'est pas
|
|
131
|
+
encore branché, donc ``heat`` et ``pepites`` restent les sources.
|
|
132
|
+
"""
|
|
133
|
+
lines = ["# Rapport rifterm", "", f"Période : {payload.get('days', 1)} jour(s)", ""]
|
|
134
|
+
|
|
135
|
+
lines += ["## Heat Index", ""]
|
|
136
|
+
heat = payload.get("heat")
|
|
137
|
+
score = global_heat(heat if isinstance(heat, dict) else {})
|
|
138
|
+
lines.append(f"Score global : {score if score is not None else '-'}")
|
|
139
|
+
heat_rows = _rows(heat if isinstance(heat, dict) else {}, "heat_index")
|
|
140
|
+
if not heat_rows:
|
|
141
|
+
lines += ["", "Aucune donnée heat disponible."]
|
|
142
|
+
else:
|
|
143
|
+
headers = ["Ticker", "Date", "Heat", "Niveau", "Type", "Conviction", "Signaux"]
|
|
144
|
+
table_rows = []
|
|
145
|
+
for row in heat_rows:
|
|
146
|
+
heat_value = row.get("heat_index")
|
|
147
|
+
conviction = row.get("conviction_score")
|
|
148
|
+
table_rows.append(
|
|
149
|
+
[
|
|
150
|
+
str(row.get("ticker") or "?"),
|
|
151
|
+
str(row.get("date") or "-"),
|
|
152
|
+
f"{float(heat_value):.1f}" if heat_value is not None else "-",
|
|
153
|
+
str(row.get("heat_level") or "-"),
|
|
154
|
+
str(row.get("market_type") or "-"),
|
|
155
|
+
f"{float(conviction):.1f}" if conviction is not None else "-",
|
|
156
|
+
_signals(row),
|
|
157
|
+
]
|
|
158
|
+
)
|
|
159
|
+
lines += ["", _markdown_table(headers, table_rows)]
|
|
160
|
+
|
|
161
|
+
lines += ["", "## Pépites", ""]
|
|
162
|
+
pepites = payload.get("pepites")
|
|
163
|
+
pepites_rows = _rows(pepites if isinstance(pepites, dict) else {}, "pepite_score")
|
|
164
|
+
if not pepites_rows:
|
|
165
|
+
lines.append("Aucune pépite détectée sur la période.")
|
|
166
|
+
else:
|
|
167
|
+
headers = ["Ticker", "Score", "Heat", "Signaux", "Date"]
|
|
168
|
+
table_rows = []
|
|
169
|
+
for row in pepites_rows:
|
|
170
|
+
pepite_score = row.get("pepite_score")
|
|
171
|
+
heat_value = row.get("heat_index")
|
|
172
|
+
table_rows.append(
|
|
173
|
+
[
|
|
174
|
+
str(row.get("ticker") or "?"),
|
|
175
|
+
f"{float(pepite_score):.1f}" if pepite_score is not None else "-",
|
|
176
|
+
f"{float(heat_value):.1f}" if heat_value is not None else "-",
|
|
177
|
+
_signals(row),
|
|
178
|
+
str(row.get("date") or "-"),
|
|
179
|
+
]
|
|
180
|
+
)
|
|
181
|
+
lines += ["", _markdown_table(headers, table_rows)]
|
|
182
|
+
|
|
183
|
+
return "\n".join(lines) + "\n"
|
|
184
|
+
|
|
185
|
+
|
|
186
|
+
def _markdown_table(headers: list[str], rows: list[list[str]]) -> str:
|
|
187
|
+
"""Table Markdown compacte ; ``|`` et retours à la ligne restent inoffensifs."""
|
|
188
|
+
escape = lambda value: str(value).replace("|", "\\|").replace("\n", " ")
|
|
189
|
+
result = ["| " + " | ".join(map(escape, headers)) + " |"]
|
|
190
|
+
result.append("| " + " | ".join(["---"] * len(headers)) + " |")
|
|
191
|
+
for row in rows:
|
|
192
|
+
result.append("| " + " | ".join(map(escape, row)) + " |")
|
|
193
|
+
return "\n".join(result)
|
|
@@ -0,0 +1,112 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: rifterm
|
|
3
|
+
Version: 0.2.0
|
|
4
|
+
Summary: rifterm — le marché, dans votre terminal. CLI open source de rif (Heat Index, pépites, rapports).
|
|
5
|
+
Project-URL: Homepage, https://lerif.ca/rifterm
|
|
6
|
+
Project-URL: Repository, https://github.com/soloofboom/rifterm
|
|
7
|
+
Project-URL: Changelog, https://github.com/soloofboom/rifterm/blob/main/CHANGELOG.md
|
|
8
|
+
Author: soloofboom
|
|
9
|
+
License-Expression: MIT
|
|
10
|
+
License-File: LICENSE
|
|
11
|
+
Keywords: cli,finance,market,rif
|
|
12
|
+
Classifier: Development Status :: 4 - Beta
|
|
13
|
+
Classifier: Environment :: Console
|
|
14
|
+
Classifier: Intended Audience :: Financial and Insurance Industry
|
|
15
|
+
Classifier: Operating System :: OS Independent
|
|
16
|
+
Classifier: Programming Language :: Python :: 3
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
18
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
19
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
20
|
+
Classifier: Topic :: Office/Business :: Financial :: Investment
|
|
21
|
+
Requires-Python: >=3.11
|
|
22
|
+
Requires-Dist: httpx>=0.27
|
|
23
|
+
Requires-Dist: rich>=13.7
|
|
24
|
+
Requires-Dist: typer>=0.12
|
|
25
|
+
Provides-Extra: dev
|
|
26
|
+
Requires-Dist: pytest>=8.0; extra == 'dev'
|
|
27
|
+
Requires-Dist: ruff>=0.5; extra == 'dev'
|
|
28
|
+
Description-Content-Type: text/markdown
|
|
29
|
+
|
|
30
|
+
# rifterm
|
|
31
|
+
|
|
32
|
+
> Le marché, dans votre terminal.
|
|
33
|
+
|
|
34
|
+
CLI open source (MIT) de [rif](https://lerif.ca) — Heat Index, pépites et
|
|
35
|
+
données de marché en ligne de commande. Le CLI est gratuit, les données sont
|
|
36
|
+
payantes.
|
|
37
|
+
|
|
38
|
+
**Statut : v0.2.** Disponible sur PyPI :
|
|
39
|
+
|
|
40
|
+
```bash
|
|
41
|
+
pipx install rifterm
|
|
42
|
+
```
|
|
43
|
+
|
|
44
|
+
## Utilisation
|
|
45
|
+
|
|
46
|
+
```text
|
|
47
|
+
rifterm login <clé> Sauvegarde ta clé API RIF (format rif_…)
|
|
48
|
+
rifterm heat Heat Index quotidien — score global + tickers
|
|
49
|
+
rifterm pepites Pépites récentes — ticker, score, heat, signaux
|
|
50
|
+
rifterm report Agrégat heat + pépites — lecture ou export
|
|
51
|
+
rifterm status État de ta clé + quota quotidien
|
|
52
|
+
```
|
|
53
|
+
|
|
54
|
+
Options utiles (sur `heat`, `pepites` et `report`) :
|
|
55
|
+
|
|
56
|
+
- `--days N` — fenêtre en jours (1–30, défaut 1)
|
|
57
|
+
- `--no-cache` — force l'appel API en ignorant le cache local (TTL 5 min)
|
|
58
|
+
- `--json` — sortie JSON brute, sans styles ni emoji (global ou par commande)
|
|
59
|
+
- `--out report.md` / `--out report.json` — export fichier pour `report`
|
|
60
|
+
|
|
61
|
+
Exemples :
|
|
62
|
+
|
|
63
|
+
```bash
|
|
64
|
+
rifterm heat # tableau riche dans le terminal
|
|
65
|
+
rifterm heat --json | jq '.data[0]'
|
|
66
|
+
rifterm pepites --days 3 --json
|
|
67
|
+
rifterm report --days 2 --out report.md
|
|
68
|
+
```
|
|
69
|
+
|
|
70
|
+
> `report` n'appelle pas encore un endpoint serveur `/cli/report` : celui-ci
|
|
71
|
+
> n'est pas branché. La commande agrège pour l'instant côté CLI
|
|
72
|
+
> `/cli/heat` + `/cli/pepites`; ça devra évoluer quand l'endpoint existera.
|
|
73
|
+
|
|
74
|
+
Les données nécessitent une clé API (abonnement PRO+ sur
|
|
75
|
+
[lerif.ca/rifterm](https://lerif.ca/rifterm)). Le CLI lui-même est gratuit et
|
|
76
|
+
open source.
|
|
77
|
+
|
|
78
|
+
Le cache local (5 min, par endpoint + paramètres, dans le dossier de config)
|
|
79
|
+
économise ton quota quotidien de 1000 appels ; `--no-cache` pour forcer.
|
|
80
|
+
|
|
81
|
+
## Développement
|
|
82
|
+
|
|
83
|
+
```bash
|
|
84
|
+
git clone https://github.com/soloofboom/rifterm
|
|
85
|
+
cd rifterm
|
|
86
|
+
pip install -e ".[dev]"
|
|
87
|
+
pytest
|
|
88
|
+
ruff check .
|
|
89
|
+
ruff format --check .
|
|
90
|
+
```
|
|
91
|
+
|
|
92
|
+
Architecture :
|
|
93
|
+
|
|
94
|
+
- `src/rifterm/cli.py` — commandes Typer
|
|
95
|
+
- `src/rifterm/client.py` — client HTTP (`X-API-Key`, erreurs FR, quotas)
|
|
96
|
+
- `src/rifterm/cache.py` — cache TTL local (5 min, quota 1000/jour)
|
|
97
|
+
- `src/rifterm/render.py` — rendu rich vs JSON
|
|
98
|
+
- `src/rifterm/config.py` — clé API locale (`~/.config/rifterm/config.toml`, 0600)
|
|
99
|
+
|
|
100
|
+
Variables d'environnement :
|
|
101
|
+
|
|
102
|
+
- `RIFTERM_API_URL` — URL de base de l'API (défaut : `https://lerif.ca`)
|
|
103
|
+
- `RIFTERM_CONFIG` — chemin de la config (défaut : `~/.config/rifterm/config.toml`)
|
|
104
|
+
|
|
105
|
+
## Feuille de route
|
|
106
|
+
|
|
107
|
+
Un endpoint serveur `/cli/report` reste possible plus tard — suivi dans
|
|
108
|
+
l'issue [#3](https://github.com/soloofboom/rifterm/issues/3).
|
|
109
|
+
|
|
110
|
+
## Licence
|
|
111
|
+
|
|
112
|
+
[MIT](LICENSE) — forkez, auditez, contribuez.
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
rifterm/__init__.py,sha256=BgPQl3Trm93joEVdSZOQyWXtD_icjDQz1ASJRBZZOyc,266
|
|
2
|
+
rifterm/cache.py,sha256=IXZQToym85anqWBuSmUYS2PnZug_wIGcQ5viWxAiOE0,3207
|
|
3
|
+
rifterm/cli.py,sha256=ZqBSGtYVjSRQPloKWXmRlCw0N7yIaF5UYC3T3mpDaZY,7485
|
|
4
|
+
rifterm/client.py,sha256=32F8NQHF7u5DCej6NPtA-G6dajT4AmGUEhCmlLwON1k,2976
|
|
5
|
+
rifterm/config.py,sha256=AI9sntSADGOiRqtqLMoUf6b5Of0hMRwN58q1bykFRzk,1294
|
|
6
|
+
rifterm/render.py,sha256=ZlN5P4c8OxzeWNQHAgjI2D30isGtguPJQmuW4X-Gjwo,7771
|
|
7
|
+
rifterm-0.2.0.dist-info/METADATA,sha256=GkbUlqe8fuJxnj7NZPREEHRKydELTZQq8szhTRc1CO8,3798
|
|
8
|
+
rifterm-0.2.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
|
|
9
|
+
rifterm-0.2.0.dist-info/entry_points.txt,sha256=L04seA7wXs-DZEsiSdjM0jHa4cfHYL8C1TOLj4RP_Aw,44
|
|
10
|
+
rifterm-0.2.0.dist-info/licenses/LICENSE,sha256=x1Xk2hO-dCl2zeCQNHQlhl7xLVTOKe6GRJxFKyRIUX8,1066
|
|
11
|
+
rifterm-0.2.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 soloofboom
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|