prabalGaur commited on
Commit
7ecaa4a
·
verified ·
1 Parent(s): 4167189

Upload community_contributions/chrys/sources/metals_api.py with huggingface_hub

Browse files
community_contributions/chrys/sources/metals_api.py ADDED
@@ -0,0 +1,58 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """CommodityPriceAPI adapter for gold (XAU) and silver (XAG)."""
2
+ import requests
3
+
4
+ from models import AssetData
5
+
6
+ BASE = "https://api.commoditypriceapi.com/v2"
7
+
8
+
9
+ def _symbol_to_code(symbol: str) -> str | None:
10
+ s = symbol.upper().replace("/USD", "").strip()
11
+ if s == "XAU":
12
+ return "XAU"
13
+ if s == "XAG":
14
+ return "XAG"
15
+ return None
16
+
17
+
18
+ def fetch_metals(symbol: str, api_key: str = "") -> AssetData | None:
19
+ code = _symbol_to_code(symbol)
20
+ if not code:
21
+ return None
22
+ if not api_key:
23
+ return None
24
+ try:
25
+ r = requests.get(
26
+ f"{BASE}/rates/latest",
27
+ params={"apiKey": api_key, "symbols": code},
28
+ timeout=10,
29
+ )
30
+ r.raise_for_status()
31
+ data = r.json()
32
+ if not data.get("success", False):
33
+ return None
34
+ rates = data.get("rates", {})
35
+ # rates can be { "XAU": 1792.9 } or nested by symbol
36
+ price = rates.get(code)
37
+ if price is None and isinstance(rates, dict):
38
+ for v in rates.values():
39
+ if isinstance(v, (int, float)):
40
+ price = float(v)
41
+ break
42
+ else:
43
+ price = float(price) if price is not None else None
44
+ if price is None or price <= 0:
45
+ return None
46
+ return AssetData(
47
+ asset=symbol,
48
+ price=price,
49
+ change_1h="",
50
+ change_24h="",
51
+ volume_ratio=1.0,
52
+ ohlcv_14=[],
53
+ ohlcv_50=[],
54
+ high_52w=price,
55
+ low_52w=price,
56
+ )
57
+ except Exception:
58
+ return None