File size: 14,518 Bytes
2bbc43c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
#!/usr/bin/env python3
"""FIXED downloader for Binance futures funding rates + depth + equities.

Fixes:
    1. Funding rates: use Binance REST API (works for any historical date)
    2. Depth: try both 'depth' and 'depthBookToTick' paths + monthly fallback
    3. Equities: auto-install yfinance if missing

Usage:
    python scripts/download_fixed.py --out data/more/
"""
import argparse
import json
import logging
import subprocess
import sys
import urllib.request
from pathlib import Path

logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s")
logger = logging.getLogger(__name__)


def download_file(url: str, out_path: Path, timeout: int = 120) -> bool:
    if out_path.exists() and out_path.stat().st_size > 0:
        logger.info("  SKIP (exists): %s", out_path.name)
        return True
    try:
        logger.info("  GET %s", url)
        req = urllib.request.Request(url, headers={"User-Agent": "flash-crash-watchdog/0.4"})
        with urllib.request.urlopen(req, timeout=timeout) as response:
            data = response.read()
            out_path.parent.mkdir(parents=True, exist_ok=True)
            out_path.write_bytes(data)
            size_mb = len(data) / (1024 * 1024)
            logger.info("  βœ“ %s (%.1f MB)", out_path.name, size_mb)
            return True
    except Exception as e:
        logger.error("  βœ— %s", e)
        return False


def download_json(url: str, out_path: Path, timeout: int = 30) -> bool:
    """Download JSON from an API endpoint."""
    if out_path.exists() and out_path.stat().st_size > 0:
        logger.info("  SKIP (exists): %s", out_path.name)
        return True
    try:
        logger.info("  GET %s", url)
        req = urllib.request.Request(url, headers={"User-Agent": "flash-crash-watchdog/0.4"})
        with urllib.request.urlopen(req, timeout=timeout) as response:
            data = json.loads(response.read())
            out_path.parent.mkdir(parents=True, exist_ok=True)
            out_path.write_text(json.dumps(data, indent=2))
            logger.info("  βœ“ %s (%d records)", out_path.name, len(data) if isinstance(data, list) else 1)
            return True
    except Exception as e:
        logger.error("  βœ— %s", e)
        return False


# ═══════════════════════════════════════════════════════════════════════════
# 1. FUNDING RATES via Binance REST API (works for any historical date)
# ═══════════════════════════════════════════════════════════════════════════
def download_funding_rates_api(out_dir: Path) -> int:
    """Download funding rates via Binance Futures REST API.

    API: GET /fapi/v1/fundingRate
    Params: symbol, startTime, endTime, limit (max 1000)
    """
    logger.info("=" * 70)
    logger.info("1. BINANCE FUNDING RATES (via REST API)")
    logger.info("   Inverted funding = extreme short pressure (crypto crash signal)")
    logger.info("=" * 70)

    # Convert dates to timestamps (ms)
    import datetime
    crash_periods = {
        "2021-05-19": ("2021-05-19", "2021-05-20", "May 2021 BTC crash"),
        "2022-05-10": ("2022-05-09", "2022-05-13", "May 2022 LUNA crash"),
        "2022-06-13": ("2022-06-13", "2022-06-14", "Celsius freeze"),
        "2024-08-05": ("2024-08-05", "2024-08-06", "Carry trade unwind"),
    }
    symbols = ["BTCUSDT", "ETHUSDT"]

    success = 0
    total = 0
    for symbol in symbols:
        for date_key, (start, end, desc) in crash_periods.items():
            total += 1
            start_ts = int(datetime.datetime.strptime(start, "%Y-%m-%d").timestamp() * 1000)
            end_ts = int(datetime.datetime.strptime(end, "%Y-%m-%d").timestamp() * 1000)
            url = (
                f"https://fapi.binance.com/fapi/v1/fundingRate"
                f"?symbol={symbol}&startTime={start_ts}&endTime={end_ts}&limit=1000"
            )
            out = out_dir / f"{symbol}-funding-{date_key}.json"
            logger.info("  %s %s β€” %s", symbol, date_key, desc)
            if download_json(url, out):
                success += 1
    logger.info("  Result: %d/%d files\n", success, total)
    return success


