File size: 24,874 Bytes
cae0896
 
74098d2
 
 
cae0896
d7171f4
74098d2
cae0896
 
74098d2
d7171f4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
74098d2
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
---
title: StratoTest
emoji: ๐Ÿ“ˆ
colorFrom: purple
colorTo: pink
sdk: docker
app_port: 7860
pinned: true
---


# StratoTest by Team Prahari
### Agentic AI Backtesting Tool โ€” Describe a strategy in plain English. Get a full backtest in seconds.

[![Live Demo](https://img.shields.io/badge/๐Ÿค—%20Hugging%20Face-Live%20Demo-blue)](https://darshanpurohit-stratotest.hf.space/)
[![Space](https://img.shields.io/badge/๐Ÿค—%20Hugging%20Face-Space%20+%20Code-yellow)](https://huggingface.co/spaces/Darshanpurohit/StratoTest/)
[![FastAPI](https://img.shields.io/badge/Backend-FastAPI-009688)](https://fastapi.tiangolo.com/)
[![Streamlit](https://img.shields.io/badge/Frontend-Streamlit-FF4B4B)](https://streamlit.io/)

---

---

<div align="center">

#  TEAM PRAHARI 
```
โ•”โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•—
โ•‘              Built by three builders.                โ•‘
โ•‘           Powered by one obsession.                  โ•‘
โ•šโ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•
```

<br/>

| &nbsp;&nbsp;&nbsp;๐Ÿง‘โ€๐Ÿ’ป&nbsp;&nbsp;&nbsp; | Builder | &nbsp;&nbsp;&nbsp;GitHub&nbsp;&nbsp;&nbsp; |
|:---:|:---|:---:|
| ![](https://img.shields.io/badge/-โ—-ff6b6b?style=flat-square) | **Chandan Singh** | [![GitHub](https://img.shields.io/badge/chandan22468-%23181717?style=for-the-badge&logo=github)](https://github.com/chandan22468) |
| ![](https://img.shields.io/badge/-โ—-ffd93d?style=flat-square) | **Darshan Purohit** | [![GitHub](https://img.shields.io/badge/darshanpurohit20-%23181717?style=for-the-badge&logo=github)](https://github.com/darshanpurohit20) |
| ![](https://img.shields.io/badge/-โ—-6bcb77?style=flat-square) | **Harsh Redasani** | [![GitHub](https://img.shields.io/badge/redasaniharsh-%23181717?style=for-the-badge&logo=github)](https://github.com/redasaniharsh) |

<br/>

![](https://img.shields.io/badge/Hackathon-2026-blueviolet?style=for-the-badge)
![](https://img.shields.io/badge/Made%20with-Claude%20+%20Gemini%20+%20Pinecone-black?style=for-the-badge)
![](https://img.shields.io/badge/India-๐Ÿ‡ฎ๐Ÿ‡ณ-orange?style=for-the-badge)

</div>

---

## ๐ŸŒ Deployed Links

| Interface | URL |
|---|---|
| **Direct UI** | [darshanpurohit-stratotest.hf.space](https://darshanpurohit-stratotest.hf.space/) |
| **UI + Codebase (Hugging Face Space)** | [huggingface.co/spaces/Darshanpurohit/StratoTest](https://huggingface.co/spaces/Darshanpurohit/StratoTest/) |

---

## ๐Ÿง  What is StratoTest?

StratoTest is a **multi-agent AI backtesting system**. A user types a trading strategy in plain English. A pipeline of autonomous AI agents converts that description into executable Python code, validates it, runs a realistic historical simulation with friction modelling, generates a performance tearsheet, and then autonomously optimizes the strategy โ€” all without any further user input.

A **Talkback Validation Agent** acts as a conversational gatekeeper, ensuring queries are complete before expensive computation begins. A **Pinecone RAG Layer** provides a strategy memory store, surfacing historically relevant configurations to auto-fill missing details and improve results over time.

---

## โœจ Key Features (USPs)

1. **Self-correcting code generation** โ€” The agent writes Python strategy code, runs it in a sandbox, and fixes its own errors without user intervention. Not a chatbot โ€” an agent with a goal.

2. **Autonomous optimization loop** โ€” The Optimization Agent tries parameter variants, compares results, keeps improvements, and discards regressions. Goal-driven: targets Sharpe > 1.0 and Max Drawdown < 20%.

3. **Lookahead bias detection** โ€” The Validation Agent checks for future data leakage, a real quantitative finance concern that most tools ignore entirely.

4. **Live agent reasoning panel** โ€” Every tool call, every decision, every fix is streamed to the UI in real time. Watch the agent think.

5. **Session memory** โ€” "Test the same strategy but add a volume filter" works because agents remember prior runs.

6. **Friction-realistic results** โ€” Slippage, commissions, and spread are baked in. Results reflect what you'd actually make, not theoretical maximums.

7. **Explain Agent** โ€” Post-backtest, ask "Why did it lose in 2022?" and get a narrative explanation with structural fix suggestions.

8. **Talkback Validation Layer** โ€” Before any compute, the Talkback Agent confirms all required fields (asset, timeframe, date range, strategy intent) โ€” using RAG to auto-suggest smart defaults from past successful runs.

9. **Pinecone RAG Memory** โ€” Every successful backtest is embedded and stored. Future queries retrieve semantically similar past configs to guide decisions automatically.

---

## ๐Ÿ—๏ธ System Architecture

### The Multi-Agent Pipeline

```
User Natural Language Input
         โ”‚
         โ–ผ
โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚    TALKBACK AGENT (NEW)     โ”‚  โ† Validates query completeness
โ”‚                             โ”‚    Uses Pinecone RAG for smart defaults
โ”‚  Checks:                    โ”‚    Asks user only if RAG can't fill gaps
โ”‚  โ€ข asset_name               โ”‚
โ”‚  โ€ข timeframe                โ”‚
โ”‚  โ€ข start_date / end_date    โ”‚
โ”‚  โ€ข strategy_hint            โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜
         โ”‚ enriched, complete query
         โ–ผ
โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚      STRATEGY AGENT         โ”‚  โ† LangChain + Claude + Tools
โ”‚                             โ”‚    Writes Python strategy code
โ”‚  Tools:                     โ”‚    Self-corrects syntax errors
โ”‚  โ€ข validate_syntax          โ”‚    Loops until sandbox passes
โ”‚  โ€ข run_sandbox_test         โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜
         โ”‚ validated strategy code (Python string)
         โ–ผ
โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚     VALIDATION AGENT        โ”‚  โ† Separate LLM call
โ”‚                             โ”‚    Checks lookahead bias
โ”‚  Checks:                    โ”‚    Minimum trade count
โ”‚  โ€ข lookahead bias           โ”‚    Sharpe sanity check
โ”‚  โ€ข trade frequency          โ”‚    Sends PASS or FAIL+reason
โ”‚  โ€ข Sharpe sanity            โ”‚    back to Strategy Agent
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜
         โ”‚ PASS
         โ–ผ
โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚   BACKTEST ENGINE           โ”‚  โ† Pure Python, no LLM
โ”‚                             โ”‚    exec() the strategy code
โ”‚  Applies:                   โ”‚    Apply friction costs
โ”‚  โ€ข slippage                 โ”‚    Calculate all metrics
โ”‚  โ€ข commissions              โ”‚
โ”‚  โ€ข spread                   โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜
         โ”‚ metrics dict
         โ–ผ
โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚    OPTIMIZATION AGENT       โ”‚  โ† LangChain + Claude + Tools
โ”‚                             โ”‚    Goal: Sharpe > 1.0, DD < 20%
โ”‚  Tools:                     โ”‚    ONE tweak per iteration
โ”‚  โ€ข tweak_parameter          โ”‚    Max 4 iterations
โ”‚  โ€ข run_full_backtes         โ”‚    Returns best variant
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜
         โ”‚ best strategy + all iteration metrics
         โ–ผ
โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚      TEARSHEET + UI         โ”‚  โ† Plotly charts + Streamlit
โ”‚                             โ”‚    Equity curve
โ”‚   Shows:                    โ”‚    Drawdown chart
โ”‚  โ€ข Original vs Best         โ”‚    Monthly returns heatmap
โ”‚  โ€ข Iteration table          โ”‚    Agent reasoning log
โ”‚  โ€ข Explain button           โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜
         โ”‚ on-demand
         โ–ผ
โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚     EXPLAIN AGENT           โ”‚  โ† Single LLM call, no tools
โ”‚                             โ”‚    Analyzes bad periods
โ”‚  Answers:                   โ”‚    Explains WHY it lost money
โ”‚  โ€ข "Why 2022 loss?"         โ”‚    Suggests structural fixes
โ”‚  โ€ข "What kills it?"         โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜
```

### RAG + Talkback Layer (Intelligence Layers)

The existing pipeline is extended with two intelligence layers that prevent silent hallucination and leverage historical strategy memory:

```
BEFORE (Old Flow):
  User Query โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ†’ Deep Agent โ†’ Backtest

AFTER (New Flow):
  User Query โ†’ [Talkback Agent] โ†’ [RAG Layer] โ†’ [Validation Gate]
                                                      โ”‚
                                                      โ–ผ 
                                          โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ดโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
                                          โ–ผ                       โ–ผ
                                   [Complete Query]        [Incomplete Query]
                                          โ”‚                       โ”‚
                                          โ”‚               [Ask User + LLM Defaults]
                                          โ”‚                       โ”‚
                                          โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜
                                                      โ–ผ
                                               Deep Agent Controller
                                                      โ”‚
                                                      โ–ผ
                                               Backtest Engine
                                                      โ”‚
                                                      โ–ผ
                                        [Index Result โ†’ Pinecone RAG]
```

| Layer | Name | Role | Technology |
|---|---|---|---|
| Layer 1 | **Pinecone RAG Layer** | Retrieves historically relevant strategy configs from a vector database | Pinecone + Gemini Embeddings |
| Layer 2 | **Talkback Validation Agent** | Validates all required fields; uses RAG to suggest smart defaults; asks user only when necessary | Gemini 2.0 Flash + Pinecone |

#### What Gets Stored in Pinecone

Every successful backtest (win rate > 50%) is embedded and stored. Each vector carries rich metadata:

```json
{
  "strategy_id": "uuid-v4",
  "asset_name": "RELIANCE.NS",
  "asset_label": "Reliance Industries",
  "timeframe": "1d",
  "start_date": "2022-01-01",
  "end_date": "2024-01-01",
  "duration_label": "2 years",
  "strategy_type": "EMA Cross",
  "indicators_used": ["EMA_20", "EMA_50", "ADX"],
  "win_rate": 62.5,
  "roi": 18.3,
  "market_regime": "trending",
  "trade_count": 45,
  "summary_text": "EMA 20/50 crossover on Reliance Industries daily chart over 2 years trending regime"
}
```

#### Talkback Decision Logic

The Talkback Agent enforces that all 5 required fields are resolved before passing the query to the Deep Agent:

| Field | Example Values | Resolution Path |
|---|---|---|
| `asset_name` | `"Nifty 50"`, `"RELIANCE"`, `"BTC/USD"` | User text โ†’ NER โ†’ RAG suggestion โ†’ User confirm |
| `timeframe` | `"1d"`, `"1h"`, `"15m"`, `"1w"` | User text โ†’ RAG suggestion โ†’ LLM default |
| `start_date` | `"2022-01-01"` | User text โ†’ duration math โ†’ LLM default |
| `end_date` | `"2024-12-31"` or `"today"` | Derived from start + duration |
| `strategy_hint` | `"RSI overbought"`, `"EMA cross"`, `"breakout"` | User intent โ†’ RAG strategy_type โ†’ LLM inference |

Auto-fill threshold: if RAG confidence score > 0.85, the field is filled automatically and the user is notified. Below 0.85, the field goes to the missing list and the Talkback UI presents options.

---

## ๐Ÿš€ Quick Start

### 1. Clone and set up

```bash
git clone https://github.com/darshanpurohit20/Prahari_Stratotest
cd Prahari_Stratotest
cp .env.example .env
```

### 2. Add your API keys

Edit `.env`:

```env
ANTHROPIC_API_KEY=your_anthropic_key_here
PINECONE_API_KEY=your_pinecone_key_here
GEMINI_API_KEY=your_gemini_key_here
```

Get your Anthropic key at: https://console.anthropic.com/

### 3. Install dependencies

```bash
pip install -r requirements.txt
```

### 4. (Optional) Seed Pinecone with sample strategies

```bash
python scripts/seed_pinecone.py
```

### 5. Start the FastAPI backend

```bash
python -m uvicorn main:app --reload --port 8000
```

### 6. Start the Streamlit frontend (new terminal)

```bash
streamlit run frontend/app.py
```

### 7. Open browser

- **Frontend:** http://localhost:8501
- **API Docs:** http://localhost:8000/docs

---

## ๐Ÿ“ Project Structure

```
prahari/
โ”‚
โ”œโ”€โ”€ main.py                          โ† FastAPI app factory + uvicorn runner
โ”œโ”€โ”€ requirements.txt                 โ† All pinned dependencies
โ”œโ”€โ”€ .env.example                     โ† Template for secrets (never commit .env)
โ”œโ”€โ”€ .gitignore
โ”œโ”€โ”€ config.py                        โ† Central config (env vars, constants)
โ”‚
โ”œโ”€โ”€ agent/                           โ† All LLM agent logic
โ”‚   โ”œโ”€โ”€ tools.py                     โ† @tool decorated LangChain tools
โ”‚   โ”œโ”€โ”€ strategy_agent.py            โ† Agent 1: code generation + self-correction
โ”‚   โ”œโ”€โ”€ validation_agent.py          โ† Agent 2: bias + sanity checks
โ”‚   โ”œโ”€โ”€ optimization_agent.py        โ† Agent 3: autonomous parameter tuning
โ”‚   โ”œโ”€โ”€ explain_agent.py             โ† Agent 4: narrative loss explanation
โ”‚   โ”œโ”€โ”€ memory.py                    โ† Session context store
โ”‚   โ”œโ”€โ”€ pipeline.py                  โ† Master orchestrator
โ”‚   โ”œโ”€โ”€ parser.py                    โ† Claude LLM parser
โ”‚   โ””โ”€โ”€ prompts.py                   โ† All system prompts (single source of truth)
โ”‚
โ”œโ”€โ”€ rag/                             โ† RAG + Talkback intelligence layers (NEW)
โ”‚   โ”œโ”€โ”€ embedder.py                  โ† Gemini text-embedding-004 wrapper
โ”‚   โ”œโ”€โ”€ indexer.py                   โ† Pinecone upsert + index_completed_strategy()
โ”‚   โ”œโ”€โ”€ retriever.py                 โ† Pinecone query + top-K fetch
โ”‚   โ”œโ”€โ”€ talkback_agent.py            โ† Talkback Validation Agent (Gemini 2.0 Flash)
โ”‚   โ”œโ”€โ”€ default_generator.py         โ† LLM Default Generator + static fallbacks
โ”‚   โ””โ”€โ”€ validator.py                 โ† Entity extraction + confidence scoring
โ”‚
โ”œโ”€โ”€ engine/                          โ† Pure Python backtesting (no LLM)
โ”‚   โ”œโ”€โ”€ data.py                      โ† yfinance OHLCV fetcher + indicator calc
โ”‚   โ”œโ”€โ”€ backtester.py                โ† exec() engine + trade simulator
โ”‚   โ”œโ”€โ”€ friction.py                  โ† Slippage, commission, spread models
โ”‚   โ”œโ”€โ”€ tearsheet.py                 โ† Metrics computation + chart data
โ”‚   โ””โ”€โ”€ strategies/
โ”‚       โ”œโ”€โ”€ base.py                  โ† BaseStrategy ABC โ€” every generated class inherits this
โ”‚       โ”œโ”€โ”€ ma_crossover.py          โ† Strategy 1: MA / EMA Crossover
โ”‚       โ”œโ”€โ”€ rsi_reversal.py          โ† Strategy 2: RSI Reversal
โ”‚       โ”œโ”€โ”€ fibonacci_pullback.py    โ† Strategy 3: Fibonacci Pullback
โ”‚       โ””โ”€โ”€ strategies.py           โ† Strategies 4โ€“10
โ”‚
โ”œโ”€โ”€ api/                             โ† FastAPI REST layer
โ”‚   โ”œโ”€โ”€ models/
โ”‚   โ”‚   โ”œโ”€โ”€ request.py               โ† Pydantic input models
โ”‚   โ”‚   โ””โ”€โ”€ response.py              โ† Pydantic output models
โ”‚   โ””โ”€โ”€ routes/
โ”‚       โ”œโ”€โ”€ backtest.py              โ† POST /backtest
โ”‚       โ”œโ”€โ”€ talkback.py              โ† POST /talkback/validate, POST /talkback/confirm (NEW)
โ”‚       โ”œโ”€โ”€ strategy.py              โ† GET /strategies, POST /explain
โ”‚       โ””โ”€โ”€ health.py                โ† GET /health
โ”‚
โ”œโ”€โ”€ scripts/
โ”‚   โ””โ”€โ”€ seed_pinecone.py             โ† One-time Pinecone seed script for testing
โ”‚
โ””โ”€โ”€ frontend/
    โ””โ”€โ”€ app.py                       โ† Streamlit UI (single file)
```

---

## ๐ŸŽฏ Supported Strategies

### Classic

| # | Strategy |
|---|---|
| 1 | MA / EMA Crossover |
| 2 | RSI Reversal |
| 3 | Fibonacci Pullback |
| 4 | Support / Resistance Bounce |
| 5 | Breakout + Retest |
| 6 | Higher High Higher Low |

### SMC (Smart Money Concepts)

| # | Strategy |
|---|---|
| 7 | Order Block Entry |
| 8 | Fair Value Gap (FVG) |
| 9 | Change of Character (CHoCH) |
| 10 | Break of Structure + Pullback |

---

## ๐Ÿ’ฌ Example Inputs

```
"Buy when 50 EMA crosses above 200 EMA, SL below last swing low, 1:2 RR"
"Buy at bullish order block, SL below OB, 1:3 RR"
"Buy when RSI drops below 30, SL below swing low, 1:2 RR"
"Buy at 0.618 fibonacci level in uptrend, 1:2 RR"
"Buy after break of structure pullback, SL below BOS, 1:3 RR"
"Buy when MACD crosses above signal line and RSI is below 60"
"Buy at Bollinger Band lower band, sell at upper band"
```

---

## ๐ŸŒ Supported Markets & Tickers

| Market | Example Tickers |
|---|---|
| NSE India | `RELIANCE.NS`, `TCS.NS`, `INFY.NS` |
| BSE India | `RELIANCE.BO` |
| Nifty Index | `^NSEI`, `^NSEBANK` |
| US Stocks | `AAPL`, `TSLA`, `GOOGL` |
| Crypto | `BTC-USD`, `ETH-USD` |
| Forex | `EURUSD=X`, `GBPUSD=X` |

---

## ๐Ÿ”Œ API Reference

### Core Endpoints

| Method | Route | Description |
|---|---|---|
| `POST` | `/backtest` | Run a full agentic backtest |
| `GET` | `/strategies` | List all supported strategy types |
| `POST` | `/explain` | Ask the Explain Agent about backtest results |
| `GET` | `/health` | Service health check |

### Talkback Endpoints (RAG Layer)

| Method | Route | Description |
|---|---|---|
| `POST` | `/talkback/validate` | Submit a raw query for entity extraction + RAG validation |
| `POST` | `/talkback/confirm` | Submit confirmed/modified fields to get an enriched query ready for the Deep Agent |

#### Example: Validate a query

```bash
curl -X POST http://localhost:8000/talkback/validate \
  -H "Content-Type: application/json" \
  -d '{"user_query": "RSI strategy on Nifty"}'
```

Response when fields are missing:

```json
{
  "status": "incomplete",
  "resolved_fields": {
    "asset_name": "^NSEI",
    "strategy_hint": "RSI"
  },
  "missing_fields": [
    {
      "field": "timeframe",
      "question": "What timeframe should the backtest use?",
      "options": [
        {"label": "Daily (1d)", "value": "1d"},
        {"label": "Hourly (1h)", "value": "1h"},
        {"label": "Weekly (1wk)", "value": "1wk"},
        {"label": "Custom โ€” I'll type it", "value": null}
      ],
      "rag_suggestion": {
        "label": "Daily (based on similar Nifty RSI strategies)",
        "confidence": 0.91
      }
    }
  ]
}
```

---

## ๐Ÿ“Š Data Schemas

### BacktestResult

```python
{
    "total_trades":          int,
    "sharpe_ratio":          float,   # annualised
    "max_drawdown_pct":      float,   # negative, e.g. -18.3
    "win_rate_pct":          float,   # 0โ€“100
    "total_return_pct":      float,
    "profit_factor":         float,
    "avg_trade_return_pct":  float,
    "best_trade_pct":        float,
    "worst_trade_pct":       float,
    "equity_curve":          list[float],         # one per bar
    "monthly_returns":       dict[str, float],    # {"2023-01": 2.3, ...}
    "warning":               str | None,
    "error":                 str | None,
    "traceback":             str | None,
}
```

### PipelineResult

```python
{
    "success":              bool,
    "strategy_name":        str,
    "run_id":               str,
    "strategy_code":        str,
    "baseline_metrics":     BacktestResult,
    "optimized_metrics":    BacktestResult,
    "all_iterations":       list[{
                                "label":              str,
                                "metrics":            BacktestResult,
                                "change_description": str,
                            }],
    "improvement_pct":      float,
    "goal_met":             bool,
    "validation_issues":    list[str],
    "reasoning_log":        list[str],
    "stage_failed":         str | None,
    "error":                str | None,
}
```

---

## โš ๏ธ Error Handling

Every agent function returns a result dict with a `"success"` or `"error"` key โ€” nothing raises unhandled exceptions. Errors are surfaced to the UI gracefully with friendly messages.

| Stage | Fallback |
|---|---|
| Data fetch failure | Return early: `"Could not fetch data for {ticker}"` |
| Strategy Agent fails | Return agent's last error + reasoning log |
| Validation fails | Log warning, continue (sandbox already passed) |
| Backtest fails | Return engine error + strategy code for debug |
| Optimization fails | Return baseline results + log that optimization failed |
| Pinecone unavailable | Skip RAG entirely, proceed with entity extraction only |
| Gemini embedding fails | Use cached zero-vector, skip RAG for this request |
| Pinecone upsert fails | Log warning, return backtest result normally โ€” non-blocking |
| RAG returns 0 matches | Skip RAG suggestions, rely purely on LLM defaults |

---

## โž• Extending the System

The system is designed so new features can be added without modifying existing files.

### Adding a New Strategy

1. Create `engine/strategies/my_strategy.py`
2. Inherit `BaseStrategy`
3. Implement `generate_signals()` and `get_indicators()`
4. Add to `STRATEGY_MAP` in `engine/backtester.py`
5. Add to `GET /strategies` in `api/routes/strategy.py`

### Adding a New Agent

1. Create `agent/new_agent.py`
2. Follow the pattern: `run_new_agent(inputs..., progress_callback) -> dict`
3. Add it as a step in `agent/pipeline.py`
4. Add its system prompt to `agent/prompts.py`

### Adding a New Chart

1. Add `build_X_chart(result: dict) -> go.Figure` to `engine/tearsheet.py`
2. Import and call it in `frontend/app.py`

### Adding Persistence (Redis/DB)

1. Modify `agent/memory.py` โ€” implement `save_session` and `get_or_create_session` to use Redis instead of the in-memory `_sessions` dict
2. No other files need to change

### Adding a New Market/Ticker Type

1. Nothing to change โ€” yfinance handles NSE (`.NS`), crypto (`-USD`), and forex (`=X`) automatically
2. Optionally add examples to the UI pill buttons in `frontend/app.py`

---

## ๐Ÿงช Testing

### Unit Tests

```bash
# Run all tests
pytest tests/

# Key test cases
# tests/test_talkback.py
```

```python
def test_complete_query_returns_ready():
    result = process_query("Backtest Nifty 50 EMA crossover daily from 2022 to 2024")
    assert result["status"] == "ready"
    assert result["enriched_query"]["asset_name"] == "^NSEI"

def test_missing_timeframe_triggers_talkback():
    result = process_query("RSI strategy on Reliance from 2022")
    assert result["status"] in ["incomplete", "ready"]
    if result["status"] == "incomplete":
        assert "timeframe" in result["talkback_options"]

def test_completely_vague_query_returns_all_missing():
    result = process_query("run a backtest")
    assert result["status"] == "incomplete"
    assert len(result["talkback_options"]) >= 3
```

### Integration Test (End-to-End)

```bash
# Start the backend
uvicorn api.main:app --reload

# Test talkback route
curl -X POST http://localhost:8000/talkback/validate \
  -H "Content-Type: application/json" \
  -d '{"user_query": "RSI strategy on Nifty"}'

# Test engine in isolation (no API key needed)
python -c "
from engine.data import fetch_ohlc
from engine.backtester import run_backtest_from_code
df = fetch_ohlc('AAPL', '90d')
print(df.columns.tolist())
print(f'Data shape: {df.shape}')
"
```

### Seed Pinecone for RAG Testing

```bash
python scripts/seed_pinecone.py
```

---

## ๐Ÿ”ง Environment Variables

```env
# Required
ANTHROPIC_API_KEY=sk-ant-...
PINECONE_API_KEY=...
GEMINI_API_KEY=...

# Optional (with defaults)
DEFAULT_TICKER=AAPL
DEFAULT_PERIOD=2y
MAX_OPTIMIZATION_ITERATIONS=4
SANDBOX_TEST_DAYS=90
MIN_TRADES_FOR_VALID_STRATEGY=3
COMMISSION_PCT=0.001
SLIPPAGE_PCT=0.0005
RAG_AUTO_FILL_THRESHOLD=0.85
RAG_TOP_K=5
```

---

*Team Prahari | Hackathon 2026*