File size: 24,188 Bytes
b45802a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
13bec2b
 
b45802a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
"""
================================================================================
PUMP.FUN MEMECOIN RESEARCH CORPUS — EXPANDED QUICKSTART & ANALYST SUITE
================================================================================

HOW TO DOWNLOAD THE DATASET & LOAD YOUR WORKSPACE:
--------------------------------------------------------------------------------
1. Using huggingface-cli (Recommended — downloads all files & shards in parallel):
   $ pip install huggingface_hub
   $ huggingface-cli download <your-hf-username>/<your-repo-name> --local-dir ./pumpfun_data

2. Using Git LFS:
   $ git lfs install
   $ git clone https://huggingface.co/datasets/<your-hf-username>/<your-repo-name> ./pumpfun_data

3. Programmatic zero-disk load in Python via DuckDB over HTTP:
   import duckdb
   df = duckdb.query('''
       SELECT * FROM 'https://huggingface.co/datasets/<username>/<repo>/resolve/main/tokens.parquet' 
       LIMIT 10
   ''').df()

EXPECTED DIRECTORY STRUCTURE (--data-dir ./pumpfun_data):
   pumpfun_data/
   ├── tokens.parquet              (798,430 rows | Master definitions & creator features)
   ├── snapshots.parquet           (26,934,769 rows | Pre-grad bonding curve time-series)
   ├── postgard_snapshots.parquet  (1,392,133 rows | Post-grad DEX liquidity snapshots)
   ├── postgard_outcomes.parquet   (5,669 rows | Post-grad outcome labels & performance)
   ├── wallet_stats.parquet        (1,016,374 rows | User wallet activity & volume profiles)
   ├── migrations.parquet          (5,701 rows | Raydium migration event logs)
   └── trades/                     (33,581,704 rows | Sharded execution ledger)
       ├── shard_01.parquet
       ├── ...
       └── shard_11.parquet

MANDATORY DATA-QUALITY FILTERS APPLIED IN THIS SUITE:
   1. System Program Exclusion: 
      user_wallet != 'BwWK17cbHxwWBKZkUYvzxLcNQ1YVyaFezduWbtm2de6s'
      (Excludes protocol system-level SOL transfer accounting records from trade logs).
   2. Suspect Concentration Row Exclusion: 
      WHERE NOT COALESCE(top10_pct_suspect, FALSE)
      (Excludes tokens with scraped top-10 concentration data anomalies).
   3. Trade-Derived Feature Reconstruction:
      Rebuilds time-windowed microstructure signals directly from trades/*.parquet 
      to bypass snapshot heartbeat-duplication artifacts (~90-95% carry-forward dupes).

USAGE:
   $ python quickstart.py --data-dir ./pumpfun_data
   $ python quickstart.py --data-dir /path/to/dataset --threads 8 --memory-limit 8GB
================================================================================
"""

import argparse
import os
import sys
import time
from typing import List, Tuple
import duckdb

# System Program Wallet Address (MUST be excluded from trade-level analysis)
SYSTEM_PROGRAM_WALLET = "BwWK17cbHxwWBKZkUYvzxLcNQ1YVyaFezduWbtm2de6s"


def print_banner(section_num: int, title: str) -> None:
    """Prints a standardized visual CLI section banner."""
    print("\n" + "=" * 80)
    print(f"=== SECTION {section_num}: {title.upper()} ===")
    print("=" * 80)


def configure_duckdb(threads: int = 4, memory_limit: str = "4GB") -> duckdb.DuckDBPyConnection:
    """
    Initializes an in-memory DuckDB connection optimized for high-throughput 
    Parquet scanning across multi-threaded CPU cores.
    """
    con = duckdb.connect(database=":memory:")
    con.execute(f"PRAGMA threads={threads};")
    con.execute(f"PRAGMA memory_limit='{memory_limit}';")
    con.execute("PRAGMA preserve_insertion_order=false;")
    return con