# ═══════════════════════════════════════════════════════════════════════════
# 2. OPEN INTEREST + LONG/SHORT RATIO via Binance REST API
# ═══════════════════════════════════════════════════════════════════════════
def download_futures_metrics_api(out_dir: Path) -> int:
    """Download open interest history + long/short ratio via Binance API."""
    logger.info("=" * 70)
    logger.info("2. BINANCE FUTURES METRICS (open interest + long/short ratio)")
    logger.info("=" * 70)

    import datetime
    success = 0
    total = 0

    # Open interest history (5-min intervals, last 30 days available)
    # GET /futures/data/openInterestHist?symbol=BTCUSDT&period=5m&limit=30
    for symbol in ["BTCUSDT", "ETHUSDT"]:
        total += 1
        url = f"https://fapi.binance.com/futures/data/openInterestHist?symbol={symbol}&period=15m&limit=1000"
        out = out_dir / f"{symbol}-open-interest-recent.json"
        if download_json(url, out):
            success += 1

        # Top trader long/short ratio (accounts)
        total += 1
        url = f"https://fapi.binance.com/futures/data/topLongShortAccountRatio?symbol={symbol}&period=15m&limit=1000"
        out = out_dir / f"{symbol}-longshort-ratio-recent.json"
        if download_json(url, out):
            success += 1

        # Taker buy/sell volume
        total += 1
        url = f"https://fapi.binance.com/futures/data/takerlongshortRatio?symbol={symbol}&period=15m&limit=1000"
        out = out_dir / f"{symbol}-taker-volume-recent.json"
        if download_json(url, out):
            success += 1

    logger.info("  Result: %d/%d files\n", success, total)
    return success


# ═══════════════════════════════════════════════════════════════════════════
# 3. DEPTH β€” try multiple paths (daily + monthly, both types)
# ═══════════════════════════════════════════════════════════════════════════
def download_depth_multi(out_dir: Path) -> int:
    """Try multiple URL patterns for Binance depth data."""
    logger.info("=" * 70)
    logger.info("3. BINANCE DEPTH SNAPSHOTS (trying multiple URL patterns)")
    logger.info("=" * 70)

    dates = ["2021-05-19", "2022-05-10", "2024-08-05"]
    success = 0
    total = 0

    for date in dates:
        total += 1
        year, month, day = date.split("-")
        # Try 4 URL patterns in order
        urls = [
            # 1. Daily depthBookToTick
            f"https://data.binance.vision/data/spot/daily/depthBookToTick/BTCUSDT/BTCUSDT-depthBookToTick-{date}.zip",
            # 2. Daily depth (snapshot)
            f"https://data.binance.vision/data/spot/daily/depth/BTCUSDT/BTCUSDT-depth-{date}.zip",
            # 3. Monthly depthBookToTick
            f"https://data.binance.vision/data/spot/monthly/depthBookToTick/BTCUSDT/BTCUSDT-depthBookToTick-{year}-{month}.zip",
            # 4. Monthly depth
            f"https://data.binance.vision/data/spot/monthly/depth/BTCUSDT/BTCUSDT-depth-{year}-{month}.zip",
        ]
        downloaded = False
        for i, url in enumerate(urls):
            out = out_dir / f"BTCUSDT-depth-{date}.zip"
            if download_file(url, out):
                success += 1
                downloaded = True
                break
        if not downloaded:
            logger.warning("  βœ— No depth data available for %s (tried 4 URL patterns)", date)
    logger.info("  Result: %d/%d files\n", success, total)
    return success


# ═══════════════════════════════════════════════════════════════════════════
# 4. EQUITIES via yfinance (auto-install if missing)
# ═══════════════════════════════════════════════════════════════════════════
def ensure_yfinance() -> bool:
    """Ensure yfinance is installed. Returns True if available."""
    try:
        import yfinance  # noqa: F401
        return True
    except ImportError:
        logger.info("  yfinance not installed. Installing...")
        try:
            subprocess.check_call([sys.executable, "-m", "pip", "install", "yfinance", "--quiet"])
            logger.info("  βœ“ yfinance installed")
            return True
        except Exception as e:
            logger.error("  βœ— Failed to install yfinance: %s", e)
            logger.error("  Run manually: pip install yfinance")
            return False


