File size: 9,762 Bytes
db0a14e e125fa3 db0a14e e125fa3 db0a14e e125fa3 db0a14e e125fa3 db0a14e e125fa3 db0a14e e125fa3 db0a14e e125fa3 db0a14e e125fa3 db0a14e e125fa3 db0a14e e125fa3 db0a14e e125fa3 db0a14e | 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 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 | import os
import argparse
from typing import List, Optional, Sequence, Tuple
from dotenv import load_dotenv
from clickhouse_driver import Client as ClickHouseClient
def parse_args() -> argparse.Namespace:
parser = argparse.ArgumentParser(
description="Fast SQL-based hyperparameter analysis (trades-only) for seq_len + horizons."
)
parser.add_argument("--token_address", type=str, default=None, help="Analyze a single token address.")
parser.add_argument(
"--windows_min",
type=str,
default="5,10,30,60",
help="Comma-separated trade-count windows in minutes (e.g. '5,10,30,60').",
)
parser.add_argument(
"--min_price_usd",
type=float,
default=0.0,
help="Treat trades with price_usd <= min_price_usd as invalid (default: 0.0).",
)
return parser.parse_args()
def _parse_windows(windows_min: str) -> List[int]:
out: List[int] = []
for part in (windows_min or "").split(","):
part = part.strip()
if not part:
continue
out.append(int(part))
out = sorted(set([w for w in out if w > 0]))
if not out:
raise ValueError("No valid --windows_min provided.")
return out
def _connect_clickhouse_from_env() -> ClickHouseClient:
ch_host = os.getenv("CLICKHOUSE_HOST", "localhost")
ch_port = int(os.getenv("CLICKHOUSE_NATIVE_PORT", "9000"))
ch_user = os.getenv("CLICKHOUSE_USER", None)
ch_pass = os.getenv("CLICKHOUSE_PASSWORD", None)
ch_db = os.getenv("CLICKHOUSE_DB", None)
kwargs = {"host": ch_host, "port": ch_port}
if ch_user:
kwargs["user"] = ch_user
if ch_pass:
kwargs["password"] = ch_pass
if ch_db:
kwargs["database"] = ch_db
return ClickHouseClient(**kwargs)
def _quantile_levels() -> Sequence[float]:
# Keep these aligned with the printed labels below.
return (0.25, 0.5, 0.75, 0.90, 0.95, 0.99)
def _fmt_q_tuple(q: Tuple[float, ...]) -> str:
# Labels match _quantile_levels()
labels = ["25%", "50%", "75%", "90%", "95%", "99%"]
parts = []
for lbl, v in zip(labels, q):
parts.append(f"{lbl}: {float(v):.2f}")
return " | ".join(parts)
def _print_row(prefix: str, mean_v: float, q_tuple: Tuple[float, ...], max_v: float) -> None:
print(f"[{prefix}]")
print(f" Mean: {float(mean_v):.2f} | Median: {float(q_tuple[1]):.2f} | Max: {float(max_v):.2f}")
print(f" {_fmt_q_tuple(q_tuple)}")
def fetch_aggregated_stats_sql(
ch: ClickHouseClient,
windows_min: List[int],
min_price_usd: float,
token_address: Optional[str] = None,
) -> List[tuple]:
"""
One ClickHouse query that computes distribution statistics directly (no per-token loop in Python).
Returns two groups:
- grp='all'
- grp='subset' where trades_full > 50 and lifespan_sec > 300 (5 minutes)
"""
q_levels = _quantile_levels()
q_levels_sql = ", ".join(str(q) for q in q_levels)
per_token_window_exprs = []
agg_window_exprs = []
for w in windows_min:
sec = int(w) * 60
per_token_window_exprs.append(
f"countIf(is_valid AND (trade_ts - mint_ts) <= {sec}) AS trades_{w}m"
)
agg_window_exprs.append(
f"avg(trades_{w}m) AS trades_{w}m_mean,"
f" quantilesExact({q_levels_sql})(trades_{w}m) AS trades_{w}m_q,"
f" max(trades_{w}m) AS trades_{w}m_max"
)
params = {"min_price": float(min_price_usd)}
token_filter = ""
if token_address:
token_filter = "AND m.mint_address = %(token)s"
params["token"] = token_address
# Note: we pre-filter trades to only minted tokens for speed.
query = f"""
WITH
per_token AS (
SELECT
m.mint_address AS mint_address,
toUnixTimestamp(m.timestamp) AS mint_ts,
countIf(is_valid) AS trades_full,
(maxIf(trade_ts, is_valid) - mint_ts) AS lifespan_sec,
(toUnixTimestamp(argMaxIf(t.timestamp, t.price_usd, is_valid)) - mint_ts) AS time_to_ath_sec,
{", ".join(per_token_window_exprs)}
FROM mints AS m
INNER JOIN
(
SELECT
base_address,
timestamp,
toUnixTimestamp(timestamp) AS trade_ts,
price_usd,
(price_usd > %(min_price)s) AS is_valid
FROM trades
WHERE base_address IN (SELECT mint_address FROM mints)
) AS t
ON t.base_address = m.mint_address
WHERE 1=1
{token_filter}
GROUP BY
mint_address,
mint_ts
HAVING
trades_full > 0
)
SELECT
grp,
count() AS tokens,
avg(trades_full) AS trades_full_mean,
quantilesExact({q_levels_sql})(trades_full) AS trades_full_q,
max(trades_full) AS trades_full_max,
avg(lifespan_sec / 60.0) AS lifespan_min_mean,
quantilesExact({q_levels_sql})(lifespan_sec / 60.0) AS lifespan_min_q,
max(lifespan_sec / 60.0) AS lifespan_min_max,
avg(time_to_ath_sec / 60.0) AS tta_min_mean,
quantilesExact({q_levels_sql})(time_to_ath_sec / 60.0) AS tta_min_q,
max(time_to_ath_sec / 60.0) AS tta_min_max,
{", ".join(agg_window_exprs)}
FROM per_token
ARRAY JOIN ['all', 'subset'] AS grp
WHERE (grp = 'all')
OR (grp = 'subset' AND trades_full > 50 AND lifespan_sec > 300)
GROUP BY grp
ORDER BY grp
"""
return ch.execute(query, params)
def fetch_single_token_sql(
ch: ClickHouseClient,
windows_min: List[int],
min_price_usd: float,
token_address: str,
) -> Optional[tuple]:
per_token_window_exprs = []
for w in windows_min:
sec = int(w) * 60
per_token_window_exprs.append(
f"countIf(is_valid AND (trade_ts - mint_ts) <= {sec}) AS trades_{w}m"
)
params = {"min_price": float(min_price_usd), "token": token_address}
query = f"""
SELECT
m.mint_address AS mint_address,
toUnixTimestamp(m.timestamp) AS mint_ts,
countIf(is_valid) AS trades_full,
(maxIf(trade_ts, is_valid) - mint_ts) AS lifespan_sec,
(toUnixTimestamp(argMaxIf(t.timestamp, t.price_usd, is_valid)) - mint_ts) AS time_to_ath_sec,
{", ".join(per_token_window_exprs)}
FROM mints AS m
INNER JOIN
(
SELECT
base_address,
timestamp,
toUnixTimestamp(timestamp) AS trade_ts,
price_usd,
(price_usd > %(min_price)s) AS is_valid
FROM trades
WHERE base_address = %(token)s
) AS t
ON t.base_address = m.mint_address
WHERE m.mint_address = %(token)s
GROUP BY
mint_address,
mint_ts
HAVING
trades_full > 0
"""
rows = ch.execute(query, params)
return rows[0] if rows else None
def main() -> None:
load_dotenv()
args = parse_args()
windows_min = _parse_windows(args.windows_min)
print("--- Hyperparameter Calibration Analysis (FAST SQL) ---")
print(f"Windows (min): {windows_min}")
print(f"Valid trade filter: price_usd > {float(args.min_price_usd)}")
ch = _connect_clickhouse_from_env()
if args.token_address:
row = fetch_single_token_sql(
ch=ch,
windows_min=windows_min,
min_price_usd=float(args.min_price_usd),
token_address=args.token_address,
)
if not row:
print("Token not found (or no valid trades).")
return
mint_addr = row[0]
trades_full = int(row[2])
lifespan_min = float(row[3]) / 60.0
tta_min = float(row[4]) / 60.0
print("\n" + "=" * 40)
print("RESULTS (SINGLE TOKEN)")
print("=" * 40)
print(f"Token: {mint_addr}")
print(f"Valid trades: {trades_full}")
print(f"Lifespan (min): {lifespan_min:.2f}")
print(f"Time to ATH (min): {tta_min:.2f}")
for i, w in enumerate(windows_min):
print(f"Trades in first {w}m: {int(row[5 + i])}")
else:
rows = fetch_aggregated_stats_sql(
ch=ch,
windows_min=windows_min,
min_price_usd=float(args.min_price_usd),
token_address=None,
)
if not rows:
print("No tokens found with valid trades.")
return
print("\n" + "=" * 40)
print("RESULTS (DISTRIBUTION)")
print("=" * 40)
# Row layout:
# grp, tokens,
# trades_full_mean, trades_full_q(tuple), trades_full_max,
# lifespan_min_mean, lifespan_min_q(tuple), lifespan_min_max,
# tta_min_mean, tta_min_q(tuple), tta_min_max,
# repeated for each window: mean, q(tuple), max
for row in rows:
grp = row[0]
tokens = int(row[1])
print(f"\n--- Group: {grp} (tokens={tokens}) ---")
_print_row("Trades (Full History, Valid Only)", row[2], row[3], row[4])
print("")
_print_row("Token Lifespan (Minutes)", row[5], row[6], row[7])
print("")
_print_row("Time to ATH (Minutes)", row[8], row[9], row[10])
cursor = 11
for w in windows_min:
mean_v = row[cursor]
q_v = row[cursor + 1]
max_v = row[cursor + 2]
cursor += 3
print("")
_print_row(f"Trades in First {w} Minutes (Valid Only)", mean_v, q_v, max_v)
print("\nRecommendation Logic (Trades-only):")
print("- Horizons: look at Time-to-ATH p90/p95 (all vs subset).")
print("- Max seq len: look at Trades-in-first-(max horizon) p95/p99.")
print(" Then add headroom for non-trade events (transfers/pool/liquidity/etc).")
if __name__ == "__main__":
main()
|