# ==============================================================================
# 1. CORPUS DISCOVERY & TABLE FOOTPRINT AUDIT
# ==============================================================================
def audit_corpus_structure(con: duckdb.DuckDBPyConnection, data_dir: str) -> None:
    """
    Validates physical presence and DuckDB readability of all 7 dataset components.
    Executes schema checks and scans row/column footprints, including multi-file 
    shards in `trades/*.parquet`.
    """
    print_banner(1, "Corpus Structure & File Inspection")

    table_configs: List[Tuple[str, str]] = [
        ("tokens", f"{data_dir}/tokens.parquet"),
        ("snapshots", f"{data_dir}/snapshots.parquet"),
        ("postgard_snapshots", f"{data_dir}/postgard_snapshots.parquet"),
        ("postgard_outcomes", f"{data_dir}/postgard_outcomes.parquet"),
        ("wallet_stats", f"{data_dir}/wallet_stats.parquet"),
        ("migrations", f"{data_dir}/migrations.parquet"),
        ("trades (sharded 11x)", f"{data_dir}/trades/*.parquet"),
    ]

    total_records = 0
    print(f"{'Table Name':<25} | {'Row Count':>15} | {'Col Count':>10} | {'Status'}")
    print("-" * 65)

    for name, path_glob in table_configs:
        try:
            # Query column structure and row counts using parallel Parquet readers
            col_query = f"SELECT COUNT(COLUMN_NAME) FROM (DESCRIBE SELECT * FROM read_parquet('{path_glob}'))"
            col_count = con.execute(col_query).fetchone()[0]

            row_query = f"SELECT COUNT(*) FROM read_parquet('{path_glob}')"
            row_count = con.execute(row_query).fetchone()[0]
            
            total_records += row_count
            print(f"{name:<25} | {row_count:>15,} | {col_count:>10} | VALID")
        except Exception as err:
            print(f"{name:<25} | {'N/A':>15} | {'N/A':>10} | ERROR ({err})")

    print("-" * 65)
    print(f"{'TOTAL INTEGRATED RECORDS':<25} | {total_records:>15,} |")
    print("\n[INFO] Sharded read check on trades/*.parquet verified across all Parquet shards.")


# ==============================================================================
# 2. DATA QUALITY AUDIT: TOKENS & CREATOR DIAGNOSTICS
# ==============================================================================
def audit_tokens_quality(con: duckdb.DuckDBPyConnection, data_dir: str) -> None:
    """
    Audits the master token definitions table (`tokens.parquet`):
    - Evaluates total token population and baseline graduation rate (~0.71%).
    - Quantifies suspect top-10 concentration rows that must be excluded.
    - Inspects structural missingness in initial_gini (requires >=3 holders to compute).
    """
    print_banner(2, "Tokens Table Quality & Graduation Base Rate")

    query = f"""
        SELECT 
            COUNT(*) AS total_tokens,
            COUNT(*) FILTER (WHERE COALESCE(top10_pct_suspect, FALSE)) AS n_suspect_rows,
            COUNT(*) FILTER (WHERE graduated_at IS NOT NULL) AS n_graduated,
            COUNT(*) FILTER (WHERE initial_gini IS NULL) AS n_null_gini,
            COUNT(*) FILTER (WHERE initial_gini IS NULL AND graduated_at IS NOT NULL) AS n_null_gini_graduated,
            ROUND(AVG(initial_holder_count), 2) AS avg_initial_holders
        FROM read_parquet('{data_dir}/tokens.parquet')
    """
    stats = con.execute(query).fetchdf()

    total = stats['total_tokens'][0]
    suspect = stats['n_suspect_rows'][0]
    graduated = stats['n_graduated'][0]
    null_gini = stats['n_null_gini'][0]
    null_gini_grad = stats['n_null_gini_graduated'][0]

    grad_rate = (graduated / total) * 100.0
    clean_total = total - suspect

    print(f"Total Tokens Evaluated:      {total:>10,}")
    print(f"Suspect Top10% Rows:        {suspect:>10,} (Excl. required for clean feature models)")
    print(f"Clean Tokens Population:    {clean_total:>10,}")
    print(f"Graduated Tokens:           {graduated:>10,} ({grad_rate:.2f}% base graduation rate)")
    print(f"Initial Gini NULLs:         {null_gini:>10,} ({100*null_gini/total:.1f}% overall — structural: <3 holders)")
    print(f"Initial Gini NULLs (Grad):  {null_gini_grad:>10,} (Only {null_gini_grad} graduated token missing Gini)")
    print(f"\n[DIAGNOSTIC] Initial Gini missingness is strictly structural (tokens with <3 holders at block zero).")


