- common/dataset.py: сохранение/загрузка фиксированного датасета для воспроизводимых экспериментов (данные больше не плывут между запусками) - exp18 run.py, run_per_asset_k.py: переведены на load_or_fetch() - exp18b результат: BTC=3+ADA=3 даёт +$23 (+20.4%) при DD -0.6% (Equity $265.45 vs $242.26 uniform K=2) - Применено в продакшн: config.yaml BTC K=3, ADA K=3 Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
106 lines
3.8 KiB
Python
106 lines
3.8 KiB
Python
"""Fixed dataset management for reproducible experiments.
|
|
|
|
Save once with save_dataset.py, then load in any experiment.
|
|
"""
|
|
|
|
import json
|
|
from pathlib import Path
|
|
|
|
import numpy as np
|
|
|
|
DATA_DIR = Path(__file__).parent.parent / "data"
|
|
|
|
ASSETS = [
|
|
{"symbol": "BTC/USDC", "ticker": "BTC-USD", "tf": "4h", "ws": 32, "leverage": 2, "weight": 0.241},
|
|
{"symbol": "ETH/USDC", "ticker": "ETH-USD", "tf": "2h", "ws": 64, "leverage": 2, "weight": 0.158},
|
|
{"symbol": "ADA/USDC", "ticker": "ADA-USD", "tf": "4h", "ws": 64, "leverage": 2, "weight": 0.137},
|
|
{"symbol": "DOT/USDC", "ticker": "DOT-USD", "tf": "4h", "ws": 32, "leverage": 2, "weight": 0.137},
|
|
{"symbol": "DOGE/USDC", "ticker": "DOGE-USD", "tf": "4h", "ws": 48, "leverage": 2, "weight": 0.127},
|
|
{"symbol": "SOL/USDC", "ticker": "SOL-USD", "tf": "2h", "ws": 128, "leverage": 2, "weight": 0.108},
|
|
{"symbol": "XRP/USDC", "ticker": "XRP-USD", "tf": "4h", "ws": 64, "leverage": 2, "weight": 0.092},
|
|
]
|
|
|
|
|
|
def save_dataset(name: str = "default") -> Path:
|
|
"""Fetch all assets from exchange and save as fixed dataset."""
|
|
import sys
|
|
sys.path.insert(0, str(Path(__file__).parent.parent.parent / "src"))
|
|
from remizov_trader.core.signals import fetch_prices_ccxt
|
|
|
|
DATA_DIR.mkdir(parents=True, exist_ok=True)
|
|
dataset_dir = DATA_DIR / name
|
|
dataset_dir.mkdir(parents=True, exist_ok=True)
|
|
|
|
meta = {"assets": {}}
|
|
|
|
for a in ASSETS:
|
|
ticker, symbol, tf = a["ticker"], a["symbol"], a["tf"]
|
|
print(f" Fetching {ticker} ({tf})...", end=" ", flush=True)
|
|
|
|
prices, dates = fetch_prices_ccxt(symbol, tf, "max")
|
|
if prices is None or len(prices) < 100:
|
|
print("SKIP (not enough data)")
|
|
continue
|
|
|
|
# Save prices as .npy, dates as strings in .json
|
|
np.save(dataset_dir / f"{ticker}_prices.npy", prices)
|
|
dates_str = [str(d) for d in dates]
|
|
(dataset_dir / f"{ticker}_dates.json").write_text(json.dumps(dates_str))
|
|
|
|
meta["assets"][ticker] = {
|
|
"symbol": symbol, "tf": tf, "ws": a["ws"],
|
|
"leverage": a["leverage"], "weight": a["weight"],
|
|
"bars": len(prices),
|
|
"date_range": f"{dates_str[0]} -> {dates_str[-1]}",
|
|
}
|
|
print(f"{len(prices)} bars ({dates_str[0][:10]} -> {dates_str[-1][:10]})")
|
|
|
|
from datetime import datetime
|
|
meta["created"] = datetime.now().isoformat()
|
|
meta["name"] = name
|
|
(dataset_dir / "meta.json").write_text(json.dumps(meta, indent=2))
|
|
|
|
print(f"\nDataset saved: {dataset_dir}")
|
|
return dataset_dir
|
|
|
|
|
|
def load_dataset(name: str = "default") -> dict:
|
|
"""Load fixed dataset. Returns dict[ticker] -> {prices, dates, tf, ws, ...}."""
|
|
dataset_dir = DATA_DIR / name
|
|
if not dataset_dir.exists():
|
|
raise FileNotFoundError(
|
|
f"Dataset '{name}' not found at {dataset_dir}. "
|
|
f"Run: .venv/bin/python3 experiments/common/save_dataset.py"
|
|
)
|
|
|
|
meta_path = dataset_dir / "meta.json"
|
|
meta = json.loads(meta_path.read_text())
|
|
|
|
result = {}
|
|
for ticker, info in meta["assets"].items():
|
|
prices = np.load(dataset_dir / f"{ticker}_prices.npy")
|
|
dates_str = json.loads((dataset_dir / f"{ticker}_dates.json").read_text())
|
|
# Convert to numpy array of date strings for compatibility
|
|
dates = np.array(dates_str)
|
|
|
|
result[ticker] = {
|
|
"prices": prices,
|
|
"dates": dates,
|
|
"tf": info["tf"],
|
|
"ws": info["ws"],
|
|
"leverage": info["leverage"],
|
|
"weight": info["weight"],
|
|
}
|
|
|
|
return result
|
|
|
|
|
|
def load_or_fetch(name: str = "default") -> dict:
|
|
"""Load dataset if exists, otherwise fetch and save."""
|
|
try:
|
|
return load_dataset(name)
|
|
except FileNotFoundError:
|
|
print(f"Dataset '{name}' not found, fetching from exchange...")
|
|
save_dataset(name)
|
|
return load_dataset(name)
|