def download_equities(out_dir: Path) -> int:
    """Download US equity + VIX data for flash-crash dates via yfinance."""
    logger.info("=" * 70)
    logger.info("4. US EQUITY DATA (SPY, QQQ, VIX, XLF, XLE via yfinance)")
    logger.info("   The May 6, 2010 US equities flash crash β€” the canonical case")
    logger.info("=" * 70)

    if not ensure_yfinance():
        return 0

    import yfinance as yf

    tickers = ["SPY", "QQQ", "^VIX", "XLF", "XLE"]
    periods = {
        "2010-05-06": "May 6, 2010 US equities flash crash (Dow -9.2% in 36 min)",
        "2015-08-24": "Aug 24, 2015 flash crash (China devaluation)",
        "2020-03-12": "March 12, 2020 COVID crash",
        "2024-08-05": "Aug 5, 2024 carry-trade unwind",
    }

    out_dir.mkdir(parents=True, exist_ok=True)
    success = 0
    total = 0
    for ticker_symbol in tickers:
        for date, desc in periods.items():
            total += 1
            logger.info("  %s %s β€” %s", ticker_symbol, date, desc)
            # Download 5 days around the crash date
            start = date
            year, month, day = map(int, date.split("-"))
            # End = date + 5 days
            from datetime import datetime, timedelta
            end_dt = datetime(year, month, day) + timedelta(days=5)
            end = end_dt.strftime("%Y-%m-%d")
            try:
                ticker = yf.Ticker(ticker_symbol)
                # Try 1-minute data first (most granular)
                hist = ticker.history(start=start, end=end, interval="1m")
                if hist.empty:
                    hist = ticker.history(start=start, end=end, interval="5m")
                if hist.empty:
                    hist = ticker.history(start=start, end=end, interval="1h")
                if hist.empty:
                    hist = ticker.history(start=start, end=end, interval="1d")
                if not hist.empty:
                    out = out_dir / f"YFINANCE-{ticker_symbol.replace('^','')}-{date}.csv"
                    hist.to_csv(out)
                    size_kb = out.stat().st_size / 1024
                    logger.info("    βœ“ %s (%.1f KB, %d bars)", out.name, size_kb, len(hist))
                    success += 1
                else:
                    logger.warning("    βœ— No data for %s on %s", ticker_symbol, date)
            except Exception as e:
                logger.error("    βœ— %s: %s", ticker_symbol, e)
    logger.info("  Result: %d/%d files\n", success, total)
    return success


# ═══════════════════════════════════════════════════════════════════════════
# 5. BYBIT historical klines (cross-exchange)
# ═══════════════════════════════════════════════════════════════════════════
def download_bybit(out_dir: Path) -> int:
    """Download Bybit historical 1-min klines (cross-exchange)."""
    logger.info("=" * 70)
    logger.info("5. BYBIT HISTORICAL KLINES (cross-exchange β€” venue #2)")
    logger.info("=" * 70)
    dates = ["2021-05-19", "2022-05-10", "2024-08-05"]
    symbols = ["BTCUSDT", "ETHUSDT"]
    success = 0
    total = 0
    for symbol in symbols:
        for date in dates:
            total += 1
            url = f"https://public.bybit.com/kline/{symbol}/{date}/1min.csv.gz"
            out = out_dir / f"BYBIT-{symbol}-1min-{date}.csv.gz"
            if download_file(url, out):
                success += 1
    logger.info("  Result: %d/%d files\n", success, total)
    return success


def main() -> int:
    parser = argparse.ArgumentParser(description="Download fixed datasets (funding API + depth + equities)")
    parser.add_argument("--out", default="data/more/", help="Output directory")
    parser.add_argument("--only", default=None,
                        help="Comma-separated: funding,metrics,depth,equities,bybit")
    args = parser.parse_args()

    out_dir = Path(args.out)
    only = set(args.only.split(",")) if args.only else None

    total = 0
    if only is None or "funding" in only:
        total += download_funding_rates_api(out_dir / "futures")
    if only is None or "metrics" in only:
        total += download_futures_metrics_api(out_dir / "metrics")
    if only is None or "depth" in only:
        total += download_depth_multi(out_dir / "depth")
    if only is None or "equities" in only:
        total += download_equities(out_dir / "equities")
    if only is None or "bybit" in only:
        total += download_bybit(out_dir / "bybit")

    logger.info("=" * 70)
    logger.info("  DOWNLOAD COMPLETE β€” %d files total", total)
    logger.info("  Output: %s", out_dir.resolve())
    logger.info("=" * 70)
    return 0 if total > 0 else 1


if __name__ == "__main__":
    raise SystemExit(main())