# ==============================================================================
# 3. DATA QUALITY AUDIT: TRADES & SYSTEM PROGRAM FILTERING
# ==============================================================================
def audit_trades_quality(con: duckdb.DuckDBPyConnection, data_dir: str) -> None:
    """
    Audits the execution ledger across all sharded Parquet files (`trades/*.parquet`):
    - Detects and quantifies System Program wallet records (must be filtered out).
    - Checks for price and volume integrity anomalies (NULL/zero amounts).
    - Measures overall distinct active trader addresses.
    """
    print_banner(3, "Trades Ledger Quality & System Wallet Filtering")

    query = f"""
        SELECT 
            COUNT(*) AS total_trades,
            COUNT(*) FILTER (WHERE user_wallet = '{SYSTEM_PROGRAM_WALLET}') AS sysprog_trades,
            COUNT(*) FILTER (WHERE price_sol IS NULL OR price_sol <= 0) AS invalid_price_trades,
            COUNT(*) FILTER (WHERE sol_amount IS NULL OR sol_amount <= 0) AS invalid_sol_trades,
            COUNT(DISTINCT user_wallet) AS unique_active_traders,
            COUNT(DISTINCT mint) AS unique_traded_mints
        FROM read_parquet('{data_dir}/trades/*.parquet')
    """
    df = con.execute(query).fetchdf()

    n_total = df['total_trades'][0]
    n_sys = df['sysprog_trades'][0]
    n_bad_price = df['invalid_price_trades'][0]
    n_bad_sol = df['invalid_sol_trades'][0]
    n_traders = df['unique_active_traders'][0]

    sys_pct = 100.0 * n_sys / n_total

    print(f"Total Granular Trades:       {n_total:>12,}")
    print(f"System Program Wallet Trades:{n_sys:>12,} ({sys_pct:.2f}% of corpus — EXCLUSION MANDATORY)")
    print(f"Unique Active Wallets:       {n_traders:>12,}")
    print(f"Invalid Price Rows (<=0/NULL):{n_bad_price:>11,}")
    print(f"Invalid SOL Amount Rows:     {n_bad_sol:>12,}")
    print(f"\n[FILTERING NOTE] Filtering out '{SYSTEM_PROGRAM_WALLET}' removes protocol accounting trades.")


# ==============================================================================
# 4. METRIC A: GRADUATION RATE BY CREATOR EXPERIENCE TIER
# ==============================================================================
def metric_creator_experience(con: duckdb.DuckDBPyConnection, data_dir: str) -> None:
    """
    Computes token graduation rate bucketed by developer track record (`creator_past_tokens`).
    Demonstrates that experienced creators achieve up to ~19x-25x higher graduation rates.
    """
    print_banner(4, "Metric A: Graduation Rate by Creator Experience Tier")

    query = f"""
        WITH tiered AS (
            SELECT
                mint,
                graduated_at IS NOT NULL AS is_graduated,
                CASE
                    WHEN COALESCE(creator_past_tokens, 0) = 0 THEN '01_first_time (0)'
                    WHEN creator_past_tokens <= 10 THEN '02_novice (1-10)'
                    WHEN creator_past_tokens <= 100 THEN '03_experienced (11-100)'
                    ELSE '04_serial_creator (100+)'
                END AS creator_tier
            FROM read_parquet('{data_dir}/tokens.parquet')
            WHERE NOT COALESCE(top10_pct_suspect, FALSE)
        )
        SELECT
            creator_tier AS "Creator Past Tokens Tier",
            COUNT(*) AS n_tokens,
            SUM(CASE WHEN is_graduated THEN 1 ELSE 0 END) AS n_graduated,
            ROUND(100.0 * SUM(CASE WHEN is_graduated THEN 1 ELSE 0 END) / COUNT(*), 3) AS graduation_rate_pct
        FROM tiered
        GROUP BY 1
        ORDER BY 1
    """
    res = con.execute(query).fetchdf()
    print(res.to_string(index=False))
    print("\n[KEY FINDING] Creators with previous project history display dramatically higher graduation odds.")


