This repository was archived by the owner on Jul 12, 2026. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 24
Expand file tree
/
Copy pathcli.py
More file actions
1932 lines (1564 loc) · 70.5 KB
/
Copy pathcli.py
File metadata and controls
1932 lines (1564 loc) · 70.5 KB
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
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""Main CLI interface for QuantCoder - inspired by Mistral Vibe CLI."""
import click
import logging
import sys
from pathlib import Path
from rich.console import Console
from rich.logging import RichHandler
from rich.panel import Panel
from rich.markdown import Markdown
from .config import Config
from .chat import InteractiveChat
from .tools import (
SearchArticlesTool,
DownloadArticleTool,
SummarizeArticleTool,
GenerateCodeTool,
ValidateCodeTool,
BacktestTool,
)
console = Console()
def setup_logging(verbose: bool = False, config: Config = None):
"""Configure logging with rich handler and rotation.
Uses the new centralized logging system with:
- Log rotation (configurable size and backup count)
- Structured JSON logging (in addition to console output)
- Optional webhook alerting for errors
"""
from quantcoder.logging_config import setup_logging as setup_qc_logging
# Get logging config if available
logging_config = None
if config:
try:
logging_config = config.get_logging_config()
except Exception:
pass # Use defaults if config fails
# Create rich console handler
rich_handler = RichHandler(
rich_tracebacks=True,
console=console,
show_time=True,
show_path=False,
)
rich_handler._custom_formatter = True # Signal to not override formatter
# Setup centralized logging
setup_qc_logging(
verbose=verbose,
config=logging_config,
console_handler=rich_handler,
)
@click.group(invoke_without_command=True)
@click.option('--verbose', '-v', is_flag=True, help='Enable verbose logging')
@click.option('--config', type=click.Path(), help='Path to config file')
@click.option('--prompt', '-p', type=str, help='Run in non-interactive mode with prompt')
@click.pass_context
def main(ctx, verbose, config, prompt):
"""
QuantCoder - AI-powered CLI for generating QuantConnect algorithms.
A conversational interface to transform research articles into trading algorithms.
"""
# Load configuration first so logging can use it
config_path = Path(config) if config else None
cfg = Config.load(config_path)
# Setup logging with config (enables rotation, JSON logs, webhooks)
setup_logging(verbose, cfg)
ctx.ensure_object(dict)
ctx.obj['config'] = cfg
ctx.obj['verbose'] = verbose
# If prompt is provided, run in non-interactive mode
if prompt:
from .chat import ProgrammaticChat
chat = ProgrammaticChat(cfg)
result = chat.process(prompt)
console.print(result)
return
# If no subcommand, launch interactive mode
if ctx.invoked_subcommand is None:
interactive(cfg)
def interactive(config: Config):
"""Launch interactive chat mode."""
banner = (
"[bold cyan]"
" ██████╗ ██╗ ██╗ █████╗ ███╗ ██╗████████╗\n"
" ██╔═══██╗██║ ██║██╔══██╗████╗ ██║╚══██╔══╝\n"
" ██║ ██║██║ ██║███████║██╔██╗ ██║ ██║\n"
" ██║▄▄ ██║██║ ██║██╔══██║██║╚██╗██║ ██║\n"
" ╚██████╔╝╚██████╔╝██║ ██║██║ ╚████║ ██║\n"
" ╚══▀▀═╝ ╚═════╝ ╚═╝ ╚═╝╚═╝ ╚═══╝ ╚═╝\n"
" ██████╗ ██████╗ ██████╗ ███████╗██████╗\n"
" ██╔════╝██╔═══██╗██╔══██╗██╔════╝██╔══██╗\n"
" ██║ ██║ ██║██║ ██║█████╗ ██████╔╝\n"
" ██║ ██║ ██║██║ ██║██╔══╝ ██╔══██╗\n"
" ╚██████╗╚██████╔╝██████╔╝███████╗██║ ██║\n"
" ╚═════╝ ╚═════╝ ╚═════╝ ╚══════╝╚═╝ ╚═╝[/bold cyan]\n"
"\n"
" [dim]v2.0 | Local AI-powered QuantConnect algorithm pipeline[/dim]\n"
" [dim]Type 'help' for commands, 'exit' to quit[/dim]"
)
console.print(Panel(banner, border_style="cyan", padding=(1, 2)))
chat = InteractiveChat(config)
chat.run()
@main.command()
@click.argument('query')
@click.option('--num', default=5, help='Number of results to return')
@click.option('--deep', is_flag=True, help='Use Tavily for semantic deep search (requires TAVILY_API_KEY)')
@click.option('--no-filter', is_flag=True, help='Skip LLM relevance filtering (with --deep)')
@click.pass_context
def search(ctx, query, num, deep, no_filter):
"""
Search for academic articles.
By default uses CrossRef API for keyword search.
With --deep flag, uses Tavily for semantic search + LLM filtering.
Examples:
quantcoder search "algorithmic trading" --num 3
quantcoder search "momentum strategy" --deep
quantcoder search "mean reversion" --deep --num 10
"""
config = ctx.obj['config']
if deep:
# Use Tavily deep search
from .tools import DeepSearchTool
tool = DeepSearchTool(config)
with console.status(f"Deep searching for '{query}'..."):
result = tool.execute(
query=query,
max_results=num,
filter_relevance=not no_filter,
)
if result.success:
console.print(f"[green]✓[/green] {result.message}\n")
for idx, article in enumerate(result.data, 1):
score = article.get('relevance_score', 0)
score_color = "green" if score > 0.7 else "yellow" if score > 0.5 else "dim"
published = f" ({article['published']})" if article.get('published') else ""
console.print(
f" [cyan]{idx}.[/cyan] {article['title']}\n"
f" [{score_color}]Score: {score:.2f}[/{score_color}]{published}\n"
f" [dim]{article['URL'][:60]}...[/dim]"
)
console.print(f"\n[dim]Use 'quantcoder download <ID>' to get articles[/dim]")
else:
console.print(f"[red]✗[/red] {result.error}")
else:
# Use arXiv search (default, open-access)
tool = SearchArticlesTool(config)
with console.status(f"Searching arXiv for '{query}'..."):
result = tool.execute(query=query, max_results=num)
if result.success:
console.print(f"[green]✓[/green] {result.message}")
for idx, article in enumerate(result.data, 1):
published = f" ({article['published']})" if article.get('published') else ""
cats = article.get('categories', [])
cat_str = f" [magenta][{', '.join(cats[:3])}][/magenta]" if cats else ""
console.print(
f" [cyan]{idx}.[/cyan] {article['title']}\n"
f" [dim]{article['authors']}{published}[/dim]{cat_str}"
)
else:
console.print(f"[red]✗[/red] {result.error}")
@main.command()
@click.argument('article_ids', type=int, nargs=-1, required=True)
@click.pass_context
def download(ctx, article_ids):
"""
Download article PDF(s) by ID.
Examples:
quantcoder download 1
quantcoder download 1 2 3
"""
config = ctx.obj['config']
tool = DownloadArticleTool(config)
for article_id in article_ids:
with console.status(f"Downloading article {article_id}..."):
result = tool.execute(article_id=article_id)
if result.success:
console.print(f"[green]✓[/green] Article {article_id}: {result.message}")
else:
console.print(f"[red]✗[/red] Article {article_id} download failed:")
for line in result.error.split("\n"):
console.print(f" [yellow]{line}[/yellow]")
@main.command()
@click.argument('article_ids', type=int, nargs=-1, required=True)
@click.pass_context
def summarize(ctx, article_ids):
"""
Summarize downloaded article(s).
When multiple articles are provided, also creates a consolidated summary
with a new ID that can be used with 'generate'.
Examples:
quantcoder summarize 1
quantcoder summarize 1 2 3 # Creates individual + consolidated summary
"""
config = ctx.obj['config']
tool = SummarizeArticleTool(config)
article_ids_list = list(article_ids)
with console.status(f"Analyzing article(s) {article_ids_list}..."):
result = tool.execute(article_ids=article_ids_list)
if result.success:
console.print(f"[green]✓[/green] {result.message}\n")
# Show individual summaries
for summary in result.data.get('summaries', []):
console.print(Panel(
Markdown(summary.get('summary_text', '')),
title=f"Summary #{summary.get('article_id')} - {summary.get('title', 'Unknown')[:50]}",
border_style="green"
))
# Highlight consolidated summary if created
if result.data.get('consolidated_summary_id'):
consolidated_id = result.data['consolidated_summary_id']
console.print(Panel(
f"[bold]Consolidated summary created: #{consolidated_id}[/bold]\n\n"
f"Source articles: {article_ids_list}\n\n"
f"Use [cyan]quantcoder generate {consolidated_id}[/cyan] to generate code from the combined strategy.",
title="Consolidated Summary",
border_style="cyan"
))
else:
console.print(f"[red]✗[/red] {result.error}")
@main.command(name='summaries')
@click.pass_context
def list_summaries(ctx):
"""
List all available summaries (individual and consolidated).
Shows summary IDs that can be used with 'generate' command.
"""
from quantcoder.core.summary_store import SummaryStore
config = ctx.obj['config']
store = SummaryStore(config.home_dir)
summaries = store.list_summaries()
if not summaries['individual'] and not summaries['consolidated']:
console.print("[yellow]No summaries found. Use 'summarize' to create some.[/yellow]")
return
from rich.table import Table
# Individual summaries
if summaries['individual']:
table = Table(title="Individual Summaries")
table.add_column("ID", style="cyan")
table.add_column("Article", style="white")
table.add_column("Title", style="green")
table.add_column("Type", style="yellow")
for s in summaries['individual']:
table.add_row(
str(s['summary_id']),
str(s['article_id']),
s['title'][:50] + "..." if len(s['title']) > 50 else s['title'],
s['strategy_type']
)
console.print(table)
console.print()
# Consolidated summaries
if summaries['consolidated']:
table = Table(title="Consolidated Summaries")
table.add_column("ID", style="cyan")
table.add_column("Source Articles", style="white")
table.add_column("Type", style="yellow")
table.add_column("Created", style="dim")
for s in summaries['consolidated']:
table.add_row(
str(s['summary_id']),
str(s['source_article_ids']),
s['strategy_type'],
s.get('created_at', '')[:10] if s.get('created_at') else ''
)
console.print(table)
console.print("\n[dim]Use 'quantcoder generate <ID>' to generate code from any summary[/dim]")
def _publish_to_notion(config, summary_id: int, code: str, sharpe: float,
backtest_data: dict, console):
"""Publish strategy article to Notion after successful backtest."""
import os
from quantcoder.core.summary_store import SummaryStore
# Check Notion credentials
notion_key = os.getenv('NOTION_API_KEY')
notion_db = os.getenv('NOTION_DATABASE_ID')
if not notion_key or not notion_db:
console.print("[yellow]⚠ Notion credentials not configured[/yellow]")
console.print(f"[dim]Set NOTION_API_KEY and NOTION_DATABASE_ID in {config.home_dir / '.env'}[/dim]")
console.print("[dim]Use 'quantcoder schedule config' to configure[/dim]")
return
try:
from quantcoder.scheduler import NotionClient, StrategyArticle
# Get summary data
store = SummaryStore(config.home_dir)
summary = store.get_summary(summary_id)
if not summary:
console.print(f"[yellow]⚠ Could not retrieve summary {summary_id} for article[/yellow]")
return
# Determine title and description based on summary type
if summary.get('is_consolidated'):
paper_title = f"Consolidated from articles {summary.get('source_article_ids', [])}"
description = summary.get('merged_description', '')
strategy_type = summary.get('merged_strategy_type', 'hybrid')
paper_url = ""
authors = []
else:
paper_title = summary.get('title', f'Strategy {summary_id}')
description = summary.get('summary_text', '')
strategy_type = summary.get('strategy_type', 'unknown')
paper_url = summary.get('url', '')
authors = [summary.get('authors', 'Unknown')]
# Generate article title based on performance
if sharpe >= 1.5:
perf_label = "High-Performance"
elif sharpe >= 1.0:
perf_label = "Strong"
elif sharpe >= 0.5:
perf_label = "Viable"
else:
perf_label = "Experimental"
strategy_type_display = strategy_type.replace("_", " ").title()
title = f"{perf_label} {strategy_type_display} Strategy"
# Build backtest results for article
backtest_results = {
'sharpe_ratio': sharpe,
'total_return': backtest_data.get('total_return', 0),
'max_drawdown': backtest_data.get('statistics', {}).get('Max Drawdown', 0),
'win_rate': backtest_data.get('statistics', {}).get('Win Rate', 'N/A'),
}
# Create StrategyArticle directly
article = StrategyArticle(
title=title,
paper_title=paper_title,
paper_url=paper_url,
paper_authors=authors,
strategy_summary=description,
strategy_type=strategy_type,
backtest_results=backtest_results,
code_snippet=code[:2000] if len(code) > 2000 else code,
tags=[strategy_type_display]
)
# Publish to Notion
notion_client = NotionClient(api_key=notion_key, database_id=notion_db)
page = notion_client.create_strategy_page(article)
if page:
console.print(f"[green]✓ Published to Notion[/green] (page: {page.id[:8]}...)")
else:
console.print("[yellow]⚠ Failed to create Notion page[/yellow]")
except ImportError as e:
console.print(f"[yellow]⚠ Scheduler module not available: {e}[/yellow]")
except Exception as e:
console.print(f"[red]✗ Failed to publish to Notion: {e}[/red]")
def _run_evolution(config, code: str, source_name: str, max_generations: int,
variants_per_gen: int, start_date: str, end_date: str, console):
"""Run evolution on a strategy to improve it."""
import asyncio
import os
try:
from quantcoder.evolver import EvolutionEngine, EvolutionConfig
# Get QC credentials
qc_user = os.getenv('QC_USER_ID') or os.getenv('QUANTCONNECT_USER_ID')
qc_token = os.getenv('QC_API_TOKEN') or os.getenv('QUANTCONNECT_API_KEY')
qc_project = os.getenv('QC_PROJECT_ID')
if not all([qc_user, qc_token]):
console.print("[yellow]⚠ QC credentials not fully configured for evolution[/yellow]")
return None
# Create evolution config
evo_config = EvolutionConfig(
qc_user_id=qc_user,
qc_api_token=qc_token,
qc_project_id=int(qc_project) if qc_project else None,
max_generations=max_generations,
variants_per_generation=variants_per_gen,
backtest_start_date=start_date,
backtest_end_date=end_date,
)
engine = EvolutionEngine(evo_config)
# Progress callback
def on_gen_complete(state, gen):
best = state.elite_pool.get_best()
if best and best.fitness:
console.print(f" [dim]Gen {gen}: Best fitness = {best.fitness:.4f}[/dim]")
engine.on_generation_complete = on_gen_complete
async def run_evo():
return await engine.evolve(code, source_name)
# Run evolution
with console.status("Evolving strategy..."):
result = asyncio.run(run_evo())
# Get best variant
best = engine.get_best_variant()
if best and best.code:
return {
'code': best.code,
'sharpe': best.metrics.get('sharpe_ratio', 0) if best.metrics else 0,
'backtest_data': best.metrics or {},
'evolution_id': result.evolution_id,
}
return None
except ImportError as e:
console.print(f"[yellow]⚠ Evolution module not available: {e}[/yellow]")
return None
except Exception as e:
console.print(f"[red]✗ Evolution failed: {e}[/red]")
return None
@main.command(name='generate')
@click.argument('summary_id', type=int)
@click.option('--max-attempts', default=6, help='Maximum refinement attempts')
@click.option('--open-in-editor', is_flag=True, help='Open generated code in editor (default: Zed)')
@click.option('--editor', default=None, help='Editor to use (overrides config, e.g., zed, code, vim)')
@click.option('--backtest', is_flag=True, help='Run backtest on QuantConnect after generation')
@click.option('--min-sharpe', default=0.5, type=float, help='Min Sharpe to keep algo and publish to Notion (with --backtest)')
@click.option('--start-date', default='2020-01-01', help='Backtest start date (with --backtest)')
@click.option('--end-date', default='2024-01-01', help='Backtest end date (with --backtest)')
@click.option('--evolve', is_flag=True, help='Evolve strategy after backtest passes (with --backtest)')
@click.option('--gens', default=5, type=int, help='Number of evolution generations (with --evolve)')
@click.option('--variants', default=3, type=int, help='Variants per generation (with --evolve)')
@click.pass_context
def generate_code(ctx, summary_id, max_attempts, open_in_editor, editor, backtest, min_sharpe, start_date, end_date, evolve, gens, variants):
"""
Generate QuantConnect code from a summary.
SUMMARY_ID can be:
- An individual article summary ID
- A consolidated summary ID (created from multiple articles)
With --backtest flag:
- Runs backtest on QuantConnect after code generation
- If Sharpe >= min-sharpe: keeps algo in QC and publishes article to Notion
- If Sharpe < min-sharpe: reports results but does not publish
With --evolve flag (requires --backtest):
- After backtest passes, evolves the strategy for N generations
- Publishes the best evolved variant to Notion
Examples:
quantcoder generate 1 # From article 1 summary
quantcoder generate 6 # From consolidated summary #6
quantcoder generate 1 --open-in-editor
quantcoder generate 1 --backtest # Generate, backtest, and publish if good
quantcoder generate 1 --backtest --min-sharpe 1.0
quantcoder generate 1 --backtest --evolve --gens 5 # Evolve after backtest
"""
config = ctx.obj['config']
tool = GenerateCodeTool(config)
with console.status(f"Generating code for summary #{summary_id}..."):
result = tool.execute(summary_id=summary_id, max_refine_attempts=max_attempts)
if result.success:
console.print(f"[green]✓[/green] {result.message}\n")
# Display summary
if result.data.get('summary'):
console.print(Panel(
Markdown(result.data['summary']),
title="Strategy Summary",
border_style="blue"
))
# Display code
from rich.syntax import Syntax
code_display = Syntax(
result.data['code'],
"python",
theme="monokai",
line_numbers=True
)
console.print("\n")
console.print(Panel(
code_display,
title="Generated Code",
border_style="green"
))
# Open in editor if requested
if open_in_editor:
from .editor import open_in_editor as launch_editor, get_editor_display_name
editor_cmd = editor or config.ui.editor
editor_name = get_editor_display_name(editor_cmd)
code_path = result.data.get('path')
if code_path:
if launch_editor(code_path, editor_cmd):
console.print(f"[cyan]Opened in {editor_name}[/cyan]")
else:
console.print(f"[yellow]Could not open in {editor_name}. Is it installed?[/yellow]")
# Handle backtest if requested
if backtest:
code_path = result.data.get('path')
if not code_path:
console.print("[red]✗[/red] Cannot backtest: no code file path")
return
# Check QuantConnect credentials
if not config.has_quantconnect_credentials():
console.print("[red]Error: QuantConnect credentials not configured[/red]")
console.print(f"[yellow]Please set QUANTCONNECT_API_KEY and QUANTCONNECT_USER_ID in {config.home_dir / '.env'}[/yellow]")
return
console.print("\n")
backtest_tool = BacktestTool(config)
with console.status(f"Running backtest ({start_date} to {end_date})..."):
bt_result = backtest_tool.execute(
file_path=code_path,
start_date=start_date,
end_date=end_date,
name=f"Summary_{summary_id}"
)
if not bt_result.success:
console.print(f"[red]✗[/red] Backtest failed: {bt_result.error}")
return
try:
sharpe = float(bt_result.data.get('sharpe_ratio', 0))
except (TypeError, ValueError):
sharpe = 0.0
console.print(f"[green]✓[/green] Backtest complete: Sharpe = {sharpe:.2f}")
# Display backtest results
from rich.table import Table
bt_table = Table(title="Backtest Results")
bt_table.add_column("Metric", style="cyan")
bt_table.add_column("Value", style="green")
bt_table.add_row("Sharpe Ratio", f"{sharpe:.2f}")
bt_table.add_row("Total Return", str(bt_result.data.get('total_return', 'N/A')))
cagr = bt_result.data.get('cagr')
bt_table.add_row("CAGR", f"{cagr:.1%}" if isinstance(cagr, (int, float)) else "N/A")
max_dd = bt_result.data.get('max_drawdown')
bt_table.add_row("Max Drawdown", f"{max_dd:.1%}" if isinstance(max_dd, (int, float)) else "N/A")
win_rate = bt_result.data.get('win_rate')
bt_table.add_row("Win Rate", f"{win_rate:.1%}" if isinstance(win_rate, (int, float)) else "N/A")
total_trades = bt_result.data.get('total_trades')
bt_table.add_row("Total Trades", str(total_trades) if total_trades is not None else "N/A")
console.print(bt_table)
# Check acceptance criteria
if sharpe >= min_sharpe:
console.print(f"\n[green]✓ Sharpe {sharpe:.2f} >= {min_sharpe} - ACCEPTED[/green]")
final_code = result.data['code']
final_sharpe = sharpe
final_backtest_data = bt_result.data
# Run evolution if requested
if evolve:
console.print(f"\n[cyan]Evolving strategy for {gens} generations...[/cyan]")
evolved_result = _run_evolution(
config=config,
code=result.data['code'],
source_name=f"Summary_{summary_id}",
max_generations=gens,
variants_per_gen=variants,
start_date=start_date,
end_date=end_date,
console=console
)
if evolved_result:
final_code = evolved_result['code']
final_sharpe = evolved_result['sharpe']
final_backtest_data = evolved_result['backtest_data']
console.print(f"[green]✓ Evolution complete: Sharpe improved to {final_sharpe:.2f}[/green]")
# Publish to Notion
console.print("[cyan]Publishing to Notion...[/cyan]")
_publish_to_notion(
config=config,
summary_id=summary_id,
code=final_code,
sharpe=final_sharpe,
backtest_data=final_backtest_data,
console=console
)
else:
console.print(f"\n[yellow]⚠ Sharpe {sharpe:.2f} < {min_sharpe} - NOT PUBLISHED[/yellow]")
console.print("[dim]Strategy kept locally but not published to Notion[/dim]")
else:
console.print(f"[red]✗[/red] {result.error}")
@main.command(name='validate')
@click.argument('file_path', type=click.Path(exists=True))
@click.option('--local-only', is_flag=True, help='Only run local syntax check, skip QuantConnect')
@click.pass_context
def validate_code_cmd(ctx, file_path, local_only):
"""
Validate algorithm code locally and on QuantConnect.
Example:
quantcoder validate generated_code/algorithm_1.py
quantcoder validate my_algo.py --local-only
"""
config = ctx.obj['config']
tool = ValidateCodeTool(config)
# Read the file
with open(file_path, 'r') as f:
code = f.read()
with console.status(f"Validating {file_path}..."):
result = tool.execute(code=code, use_quantconnect=not local_only)
if result.success:
console.print(f"[green]✓[/green] {result.message}")
if result.data and result.data.get('warnings'):
console.print("[yellow]Warnings:[/yellow]")
for w in result.data['warnings']:
console.print(f" • {w}")
else:
console.print(f"[red]✗[/red] {result.error}")
if result.data and result.data.get('errors'):
console.print("[red]Errors:[/red]")
for err in result.data['errors'][:10]:
console.print(f" • {err}")
@main.command(name='backtest')
@click.argument('file_path', type=click.Path(exists=True))
@click.option('--start', default='2020-01-01', help='Backtest start date (YYYY-MM-DD)')
@click.option('--end', default='2024-01-01', help='Backtest end date (YYYY-MM-DD)')
@click.option('--name', help='Name for the backtest')
@click.pass_context
def backtest_cmd(ctx, file_path, start, end, name):
"""
Run backtest on QuantConnect.
Requires QUANTCONNECT_API_KEY and QUANTCONNECT_USER_ID in ~/.quantcoder/.env
Example:
quantcoder backtest generated_code/algorithm_1.py
quantcoder backtest my_algo.py --start 2022-01-01 --end 2024-01-01
"""
config = ctx.obj['config']
# Check credentials first
if not config.has_quantconnect_credentials():
console.print("[red]Error: QuantConnect credentials not configured[/red]")
console.print(f"[yellow]Please set QUANTCONNECT_API_KEY and QUANTCONNECT_USER_ID in {config.home_dir / '.env'}[/yellow]")
return
tool = BacktestTool(config)
with console.status(f"Running backtest on {file_path} ({start} to {end})..."):
result = tool.execute(file_path=file_path, start_date=start, end_date=end, name=name)
if result.success:
console.print(f"[green]✓[/green] {result.message}\n")
# Display results table
from rich.table import Table
table = Table(title="Backtest Results")
table.add_column("Metric", style="cyan")
table.add_column("Value", style="green")
table.add_row("Backtest ID", str(result.data.get('backtest_id', 'N/A')))
sharpe = result.data.get('sharpe_ratio')
try:
table.add_row("Sharpe Ratio", f"{float(sharpe):.2f}" if sharpe is not None else "N/A")
except (ValueError, TypeError):
table.add_row("Sharpe Ratio", str(sharpe))
table.add_row("Total Return", str(result.data.get('total_return') or 'N/A'))
cagr = result.data.get('cagr')
table.add_row("CAGR", f"{cagr:.1%}" if isinstance(cagr, (int, float)) else "N/A")
max_dd = result.data.get('max_drawdown')
table.add_row("Max Drawdown", f"{max_dd:.1%}" if isinstance(max_dd, (int, float)) else "N/A")
win_rate = result.data.get('win_rate')
table.add_row("Win Rate", f"{win_rate:.1%}" if isinstance(win_rate, (int, float)) else "N/A")
total_trades = result.data.get('total_trades')
table.add_row("Total Trades", str(total_trades) if total_trades is not None else "N/A")
console.print(table)
else:
console.print(f"[red]✗[/red] {result.error}")
@main.command()
@click.pass_context
def config_show(ctx):
"""Show current configuration."""
config = ctx.obj['config']
config_text = f"""
**Model Configuration:**
- Provider: {config.model.provider}
- Model: {config.model.model}
- Temperature: {config.model.temperature}
- Max Tokens: {config.model.max_tokens}
**UI Configuration:**
- Theme: {config.ui.theme}
- Auto Approve: {config.ui.auto_approve}
- Show Token Usage: {config.ui.show_token_usage}
**Tools Configuration:**
- Downloads Directory: {config.tools.downloads_dir}
- Generated Code Directory: {config.tools.generated_code_dir}
- Enabled Tools: {', '.join(config.tools.enabled_tools)}
**Paths:**
- Home Directory: {config.home_dir}
- Config File: {config.home_dir / 'config.toml'}
"""
console.print(Panel(
Markdown(config_text),
title="Configuration",
border_style="cyan"
))
@main.command()
def version():
"""Show version information."""
from . import __version__
console.print(f"QuantCoder v{__version__}")
# ============================================================================
# AUTONOMOUS MODE COMMANDS
# ============================================================================
@main.group()
def auto():
"""
Autonomous self-improving mode for strategy generation.
This mode runs continuously, learning from errors and improving over time.
"""
pass
@auto.command(name='start')
@click.option('--query', required=True, help='Strategy query (e.g., "momentum trading")')
@click.option('--max-iterations', default=50, help='Maximum iterations to run')
@click.option('--min-sharpe', default=0.5, type=float, help='Minimum Sharpe ratio threshold')
@click.option('--output', type=click.Path(), help='Output directory for strategies')
@click.option('--demo', is_flag=True, help='Run in demo mode (no real API calls)')
@click.pass_context
def auto_start(ctx, query, max_iterations, min_sharpe, output, demo):
"""
Start autonomous strategy generation.
Example:
quantcoder auto start --query "momentum trading" --max-iterations 50
"""
import asyncio
from pathlib import Path
from quantcoder.autonomous import AutonomousPipeline
config = ctx.obj['config']
if demo:
console.print("[yellow]Running in DEMO mode (no real API calls)[/yellow]\n")
output_dir = Path(output) if output else None
pipeline = AutonomousPipeline(
config=config,
demo_mode=demo
)
try:
asyncio.run(pipeline.run(
query=query,
max_iterations=max_iterations,
min_sharpe=min_sharpe,
output_dir=output_dir
))
except KeyboardInterrupt:
console.print("\n[yellow]Autonomous mode stopped by user[/yellow]")
@auto.command(name='status')
def auto_status():
"""
Show autonomous mode status and learning statistics.
"""
from quantcoder.autonomous.database import LearningDatabase
db = LearningDatabase()
# Show library stats
stats = db.get_library_stats()
console.print("\n[bold cyan]Autonomous Mode Statistics[/bold cyan]\n")
console.print(f"Total strategies generated: {stats.get('total_strategies', 0)}")
console.print(f"Successful: {stats.get('successful', 0)}")
console.print(f"Average Sharpe: {stats.get('avg_sharpe', 0):.2f}\n")
# Show common errors
console.print("[bold cyan]Common Errors:[/bold cyan]")
from quantcoder.autonomous.learner import ErrorLearner
learner = ErrorLearner(db)
errors = learner.get_common_errors(limit=5)
for i, error in enumerate(errors, 1):
fix_rate = (error['fixed_count'] / error['count'] * 100) if error['count'] > 0 else 0
console.print(f" {i}. {error['error_type']}: {error['count']} ({fix_rate:.0f}% fixed)")
db.close()
@auto.command(name='report')
@click.option('--format', type=click.Choice(['text', 'json']), default='text')
def auto_report(format):
"""
Generate learning report from autonomous mode.
"""
from quantcoder.autonomous.database import LearningDatabase
db = LearningDatabase()
stats = db.get_library_stats()
if format == 'json':
import json
console.print(json.dumps(stats, indent=2))
else:
# Text format
console.print("\n[bold cyan]Autonomous Mode Learning Report[/bold cyan]\n")
console.print("=" * 60)
# Overall stats
console.print(f"\nTotal Strategies: {stats.get('total_strategies', 0)}")
console.print(f"Successful: {stats.get('successful', 0)}")
console.print(f"Average Sharpe: {stats.get('avg_sharpe', 0):.2f}")
console.print(f"Average Errors: {stats.get('avg_errors', 0):.1f}")
console.print(f"Average Refinements: {stats.get('avg_refinements', 0):.1f}")
# Category breakdown
if stats.get('categories'):
console.print("\n[bold]Category Breakdown:[/bold]")
for cat in stats['categories']:
console.print(f" • {cat['category']}: {cat['count']} strategies (avg Sharpe: {cat['avg_sharpe']:.2f})")
db.close()
# ============================================================================
# LIBRARY BUILDER MODE COMMANDS
# ============================================================================
@main.group()
def library():
"""
Library builder mode - Build comprehensive strategy library from scratch.
This mode systematically generates strategies across all major categories.
"""
pass
@library.command(name='build')
@click.option('--comprehensive', is_flag=True, help='Build all categories')
@click.option('--max-hours', default=24, type=int, help='Maximum build time in hours')
@click.option('--output', type=click.Path(), help='Output directory for library')
@click.option('--min-sharpe', default=0.5, type=float, help='Minimum Sharpe ratio threshold')
@click.option('--categories', help='Comma-separated list of categories to build')
@click.option('--demo', is_flag=True, help='Run in demo mode (no real API calls)')
@click.pass_context
def library_build(ctx, comprehensive, max_hours, output, min_sharpe, categories, demo):
"""
Build strategy library from scratch.
Example:
quantcoder library build --comprehensive --max-hours 24
quantcoder library build --categories momentum,mean_reversion
"""
import asyncio
from pathlib import Path
from quantcoder.library import LibraryBuilder
config = ctx.obj['config']
if demo:
console.print("[yellow]Running in DEMO mode (no real API calls)[/yellow]\n")
output_dir = Path(output) if output else None
category_list = categories.split(',') if categories else None
builder = LibraryBuilder(
config=config,
demo_mode=demo
)
try:
asyncio.run(builder.build(
comprehensive=comprehensive,
max_hours=max_hours,
output_dir=output_dir,
min_sharpe=min_sharpe,
categories=category_list
))
except KeyboardInterrupt:
console.print("\n[yellow]Library build stopped by user[/yellow]")
@library.command(name='status')
def library_status():
"""
Show library build progress.
"""
import asyncio
from quantcoder.library import LibraryBuilder
builder = LibraryBuilder()
try:
asyncio.run(builder.status())
except FileNotFoundError:
console.print("[yellow]No library build in progress[/yellow]")