3kmfi6hp/mcp-serverless-tools / cron_sim_yield_variant.py
3kmfi6hp's picture
download
raw
4.78 kB
"""WQ Alpha Research — yield variant candidate simulation"""
import json, time, requests, sys
from pathlib import Path
API_BASE = "https://api.worldquantbrain.com"
CRED_FILE = Path("/home/gyue/.hermes/skills/wq-alpha-research/credential.txt")
# 认证
with open(CRED_FILE) as f:
creds = f.read().strip()
if creds.startswith("1|"):
creds = creds[2:]
username, password = json.loads(creds)
session = requests.Session()
session.auth = requests.auth.HTTPBasicAuth(username, password)
session.headers.update({"Content-Type": "application/json", "Accept": "application/json"})
resp = session.post(f"{API_BASE}/authentication", timeout=30)
if resp.status_code != 201:
print(f"FAIL auth: {resp.status_code}")
sys.exit(1)
print("OK auth")
# Step 1: verify field
print("--- verify: rank(cashflow_op / close) ---")
v = {
"type": "REGULAR",
"settings": {
"instrumentType": "EQUITY", "region": "USA", "universe": "TOP3000",
"delay": 1, "decay": 0, "neutralization": "MARKET",
"truncation": 0.08, "pasteurization": "ON", "unitHandling": "VERIFY",
"nanHandling": "ON", "language": "FASTEXPR", "visualization": False,
},
"regular": "rank(cashflow_op / close)",
}
r = session.post(f"{API_BASE}/simulations", json=v)
if r.status_code != 201:
print(f"FAIL verify: {r.status_code} {r.text[:200]}")
sys.exit(1)
print("OK cashflow_op / close available")
sim_id = r.headers["Location"].rstrip("/").split("/")[-1]
for _ in range(60):
d = session.get(f"{API_BASE}/simulations/{sim_id}", timeout=30).json()
if d.get("status") == "COMPLETE":
print(f"verify complete alpha={d['alpha']}")
break
if d.get("status") in ("ERROR", "FAILED"):
print(f"FAIL verify sim: {d}")
sys.exit(1)
time.sleep(5)
# Step 2: simulate
print("--- simulate: group_rank(ts_rank(cashflow_op / close, 210), industry) ---")
p = {
"type": "REGULAR",
"settings": {
"instrumentType": "EQUITY", "region": "USA", "universe": "TOP3000",
"delay": 1, "decay": 0, "neutralization": "INDUSTRY",
"truncation": 0.08, "pasteurization": "ON", "unitHandling": "VERIFY",
"nanHandling": "ON", "language": "FASTEXPR", "visualization": False,
},
"regular": "group_rank(ts_rank(cashflow_op / close, 210), industry)",
}
r = session.post(f"{API_BASE}/simulations", json=p)
if r.status_code != 201:
print(f"FAIL sim: {r.status_code} {r.text[:200]}")
sys.exit(1)
sim_id = r.headers["Location"].rstrip("/").split("/")[-1]
print(f"sim_id={sim_id}")
for i in range(60):
d = session.get(f"{API_BASE}/simulations/{sim_id}", timeout=30).json()
if d.get("status") == "COMPLETE":
aid = d["alpha"]
print(f"OK complete alpha={aid}")
break
if d.get("status") in ("ERROR", "FAILED"):
print(f"FAIL sim: {d}")
sys.exit(1)
time.sleep(5)
else:
print("FAIL timeout")
sys.exit(1)
# Step 3: metrics
a = session.get(f"{API_BASE}/alphas/{aid}", timeout=30).json()
is_ = a.get("is", {})
sh = is_.get("sharpe", 0)
fit = is_.get("fitness", 0)
to_ = is_.get("turnover", 1)
ret = is_.get("returns", 0)
dd = is_.get("maxDrawdown", 0)
print(f"\nRESULT {aid}")
print(f" Sharpe={sh} Fitness={fit} TO={to_} Ret={ret} DD={dd}")
checks = is_.get("checks", [])
is_pass = True
for c in checks:
n, r2 = c.get("name", "?"), c.get("result", "?")
print(f" {r2} {n}")
if r2 == "FAIL":
is_pass = False
s = is_.get("sharpe", 0)
print(f"\n IS Pass (excl SC): {'YES' if is_pass else 'NO'}")
# Step 4: submit
ok = (
isinstance(s, (int, float)) and s >= 1.3
and isinstance(fit, (int, float)) and fit >= 1.0
and isinstance(to_, (int, float)) and to_ <= 0.35
and is_pass
)
if ok:
print("METRICS OK -> submit")
sub = session.post(f"{API_BASE}/alphas/{aid}/submit", timeout=30)
print(f" submit status={sub.status_code}")
if sub.status_code in (200, 201):
for j in range(36):
time.sleep(10)
a2 = session.get(f"{API_BASE}/alphas/{aid}", timeout=30).json()
st = a2.get("status")
sc_c = [c for c in a2.get("is", {}).get("checks", []) if c.get("name") == "SELF_CORRELATION"]
sc_r = sc_c[0].get("result", "?") if sc_c else "?"
if st == "ACTIVE":
print(f"ACTIVE! {aid}")
break
if sc_r == "FAIL":
print(f"SELF_CORR FAIL st={st}")
break
if j % 6 == 0:
print(f" wait... st={st} SC={sc_r} ({j*10}s)")
else:
print(f"timeout st={a2.get('status')} SC={sc_r}")
elif sub.status_code == 403:
print(f"403 cooling: {sub.text[:200]}")
else:
print("SKIP not meeting thresholds")
print("DONE")

Xet Storage Details

Size:
4.78 kB
·
Xet hash:
7051541d1bb83787db7fe07a2f119f6e87f44a78c20802048fa2e26b3f32ec02

Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.