# ==============================================================================
# 5. METRIC B: HOLDER CONCENTRATION VS RUG RISK ANALYSIS
# ==============================================================================
def metric_concentration_vs_outcomes(con: duckdb.DuckDBPyConnection, data_dir: str) -> None:
    """
    Analyzes holder Gini index (`initial_gini`) vs post-graduation rug risk (`postgard_outcomes`).
    Filters out suspect concentration records for statistical validity.
    """
    print_banner(5, "Metric B: Holder Concentration (Gini) vs Post-Graduation Rug Risk")

    query = f"""
        WITH clean_tokens AS (
            SELECT 
                mint,
                initial_gini,
                initial_top10_pct
            FROM read_parquet('{data_dir}/tokens.parquet')
            WHERE NOT COALESCE(top10_pct_suspect, FALSE)
              AND initial_gini IS NOT NULL
        ),
        outcomes AS (
            SELECT 
                t.mint,
                t.initial_gini,
                o.outcome_label,
                o.rug_detected,
                CASE WHEN o.rug_detected THEN 1 ELSE 0 END AS is_rug
            FROM clean_tokens t
            INNER JOIN read_parquet('{data_dir}/postgard_outcomes.parquet') o ON t.mint = o.mint
        ),
        bucketed AS (
            SELECT 
                NTILE(5) OVER (ORDER BY initial_gini) AS gini_quintile,
                initial_gini,
                is_rug
            FROM outcomes
        )
        SELECT 
            gini_quintile AS "Gini Quintile",
            ROUND(MIN(initial_gini), 3) AS min_gini,
            ROUND(MAX(initial_gini), 3) AS max_gini,
            COUNT(*) AS n_graduated_tokens,
            SUM(is_rug) AS n_rugs,
            ROUND(100.0 * SUM(is_rug) / COUNT(*), 2) AS rug_rate_pct
        FROM bucketed
        GROUP BY 1
        ORDER BY 1
    """
    res = con.execute(query).fetchdf()
    print(res.to_string(index=False))
    print("\n[KEY FINDING] High holder inequality (Gini > 0.75) strongly predicts post-graduation rugging.")


# ==============================================================================
# 6. MICROSTRUCTURE: CLEAN TRADE-GRID FEATURE RECONSTRUCTION
# ==============================================================================
def compute_trade_microstructure_sample(con: duckdb.DuckDBPyConnection, data_dir: str) -> None:
    """
    Demonstrates building time-windowed trade flow metrics (T+3m, T+6m) directly
    from sharded `trades/*.parquet` files to bypass snapshot heartbeat duplicates.
    """
    print_banner(6, "Trade Microstructure Flow (Derived directly from trades/*.parquet)")

    query = f"""
        WITH filtered_trades AS (
            SELECT 
                mint,
                seconds_since_launch,
                is_buy,
                sol_amount
            FROM read_parquet('{data_dir}/trades/*.parquet')
            WHERE user_wallet != '{SYSTEM_PROGRAM_WALLET}'
              AND seconds_since_launch <= 360  -- First 6 minutes post-launch
        ),
        aggregated AS (
            SELECT 
                mint,
                COUNT(*) AS trades_first_6m,
                SUM(CASE WHEN seconds_since_launch <= 180 AND is_buy THEN sol_amount ELSE 0 END) AS buy_vol_3m,
                SUM(CASE WHEN seconds_since_launch <= 180 AND NOT is_buy THEN sol_amount ELSE 0 END) AS sell_vol_3m,
                SUM(CASE WHEN is_buy THEN sol_amount ELSE 0 END) AS buy_vol_6m,
                SUM(sol_amount) AS total_vol_6m
            FROM filtered_trades
            GROUP BY mint
        )
        SELECT 
            t.mint,
            t.symbol,
            a.trades_first_6m,
            ROUND(a.buy_vol_3m, 2) AS buy_vol_3m_sol,
            ROUND(a.sell_vol_3m, 2) AS sell_vol_3m_sol,
            ROUND(a.buy_vol_6m / NULLIF(a.total_vol_6m, 0), 3) AS buy_pressure_6m
        FROM aggregated a
        JOIN read_parquet('{data_dir}/tokens.parquet') t ON a.mint = t.mint
        WHERE NOT COALESCE(t.top10_pct_suspect, FALSE)
        ORDER BY a.total_vol_6m DESC
        LIMIT 5
    """
    res = con.execute(query).fetchdf()
    print(res.to_string(index=False))
    print("\n[METHODOLOGY] Constructing signals directly from trades avoids snapshot heartbeat duplication.")


