Spaces:
Sleeping
Sleeping
Delete app.py
Browse files123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703"""app.py β HuggingFace Spaces entry pointβββββββββββββββββββββββββββββββββββββββββββββββββββββQuant Knowledge Extractor + Backtesting Engine.
You upload PDFs here. Everything else is automatic: 1. PDF text extraction (+ OCR for scanned books) 2. Claude AI extracts strategies, formulas, systems 3. 3-layer deduplication + layered variant merging 4. Markdown files pushed to your HF dataset 5. Strategies compiled to Python signal functions 6. Walk-forward backtested on your tick data 7. Optimal MT5 .set files + Julia configs pushed to HF
Zero local dependencies. Everything runs in this Space."""
import ioimport osimport jsonimport zipfileimport tempfileimport shutilfrom pathlib import Pathfrom datetime import datetime
import gradio as grfrom loguru import logger
import utils.config as cfgimport utils.hf_io as hffrom pipeline.pdf_processor import PDFProcessorfrom pipeline.extractor import AIExtractor, Deduplicatorfrom pipeline.backtester import ( StrategyCompiler, WalkForwardOptimizer, build_markdown_report, build_optimal_json, build_mt5_set, build_julia_config, slugify,)from pipeline.exporter import ( strategy_markdown, formula_markdown, system_markdown, backtest_index_markdown,)
# ββ Lazy-loaded singletons ββββββββββββββββββββββββββββ_kb: dict | None = None
def get_kb() -> dict: global _kb if _kb is None: _kb = hf.kb_load() return _kb
def refresh_kb(): global _kb _kb = hf.kb_load()
# βββββββββββββββββββββββββββββββββββββββββββββββββββ# TAB 1 β UPLOAD & EXTRACT# βββββββββββββββββββββββββββββββββββββββββββββββββββ
def run_extraction(pdf_files, progress=gr.Progress(track_tqdm=True)): """Full extraction pipeline for uploaded PDFs.""" if not pdf_files: return "β οΈ No PDFs uploaded.", "" if not cfg.ANTHROPIC_API_KEY: return "β ANTHROPIC_API_KEY secret not set in Space settings.", "" if not cfg.HF_DATASET_REPO: return "β HF_DATASET_REPO secret not set in Space settings.", ""
pdf_processor = PDFProcessor() ai_extractor = AIExtractor() dedup = Deduplicator() kb = get_kb()
log, total_stats = [], { "strategies": {"added":0,"merged":0,"skipped":0}, "formulas": {"added":0,"merged":0,"skipped":0}, "systems": {"added":0,"merged":0,"skipped":0}, } hf_files = [] # Collect (remote_path, bytes) for batch push
for i, pdf_file in enumerate(pdf_files): pdf_path = Path(pdf_file.name) progress(i / len(pdf_files), desc=f"Processing {pdf_path.name}") log.append(f"\nπ [{i+1}/{len(pdf_files)}] {pdf_path.name}")
# 1. Extract chunks try: chunks = list(pdf_processor.process(pdf_path)) log.append(f" β {len(chunks)} chunks extracted") except Exception as e: log.append(f" β Extraction failed: {e}") continue
# 2. AI extraction + dedup book_stats = {k: {"added":0,"merged":0,"skipped":0} for k in ("strategies","formulas","systems")} for chunk in chunks: extracted = ai_extractor.extract(chunk) stats = dedup.process(extracted, kb) for kind in ("strategies","formulas","systems"): for action in ("added","merged","skipped"): book_stats[kind][action] += stats[kind][action] total_stats[kind][action] += stats[kind][action]
s_add = book_stats["strategies"]["added"] f_add = book_stats["formulas"]["added"] log.append(f" β New: {s_add} strategies, {f_add} formulas")
# 3. Upload PDF to HF if cfg.HF_TOKEN: hf.pdf_upload(pdf_path)
# 4. Generate markdown for every item in KB + queue for HF push for cid, rec in kb["strategies"].items(): md = strategy_markdown(rec) sl = slugify(rec.get("name","")) hf_files.append((f"extracted/strategies/{sl}.md", md.encode()))
for cid, rec in kb["formulas"].items(): md = formula_markdown(rec) sl = slugify(rec.get("name","")) hf_files.append((f"extracted/formulas/{sl}.md", md.encode()))
for cid, rec in kb["systems"].items(): md = system_markdown(rec) sl = slugify(rec.get("name","")) hf_files.append((f"extracted/systems/{sl}.md", md.encode()))
# 5. Save KB + push everything progress(0.9, desc="Saving to HuggingFace...") hf.kb_save(kb) if hf_files and cfg.HF_TOKEN: pushed = hf.push_batch(hf_files, "Update extracted knowledge") log.append(f"\nβοΈ Pushed {pushed} files to HuggingFace") refresh_kb()
counts = {k: len(kb[k]) for k in kb} summary = f"""β
Extraction Complete
PDFs processed: {len(pdf_files)}
Strategies β added: {total_stats['strategies']['added']} merged: {total_stats['strategies']['merged']} skipped: {total_stats['strategies']['skipped']}Formulas β added: {total_stats['formulas']['added']} merged: {total_stats['formulas']['merged']} skipped: {total_stats['formulas']['skipped']}Systems β added: {total_stats['systems']['added']} merged: {total_stats['systems']['merged']} skipped: {total_stats['systems']['skipped']}
KNOWLEDGE BASE TOTALS Unique strategies : {counts['strategies']} Unique formulas : {counts['formulas']} Complete systems : {counts['systems']}
Tokens used this run: {ai_extractor.tokens_used:,}""".strip() return summary, "\n".join(log[-40:])
# βββββββββββββββββββββββββββββββββββββββββββββββββββ# TAB 2 β BROWSE KNOWLEDGE BASE# βββββββββββββββββββββββββββββββββββββββββββββββββββ
def search_strategies(query, category): kb = get_kb() items = list(kb["strategies"].values()) if category and category != "All": items = [x for x in items if x.get("category") == category] if query: q = query.lower() items = [x for x in items if q in x.get("name","").lower() or q in x.get("description","").lower()] rows = [[ x.get("name","")[:50], x.get("category",""), x.get("description","")[:100], ", ".join(x.get("sources",[]))[:40], len(x.get("layers",[])), ] for x in items[:100]] return rows, f"{len(items)} strategies"
def search_formulas(query): kb = get_kb() items = list(kb["formulas"].values()) if query: q = query.lower() items = [x for x in items if q in x.get("name","").lower() or q in x.get("purpose","").lower()] return [[ x.get("name","")[:50], x.get("category",""), x.get("purpose","")[:80], "β
" if x.get("latex") else "β", ", ".join(x.get("sources",[]))[:40], ] for x in items[:100]]
def download_strategy_md(name): kb = get_kb() for rec in kb["strategies"].values(): if rec.get("name","").lower() == name.strip().lower(): md = strategy_markdown(rec) tmp = Path(tempfile.mktemp(suffix=".md")) tmp.write_text(md, encoding="utf-8") return str(tmp) return None
def download_all_strategies_zip(category): kb = get_kb() items = list(kb["strategies"].values()) if category and category != "All": items = [x for x in items if x.get("category") == category] tmp = tempfile.mktemp(suffix=".zip") with zipfile.ZipFile(tmp, "w", zipfile.ZIP_DEFLATED) as zf: for rec in items: md = strategy_markdown(rec) zf.writestr(f"{slugify(rec.get('name','unknown'))}.md", md) return tmp
def download_all_formulas_zip(): kb = get_kb() tmp = tempfile.mktemp(suffix=".zip") with zipfile.ZipFile(tmp, "w", zipfile.ZIP_DEFLATED) as zf: for rec in kb["formulas"].values(): md = formula_markdown(rec) zf.writestr(f"{slugify(rec.get('name','unknown'))}.md", md) return tmp
# βββββββββββββββββββββββββββββββββββββββββββββββββββ# TAB 3 β BACKTEST# βββββββββββββββββββββββββββββββββββββββββββββββββββ
def load_symbols(): syms = hf.tick_list_symbols() return gr.update(choices=syms, value=syms[:3] if len(syms) >= 3 else syms)
def run_backtests( selected_symbols, selected_timeframes, strategy_filter, max_strategies, viable_only_push, progress=gr.Progress(track_tqdm=True),): if not cfg.HF_TICK_REPO: return "β HF_TICK_REPO secret not set.", "" if not cfg.ANTHROPIC_API_KEY: return "β ANTHROPIC_API_KEY not set.", ""
kb = get_kb() strategies = list(kb["strategies"].values())
if strategy_filter: strategies = [s for s in strategies if strategy_filter.lower() in s.get("name","").lower()] if max_strategies > 0: strategies = strategies[:int(max_strategies)] if not strategies: return "β οΈ No strategies in KB. Run extraction first.", ""
symbols = selected_symbols or hf.tick_list_symbols()[:2] timeframes = selected_timeframes or ["1h"]
compiler = StrategyCompiler() optimizer = WalkForwardOptimizer() log, all_results, viable_count = [], [], 0 total = len(strategies) * len(symbols) * len(timeframes) done = 0
for si, rec in enumerate(strategies): name = rec.get("name","?") progress(si / len(strategies), desc=f"[{si+1}/{len(strategies)}] {name[:35]}")
exe = compiler.compile(rec) if not exe.is_valid: log.append(f"β Compile: {name[:40]} β {exe.error[:50]}") continue log.append(f"β
Compiled: {name[:40]}")
for sym in symbols: df_cache = {} for tf in timeframes: progress((done/max(total,1)), desc=f"{name[:25]} | {sym} {tf}") df = hf.tick_load(sym, tf) if df is None or len(df) < 200: log.append(f" β οΈ {sym} {tf}: no data or too short") done += 1; continue
opt = optimizer.optimize(exe, sym, tf, df) all_results.append(opt)
# Build output files report_md = build_markdown_report(opt, rec) optimal_js = build_optimal_json(opt, rec) mt5_set = build_mt5_set(opt, rec) julia_cfg = build_julia_config(opt)
if cfg.HF_TOKEN and cfg.HF_DATASET_REPO: if not viable_only_push or opt.is_viable: hf.push_backtest_result( opt.strategy, opt.symbol, opt.timeframe, report_md, optimal_js, mt5_set, julia_cfg, )
status = "β
" if opt.is_viable else "β" log.append( f" {status} {sym} {tf}: Sharpe={opt.oos_sharpe_mean:.2f} " f"DD={opt.oos_max_dd_mean:.1f}% Score={opt.robustness_score:.0f}" ) if opt.is_viable: viable_count += 1 done += 1
# Build + push master index if all_results and cfg.HF_TOKEN: idx_md = backtest_index_markdown(all_results) idx_json = { "generated": datetime.now().isoformat(), "total_strategies": len(all_results), "viable_count": viable_count, "strategies": [r.to_dict() for r in all_results], } hf.push_backtest_index(idx_md, idx_json) log.append(f"\nβοΈ Index pushed to HuggingFace")
summary = f"""π Backtesting Complete
Strategies compiled: {len([r for r in all_results])+len([l for l in log if 'β Compile' in l])}Combinations tested: {done}Viable strategies: {viable_count}Pass rate: {viable_count/max(done,1)*100:.1f}%
Results on HuggingFace: {cfg.HF_DATASET_REPO}/optimal_sets/BACKTEST_INDEX.md""".strip()
return summary, "\n".join(log[-60:])
# βββββββββββββββββββββββββββββββββββββββββββββββββββ# TAB 4 β RESULTS# βββββββββββββββββββββββββββββββββββββββββββββββββββ
def load_results(): data = hf.fetch_backtest_index() if not data: return [], "No results yet β run backtests first." strategies = data.get("strategies", []) viable = sorted( [s for s in strategies if s.get("is_viable")], key=lambda x: x.get("oos_sharpe_mean", 0), reverse=True ) rows = [[ s.get("strategy","")[:45], s.get("symbol",""), s.get("timeframe",""), f'{s.get("oos_sharpe_mean",0):.2f}', f'{s.get("oos_max_dd_mean",0):.1f}%', f'{s.get("oos_win_rate_mean",0):.1f}%', f'{s.get("oos_pf_mean",0):.2f}', f'{s.get("robustness_score",0):.0f}', ] for s in viable] count = (f"β
{len(viable)} viable / {len(strategies)} total tested | " f"Generated: {data.get('generated','')[:16]}") return rows, count
def download_result_file(strategy_name: str, symbol: str, timeframe: str, file_type: str): sl = slugify(strategy_name) sym = symbol.upper().strip() tf = timeframe.strip() prefix = f"{sl}_{sym}_{tf}" ext_map = { "MT5 .set file": f"optimal_sets/{prefix}.set", "Optimal JSON": f"optimal_sets/{prefix}_optimal.json", "Julia config": f"optimal_sets/{prefix}_config.jl", "Full report": f"backtests/{sl}/{prefix}_report.md", } remote = ext_map.get(file_type, "") if not remote: return None data = hf.fetch_file(remote) if not data: return None suffix = Path(remote).suffix tmp = tempfile.mktemp(suffix=suffix) Path(tmp).write_bytes(data) return tmp
def download_all_sets_zip(): """Download all MT5 .set files as a ZIP.""" data = hf.fetch_backtest_index() if not data: return None tmp = tempfile.mktemp(suffix=".zip") with zipfile.ZipFile(tmp, "w", zipfile.ZIP_DEFLATED) as zf: for s in data.get("strategies", []): if not s.get("is_viable"): continue sl = slugify(s["strategy"]) sym = s["symbol"] tf = s["timeframe"] remote = f"optimal_sets/{sl}_{sym}_{tf}.set" content = hf.fetch_file(remote) if content: zf.writestr(f"{sl}_{sym}_{tf}.set", content) return tmp
def download_all_json_zip(): data = hf.fetch_backtest_index() if not data: return None tmp = tempfile.mktemp(suffix=".zip") with zipfile.ZipFile(tmp, "w", zipfile.ZIP_DEFLATED) as zf: for s in data.get("strategies", []): if not s.get("is_viable"): continue sl = slugify(s["strategy"]) sym = s["symbol"] tf = s["timeframe"] remote = f"optimal_sets/{sl}_{sym}_{tf}_optimal.json" content = hf.fetch_file(remote) if content: zf.writestr(f"{sl}_{sym}_{tf}_optimal.json", content) return tmp
# βββββββββββββββββββββββββββββββββββββββββββββββββββ# TAB 5 β SETUP GUIDE# βββββββββββββββββββββββββββββββββββββββββββββββββββ
def check_config() -> str: issues, ok = [], [] checks = [ ("ANTHROPIC_API_KEY", cfg.ANTHROPIC_API_KEY, "Claude AI extraction + compilation"), ("HF_TOKEN", cfg.HF_TOKEN, "HuggingFace read/write access"), ("HF_DATASET_REPO", cfg.HF_DATASET_REPO, "Where results are saved"), ("HF_TICK_REPO", cfg.HF_TICK_REPO, "Your tick data source"), ] for name, val, desc in checks: if val: ok.append(f"β
`{name}` β {desc}") else: issues.append(f"β `{name}` missing β {desc}")
symbols = hf.tick_list_symbols() if cfg.HF_TICK_REPO else [] kb = get_kb()
lines = ["## Configuration Status", ""] lines += ok + issues lines += [ "", "## Data Status", "", f"- Tick symbols available: **{len(symbols)}** β {', '.join(symbols[:8])}{'...' if len(symbols)>8 else ''}", f"- Strategies in KB: **{len(kb['strategies'])}**", f"- Formulas in KB: **{len(kb['formulas'])}**", f"- Systems in KB: **{len(kb['systems'])}**", "", "## Backtest Settings", "", f"- WF Windows: `{cfg.WF_WINDOWS}`", f"- IS Ratio: `{cfg.WF_IS_RATIO}`", f"- Min Trades (OOS): `{cfg.MIN_TRADES}`", f"- Min Sharpe: `{cfg.MIN_SHARPE}`", f"- Commission: `{cfg.COMMISSION_PCT*100:.3f}%`", f"- Risk per trade: `{cfg.RISK_PER_TRADE*100:.1f}%`", f"- Timeframes: `{', '.join(cfg.BACKTEST_TIMEFRAMES)}`", ] if issues: lines += ["", "## β οΈ Missing Secrets", "Go to **Settings β Variables and Secrets** in your Space."] return "\n".join(lines)
# βββββββββββββββββββββββββββββββββββββββββββββββββββ# BUILD GRADIO APP# βββββββββββββββββββββββββββββββββββββββββββββββββββ
CATS = ["All"] + cfg.CATEGORIES
with gr.Blocks( title="Quant Knowledge Extractor", theme=gr.themes.Base(primary_hue="emerald", neutral_hue="slate"), css=""" .gr-button-primary { background: #10b981 !important; } h1 { color: #10b981; } .status-box { font-family: monospace; font-size: 0.85em; } """,) as demo:
gr.HTML(""" <div style="text-align:center;padding:1.2em 0 0.3em"> <h1 style="font-size:2em;color:#10b981;margin:0">π Quant Knowledge Extractor</h1> <p style="color:#94a3b8;margin:.4em 0 0"> Upload PDFs β Extract Strategies β Backtest on Tick Data β Download MT5 .set Files </p> </div> """)
with gr.Tabs():
# ββ Tab 1: Upload & Extract βββββββββββββββββββ with gr.Tab("π€ Upload & Extract"): gr.Markdown( "### Step 1 β Upload your algorithmic trading ebooks\n" "Supports text PDFs and scanned books (OCR applied automatically)." ) with gr.Row(): with gr.Column(scale=2): pdf_input = gr.File( label="Drop PDFs here", file_count="multiple", file_types=[".pdf"], ) extract_btn = gr.Button( "π Extract All Knowledge", variant="primary", size="lg", ) with gr.Column(scale=1): extract_summary = gr.Textbox( label="Result", lines=14, interactive=False, elem_classes=["status-box"], ) extract_log = gr.Textbox( label="Live Log", lines=8, interactive=False, elem_classes=["status-box"], ) extract_btn.click( fn=run_extraction, inputs=[pdf_input], outputs=[extract_summary, extract_log], )
# ββ Tab 2: Browse KB ββββββββββββββββββββββββββ with gr.Tab("π Knowledge Base"): with gr.Tabs():
with gr.Tab("π Strategies"): with gr.Row(): s_query = gr.Textbox(label="Search", placeholder="RSI, breakout, Kellyβ¦") s_cat = gr.Dropdown(choices=CATS, value="All", label="Category") s_btn = gr.Button("π Search", variant="primary") s_table = gr.Dataframe( headers=["Name","Category","Description","Sources","Variants"], datatype=["str","str","str","str","number"], interactive=False, label="Strategies", ) s_count = gr.Markdown("") with gr.Row(): s_name_in = gr.Textbox(label="Strategy name (exact) to download") s_dl_btn = gr.Button("β¬οΈ Download Markdown") s_dl_file = gr.File(label="") with gr.Row(): s_zip_btn = gr.Button("π¦ Download Category ZIP") s_zip_file = gr.File(label="") s_btn.click(fn=search_strategies, inputs=[s_query,s_cat], outputs=[s_table,s_count]) s_dl_btn.click(fn=download_strategy_md, inputs=[s_name_in], outputs=[s_dl_file]) s_zip_btn.click(fn=download_all_strategies_zip, inputs=[s_cat], outputs=[s_zip_file])
with gr.Tab("β Formulas"): with gr.Row(): f_query = gr.Textbox(label="Search formulas", placeholder="Sharpe, Kelly, ATRβ¦") f_btn = gr.Button("π Search", variant="primary") f_table = gr.Dataframe( headers=["Name","Category","Purpose","LaTeX","Sources"], datatype=["str","str","str","str","str"], interactive=False, ) f_dl_btn = gr.Button("π¦ Download All Formulas ZIP") f_dl_file = gr.File(label="") f_btn.click(fn=search_formulas, inputs=[f_query], outputs=[f_table]) f_dl_btn.click(fn=download_all_formulas_zip, outputs=[f_dl_file])
# ββ Tab 3: Backtest βββββββββββββββββββββββββββ with gr.Tab("π¬ Backtest"): gr.Markdown( "### Step 2 β Walk-Forward Backtest All Extracted Strategies\n" "Compiles each strategy β grid-searches parameters β validates out-of-sample " "β pushes MT5 `.set` files to your HuggingFace dataset." ) with gr.Row(): with gr.Column(scale=2): with gr.Row(): bt_load_syms = gr.Button("π Load Symbols from HF Tick Repo") bt_symbols = gr.CheckboxGroup( label="Symbols to test", choices=[], value=[], info="Load symbols first, then select which to test", ) bt_timeframes = gr.CheckboxGroup( label="Timeframes", choices=["1m","5m","15m","30m","1h","4h","1d"], value=["1h","4h"], ) bt_filter = gr.Textbox( label="Strategy name filter (optional)", placeholder="Leave blank to test all strategies", ) bt_max = gr.Slider( 0, 500, value=0, step=10, label="Max strategies to test (0 = all)", ) bt_viable_only = gr.Checkbox( label="Push only VIABLE strategies to HuggingFace", value=True, ) bt_run = gr.Button( "π Run Walk-Forward Backtests", variant="primary", size="lg", ) with gr.Column(scale=1): bt_summary = gr.Textbox( label="Summary", lines=12, interactive=False, elem_classes=["status-box"], ) bt_log = gr.Textbox( label="Backtest Log", lines=12, interactive=False, elem_classes=["status-box"], ) bt_load_syms.click(fn=load_symbols, outputs=[bt_symbols]) bt_run.click( fn=run_backtests, inputs=[bt_symbols, bt_timeframes, bt_filter, bt_max, bt_viable_only], outputs=[bt_summary, bt_log], )
# ββ Tab 4: Results ββββββββββββββββββββββββββββ with gr.Tab("π Results"): gr.Markdown( "### Viable Strategies β Download MT5 `.set` Files & Configs\n" "Only strategies that passed walk-forward validation appear here." ) res_refresh = gr.Button("π Refresh from HuggingFace", variant="primary") res_table = gr.Dataframe( headers=["Strategy","Symbol","TF","Sharpe","Max DD","Win%","PF","Score"], datatype=["str","str","str","str","str","str","str","str"], interactive=False, label="Viable Strategies (sorted by OOS Sharpe)", ) res_count = gr.Markdown("")
gr.Markdown("#### Download a Specific Strategy File") with gr.Row(): r_strategy = gr.Textbox(label="Strategy name", placeholder="Copy from table above") r_symbol = gr.Textbox(label="Symbol", placeholder="EURUSD") r_timeframe = gr.Textbox(label="Timeframe", placeholder="1h") r_filetype = gr.Dropdown( choices=["MT5 .set file","Optimal JSON","Julia config","Full report"], value="MT5 .set file", label="File type", ) r_dl_btn = gr.Button("β¬οΈ Download", variant="primary") r_dl_file = gr.File(label="Download")
gr.Markdown("#### Batch Downloads (all viable strategies)") with gr.Row(): all_sets_btn = gr.Button("π― All MT5 .set Files (ZIP)") all_sets_file = gr.File(label="MT5 Sets") all_json_btn = gr.Button("π All Optimal JSON (ZIP)") all_json_file = gr.File(label="Optimal JSON")
res_refresh.click(fn=load_results, outputs=[res_table, res_count]) r_dl_btn.click( fn=download_result_file, inputs=[r_strategy, r_symbol, r_timeframe, r_filetype], outputs=[r_dl_file], ) all_sets_btn.click(fn=download_all_sets_zip, outputs=[all_sets_file]) all_json_btn.click(fn=download_all_json_zip, outputs=[all_json_file]) demo.load(fn=load_results, outputs=[res_table, res_count])
# ββ Tab 5: Setup ββββββββββββββββββββββββββββββ with gr.Tab("βοΈ Setup & Status"): gr.Markdown( "### Configuration & Health Check\n\n" "**First time?** Set these Secrets in your Space:\n\n" "> Space Settings β Variables and Secrets β New Secret\n\n" "| Secret | Description |\n" "|--------|-------------|\n" "| `ANTHROPIC_API_KEY` | Claude API key (claude.ai/settings) |\n" "| `HF_TOKEN` | HuggingFace write token (hf.co/settings/tokens) |\n" "| `HF_DATASET_REPO` | `your-username/quant-knowledge-base` |\n" "| `HF_TICK_REPO` | `your-username/tick-data` |\n\n" "**Optional tuning:**\n\n" "| Variable | Default | Effect |\n" "|----------|---------|--------|\n" "| `WF_WINDOWS` | `5` | Walk-forward windows |\n" "| `MIN_SHARPE` | `0.5` | Min OOS Sharpe to mark viable |\n" "| `MIN_TRADES` | `30` | Min OOS trades required |\n" "| `COMMISSION_PCT` | `0.0002` | 0.02% per side |\n" "| `BACKTEST_TIMEFRAMES` | `1h,4h,1d` | Timeframes to test |\n" "| `SIMILARITY_THRESHOLD` | `0.85` | Dedup cosine threshold |\n" ) cfg_refresh = gr.Button("π Check Configuration") cfg_status = gr.Markdown(check_config()) cfg_refresh.click(fn=check_config, outputs=[cfg_status])
gr.HTML(""" <div style="text-align:center;padding:1em;color:#475569;font-size:.8em"> Quant Knowledge Extractor Β· Built on HuggingFace Spaces Β· Claude AI </div> """)
# ββ Launch ββββββββββββββββββββββββββββββββββββββββββββif __name__ == "__main__": demo.launch()app.pyDeleted-703