# ==============================================================================
# 7. POST-GRADUATION DEX OUTCOME & LIQUIDITY ANALYSIS
# ==============================================================================
def analyze_postgrad_performance(con: duckdb.DuckDBPyConnection, data_dir: str) -> None:
    """
    Analyzes DEX survival classifications (`postgard_outcomes.parquet`) and liquidity 
    decay trajectories (`postgard_snapshots.parquet`).
    """
    print_banner(7, "Post-Graduation Outcomes & DEX Liquidity Retention")

    # Outcome Label Breakdown
    print("--> Categorical Survival Breakdown across Graduated Population:")
    query_outcomes = f"""
        SELECT 
            outcome_label AS "Outcome Label",
            COUNT(*) AS n_tokens,
            ROUND(100.0 * COUNT(*) / SUM(COUNT(*)) OVER(), 2) AS pct_of_graduated,
            ROUND(AVG(price_change_24h_pct), 2) AS avg_24h_price_change_pct,
            SUM(CASE WHEN still_liquid_at_24h THEN 1 ELSE 0 END) AS liquid_at_24h_count
        FROM read_parquet('{data_dir}/postgard_outcomes.parquet')
        GROUP BY outcome_label
        ORDER BY n_tokens DESC
    """
    res_outcomes = con.execute(query_outcomes).fetchdf()
    print(res_outcomes.to_string(index=False))

    # Post-Grad Snapshots Liquidity Sample Check
    print("\n--> DEX Liquidity & Volume Time-Series Sample (postgard_snapshots.parquet):")
    query_snapshots = f"""
        SELECT 
            mint,
            seconds_since_graduation,
            ROUND(price_usd, 6) AS price_usd,
            ROUND(liquidity_usd, 2) AS liquidity_usd,
            ROUND(volume_1h, 2) AS vol_1h_usd,
            buy_pressure_1h
        FROM read_parquet('{data_dir}/postgard_snapshots.parquet')
        WHERE liquidity_usd IS NOT NULL
        ORDER BY snapshot_time DESC
        LIMIT 5
    """
    res_snapshots = con.execute(query_snapshots).fetchdf()
    print(res_snapshots.to_string(index=False))


# ==============================================================================
# 8. WALLET ANALYTICS & HIGH-FREQUENCY TRADER PROFILING
# ==============================================================================
def analyze_wallet_profiles(con: duckdb.DuckDBPyConnection, data_dir: str) -> None:
    """
    Profiles trader behaviors and volume distributions across 1.02M unique addresses 
    logged in `wallet_stats.parquet`.
    """
    print_banner(8, "Wallet Stats & High-Frequency Trader Distribution")

    query = f"""
        WITH wallet_tiers AS (
            SELECT 
                wallet,
                tokens_traded,
                graduated_tokens_traded,
                total_trades,
                total_buy_volume_sol + total_sell_volume_sol AS total_volume_sol,
                CASE 
                    WHEN total_trades >= 1000 THEN '01_bot_or_infra (1000+ trades)'
                    WHEN total_trades >= 100 THEN '02_heavy_trader (100-999)'
                    WHEN total_trades >= 10 THEN '03_regular_trader (10-99)'
                    ELSE '04_casual_trader (1-9)'
                END AS trader_tier
            FROM read_parquet('{data_dir}/wallet_stats.parquet')
        )
        SELECT 
            trader_tier AS "Trader Activity Tier",
            COUNT(*) AS n_wallets,
            ROUND(100.0 * COUNT(*) / SUM(COUNT(*)) OVER(), 2) AS pct_wallets,
            ROUND(AVG(tokens_traded), 1) AS avg_tokens_traded,
            ROUND(SUM(total_volume_sol), 1) AS tier_total_volume_sol
        FROM wallet_tiers
        GROUP BY 1
        ORDER BY 1
    """
    res = con.execute(query).fetchdf()
    print(res.to_string(index=False))
    print("\n[INSIGHT] A small percentage of automated bot wallets drive a major share of execution frequency.")


# ==============================================================================
# 9. MIGRATION EVENT LOGS & RAYDIUM TIMING ANALYSIS
# ==============================================================================
def analyze_migrations_performance(con: duckdb.DuckDBPyConnection, data_dir: str) -> None:
    """
    Inspects Raydium migration timing patterns logged in `migrations.parquet`.
    Computes summary distribution statistics for bonding curve graduation speed.
    """
    print_banner(9, "Raydium Migration Event Timing & Velocity Distribution")

    query = f"""
        SELECT 
            COUNT(*) AS total_migrations,
            ROUND(AVG(seconds_to_graduation), 1) AS avg_seconds_to_grad,
            ROUND(MEDIAN(seconds_to_graduation), 1) AS median_seconds_to_grad,
            ROUND(QUANTILE_CONT(seconds_to_graduation, 0.10), 1) AS p10_seconds,
            ROUND(QUANTILE_CONT(seconds_to_graduation, 0.90), 1) AS p90_seconds,
            MIN(seconds_to_graduation) AS fastest_grad_seconds,
            MAX(seconds_to_graduation) AS slowest_grad_seconds
        FROM read_parquet('{data_dir}/migrations.parquet')
    """
    res = con.execute(query).fetchdf()
    print(res.to_string(index=False))
    print("\n[INSIGHT] Graduation speed ranges from hyper-fast sniped launches to multi-day gradual curves.")


# ==============================================================================
# 10. SUMMARY & PIPELINE DATA-QUALITY CHECKLIST
# ==============================================================================
def print_pipeline_summary() -> None:
    """Prints a checklist of required data quality rules before building models."""
    print_banner(10, "Summary & Data Quality Checklist for Machine Learning")

    checklist = [
        ("1. System Program Exclusion", "ALWAYS filter out user_wallet = 'BwWK17cbHxwWBKZkUYvzxLcNQ1YVyaFezduWbtm2de6s'"),
        ("2. Suspect Row Exclusion", "ALWAYS exclude rows where COALESCE(top10_pct_suspect, FALSE) is True"),
        ("3. Heartbeat Duplicate Prevention", "Rebuild time-series signals directly from trades/*.parquet shards"),
        ("4. Structural Missingness", "Treat initial_gini NULLs as structural (<3 holders), not random missingness"),
        ("5. Walk-Forward CV Splits", "Use time-based walk-forward splits to account for non-stationary base rates"),
    ]

    for item, rule in checklist:
        print(f"  [CHECK] {item:<32} -> {rule}")
    print("\nSee README.md for full model feature engineering guidelines and replication benchmarks.")


# ==============================================================================
# MAIN CLI DRIVER
# ==============================================================================
def main() -> None:
    parser = argparse.ArgumentParser(
        description="Expanded Quickstart & Quality Audit Script for Pump.fun Memecoin Dataset"
    )
    parser.add_argument(
        "--data-dir", 
        required=True, 
        help="Path to root directory containing parquet files and trades/ subfolder"
    )
    parser.add_argument(
        "--threads", 
        type=int, 
        default=4, 
        help="Number of CPU threads for DuckDB engine (default: 4)"
    )
    parser.add_argument(
        "--memory-limit", 
        type=str, 
        default="4GB", 
        help="DuckDB memory ceiling, e.g. '4GB', '8GB' (default: 4GB)"
    )

    args = parser.parse_args()
    data_dir = args.data_dir.rstrip("/")

    # Directory existence check
    if not os.path.exists(data_dir):
        print(f"[ERROR] Directory '{data_dir}' does not exist. Please check --data-dir path.")
        sys.exit(1)

    t_start = time.time()
    print(f"Initializing DuckDB Engine (Threads: {args.threads}, Memory Limit: {args.memory_limit})...")
    con = configure_duckdb(threads=args.threads, memory_limit=args.memory_limit)

    # Run analytical sections sequentially
    audit_corpus_structure(con, data_dir)
    audit_tokens_quality(con, data_dir)
    audit_trades_quality(con, data_dir)
    metric_creator_experience(con, data_dir)
    metric_concentration_vs_outcomes(con, data_dir)
    compute_trade_microstructure_sample(con, data_dir)
    analyze_postgrad_performance(con, data_dir)
    analyze_wallet_profiles(con, data_dir)
    analyze_migrations_performance(con, data_dir)
    print_pipeline_summary()

    t_elapsed = time.time() - t_start
    print("\n" + "=" * 80)
    print(f"SUCCESS: ALL 10 ANALYTICAL SECTIONS COMPLETED IN {t_elapsed:.2f} SECONDS.")
    print("=" * 80 + "\n")


if __name__ == "__main__":
    main()