File size: 21,078 Bytes
63bad2b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "fa14ed7f",
   "metadata": {},
   "source": [
    "# Strategy Generator"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "88b42b38",
   "metadata": {},
   "source": [
    "## Imports"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "80806d52",
   "metadata": {},
   "source": [
    " Using as API  `backtrader`"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "02a959b3",
   "metadata": {},
   "outputs": [],
   "source": [
    "%matplotlib inline\n",
    "import os\n",
    "import io\n",
    "import sys\n",
    "import matplotlib.pyplot as plt\n",
    "import matplotlib.dates as mdates\n",
    "from datetime import datetime\n",
    "import backtrader as bt\n",
    "import pandas as pd\n",
    "import yfinance as yf\n",
    "import matplotlib.pyplot as plt\n",
    "from matplotlib.ticker import FuncFormatter\n",
    "from dotenv import load_dotenv\n",
    "from openai import OpenAI\n",
    "import anthropic\n",
    "import huggingface_hub \n",
    "from huggingface_hub import InferenceClient\n",
    "from IPython.display import Markdown, display, update_display\n",
    "import gradio as gr\n",
    "import subprocess\n",
    "\n",
    "# Environment\n",
    "load_dotenv(override=True)\n",
    "os.environ['OPENAI_API_KEY'] = os.getenv('OPENAI_API_KEY')\n",
    "os.environ['ANTHROPIC_API_KEY'] = os.getenv('ANTHROPIC_API_KEY')\n",
    "google_api_key = os.getenv('GOOGLE_API_KEY')\n",
    "deepseek_api_key = os.getenv('DEEPSEEK_API_KEY')\n",
    "grok_api_key = os.getenv(\"XAI_API_KEY\")\n",
    "\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "810ba72f",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Init variables\n",
    "# Market name mapping\n",
    "TICKER_TO_MARKET = {\n",
    "    'AAPL': 'Apple Inc.',\n",
    "    'GOOGL': 'Alphabet/Google',\n",
    "    'AMZN': 'Amazon.com',\n",
    "    'TSLA': 'Tesla Inc.',\n",
    "    'JPM': 'JPMorgan Chase & Co.',\n",
    "    'V': 'Visa Inc.',\n",
    "    'SPY': 'S&P 500 ETF',\n",
    "    'QQQ': 'Nasdaq 100 ETF',\n",
    "    'MSFT': 'Microsoft Corp.',\n",
    "    'NVDA': 'NVIDIA Corp.',\n",
    "    'META': 'Meta Platforms',\n",
    "    'BRK-B': 'Berkshire Hathaway',\n",
    "    'UNH': 'UnitedHealth Group',\n",
    "    'XOM': 'Exxon Mobil Corp.'\n",
    "}\n",
    "MARKET_TO_TICKER = {\n",
    "    'Apple Inc.': 'AAPL',\n",
    "    'Alphabet/Google': 'GOOGL',\n",
    "    'Amazon.com': 'AMZN',\n",
    "    'Tesla Inc.': 'TSLA',\n",
    "    'JPMorgan Chase & Co.': 'JPM',\n",
    "    'Visa Inc.': 'V',\n",
    "    'S&P 500 ETF': 'SPY',\n",
    "    'Nasdaq 100 ETF': 'QQQ',\n",
    "    'Microsoft Corp.': 'MSFT',\n",
    "    'NVIDIA Corp.': 'NVDA',\n",
    "    'Meta Platforms': 'META',\n",
    "    'Berkshire Hathaway': 'BRK-B',\n",
    "    'UnitedHealth Group': 'UNH',\n",
    "    'Exxon Mobil Corp.': 'XOM'\n",
    "}\n",
    "# Variable that will get later with Gradio\n",
    "current_date = datetime.now().strftime('%Y-%m-%d')\n",
    "MARKET = 'AAPL'\n",
    "API_FIN = 'backtrader'\n",
    "DATE={'start':'1990-01-01', 'end':current_date}\n",
    "INTERVAL='2m'\n",
    "AUTO_PERIOD= True\n",
    "PERIOD='60d'\n",
    "# LLMsP\n",
    "OPENAI_MODEL = \"gpt-5-nano\"\n",
    "CLAUDE_MODEL = \"claude-sonnet-4-20250514\"\n",
    "GIMINI_MODEL =  \"gemini-2.5-flash\"\n",
    "DEEPSEEK_MODEL = \"deepseek-reasoner\"\n",
    "QWEN3_MODEL = \"Qwen/Qwen3-Coder-480B-A35B-Instruct\"\n",
    "QWEN2_MODEL = \"Qwen/Qwen2.5-Coder-32B-Instruct\"\n",
    "SAVE_PLT= True\n",
    "GROK4_MODEL = \"grok-4-fast-reasoning\"\n",
    "LOCAL=True\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "4a0713ed",
   "metadata": {},
   "outputs": [],
   "source": [
    "\n",
    "# Initialize clients\n",
    "openai = OpenAI()\n",
    "deepseek_api= OpenAI(\n",
    "        api_key=deepseek_api_key, \n",
    "        base_url=\"https://api.deepseek.com\"\n",
    "        )\n",
    "gemini_api = OpenAI(\n",
    "        api_key=google_api_key, \n",
    "        base_url=\"https://generativelanguage.googleapis.com/v1beta/openai/\"\n",
    "        )\n",
    "grok_api = OpenAI(api_key=grok_api_key, base_url=\"https://api.x.ai/v1\")\n",
    "claude = anthropic.Anthropic()\n",
    "client = InferenceClient()     # For HuggingFace Inference API"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "3bbe4f90",
   "metadata": {},
   "source": [
    "## Prompt "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ea6649c5",
   "metadata": {},
   "outputs": [],
   "source": [
    "import inspect\n",
    "from bt_strategies import SmaCross\n",
    "import re\n",
    "# VERSION not working\n",
    "def format_class(strategy):\n",
    "    def replace_docstring(match):\n",
    "    # Replace with cleaned docstring\n",
    "        if remaining_doc:\n",
    "            return f'\"\"\"\\n{remaining_doc}\\n    \"\"\"'\n",
    "        else:\n",
    "            return '\"\"\"\"\"\"'  # Empty docstring\n",
    "    source_code = inspect.getsource(strategy)\n",
    "    #print(source_code)\n",
    "    docstring = SmaCross.__doc__\n",
    "    user_prompt_match = re.search(r'User prompt:\\s*\"([^\"]+)\"', docstring)\n",
    "    user_prompt = user_prompt_match.group(1) if user_prompt_match else \"No user prompt found.\"\n",
    "\n",
    "    call_match = re.search(r'Call:\\s*(.+)', docstring)\n",
    "    call_line = call_match.group(1) if call_match else \"cerebro.addstrategy(NotFoundStrategy)\"\n",
    "    \n",
    "    # Clean docstring\n",
    "    remaining_doc = re.sub(r'User prompt:\\s*\"[^\"]+\"\\s*\\n?', '', docstring)\n",
    "    remaining_doc = re.sub(r'Call:\\s*.+\\s*\\n?', '', remaining_doc)\n",
    "    remaining_doc = remaining_doc.strip()\n",
    "    \n",
    "    pattern = r'(\"\"\".*?\"\"\"|\\'\\'\\'.*?\\'\\'\\')'\n",
    "    clean_source = re.sub(pattern, replace_docstring, source_code, count=1, flags=re.DOTALL)\n",
    "\n",
    "\n",
    "    # ✅ Final formatted output\n",
    "    final_output = f'''\n",
    "# User prompt:\n",
    "# \"{user_prompt}\"\n",
    "\n",
    "# Generated Python code:\n",
    "import backtrader as bt\n",
    "{clean_source}\n",
    "# Initialize Cerebro\n",
    "cerebro = bt.Cerebro()\n",
    "{call_line}\n",
    "'''\n",
    "    return final_output\n",
    "\n",
    "print (format_class(SmaCross))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "id": "104360db",
   "metadata": {},
   "outputs": [],
   "source": [
    "example_1= ''' \n",
    "# User prompt:\n",
    "# \"Go long when the 10-period SMA crosses above the 100-period SMA,\n",
    "#  and exit when the 10-period SMA crosses below the 100-period SMA.\"\n",
    "\n",
    "# Generated Python code:\n",
    "import backtrader as bt\n",
    "class SmaCross(bt.Strategy):\n",
    "    \"\"\"\n",
    "    Simple moving average crossover strategy.\n",
    "    Buy when fast SMA crosses above slow SMA.\n",
    "    Sell when fast SMA crosses below slow SMA.\n",
    "    \"\"\"\n",
    "    params = dict(pfast=10, pslow=100)\n",
    "\n",
    "    def __init__(self):\n",
    "        self.sma_fast = bt.ind.SMA(period=self.p.pfast)\n",
    "        self.sma_slow = bt.ind.SMA(period=self.p.pslow)\n",
    "        self.crossover = bt.ind.CrossOver(self.sma_fast, self.sma_slow)\n",
    "\n",
    "    def next(self):\n",
    "        if not self.position:\n",
    "            if self.crossover > 0:  # Golden cross\n",
    "                self.buy()\n",
    "        elif self.crossover < 0:   # Death cross\n",
    "            self.close()\n",
    "\n",
    "# Initialize Cerebro\n",
    "cerebro = bt.Cerebro()\n",
    "cerebro.addstrategy(SmaCross, pfast=10, pslow=100)\n",
    "'''\n",
    "list_of_pyclasses = [example_1]\n",
    "system_message = f'''\n",
    "You are a financial assistant specialized in transforming natural language descriptions of trading strategies into clean, production-ready Python code.\n",
    "\n",
    "Guidelines:\n",
    "- Use only the library {API_FIN}.\n",
    "- Always create a class with the abreviation of the strategy with the form `NameOfStrategy(bt.Strategy)`.\n",
    "- Implement strategy logic in `__init__` (indicators/signals) and `next()` (trade execution).\n",
    "- Implement the strategy for this intervall of time {INTERVAL} \n",
    "- Finish with initializing the strategy in Cerebro:\n",
    "  cerebro = bt.Cerebro()\n",
    "  cerebro.addstrategy(MyStrategy, param1=value, param2=value)\n",
    "- Keep code minimal, clear, and follow Python best practices (PEP8, clear naming, modularity).\n",
    "- If a strategy cannot be implemented with {API_FIN}, respond with: \"Unable to implement with {API_FIN}.\"\n",
    "- If used any addional libraries, add it in the code: import MyUsedLibrary\n",
    "- If you don't know the answer, just say that you don't know, don't try to make up an answer.\n",
    "\n",
    "Example(s) of transformation from user prompt to Python code: \\n\n",
    "'''\n",
    "for pyclass in list_of_pyclasses:\n",
    "  system_message += pyclass"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "id": "f868548e",
   "metadata": {},
   "outputs": [],
   "source": [
    "\n",
    "def user_prompt_for(user_msg):\n",
    "    return f\"\"\"\n",
    "Trading strategy description:\n",
    "\\\"\\\"\\\"{user_msg}\\\"\\\"\\\"\n",
    "\n",
    "Task:\n",
    "- Convert the description into executable Python code.\n",
    "- Use only the library {API_FIN}.\n",
    "- Respond only with valid Python code, following Python best practices\n",
    "\"\"\""
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 20,
   "id": "1589df2f",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Messages in Openai format \n",
    "def messages_for(user_msg):\n",
    "    return [\n",
    "        {\"role\": \"system\", \"content\": system_message},\n",
    "        {\"role\": \"user\", \"content\": user_prompt_for(user_msg)}\n",
    "    ]"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "2ac6d71d",
   "metadata": {},
   "source": [
    "## LLMS executors"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 21,
   "id": "f522a0de",
   "metadata": {},
   "outputs": [],
   "source": [
    "def stream_llms(user_msg, typ_llm=\"gpt\"):   \n",
    "    messages = messages_for(user_msg)\n",
    "    if typ_llm.lower() == \"deepseek\": \n",
    "        stream = deepseek_api.chat.completions.create(\n",
    "            model=\"deepseek-chat\",\n",
    "            messages=messages,\n",
    "            stream=True\n",
    "        )\n",
    "    elif typ_llm.lower() == \"gimini\":\n",
    "        stream = gemini_api.chat.completions.create(\n",
    "            model=\"gemini-2.5-flash\",\n",
    "            messages=messages,\n",
    "            stream=True\n",
    "        )\n",
    "    elif typ_llm.lower() == \"qween2\":\n",
    "        stream = client.chat.completions.create(\n",
    "            model=QWEN2_MODEL,\n",
    "            messages=messages,\n",
    "            stream= True\n",
    "        )\n",
    "    elif typ_llm.lower() == \"qween3\":\n",
    "        stream = client.chat.completions.create(\n",
    "            model=QWEN3_MODEL,\n",
    "            messages=messages,\n",
    "            stream= True\n",
    "        )\n",
    "    elif typ_llm.lower() == \"grok4\":\n",
    "        stream = grok_api.chat.completions.create(\n",
    "            model=GROK4_MODEL,\n",
    "            messages=messages,\n",
    "            stream= True\n",
    "        )\n",
    "    elif typ_llm.lower() == \"claude\":\n",
    "        stream =  claude.messages.stream(\n",
    "        model=CLAUDE_MODEL,\n",
    "        max_tokens=2000,\n",
    "        system=messages[0]['content'],\n",
    "        messages=[messages[1]],\n",
    "    )\n",
    "    elif typ_llm.lower() == \"gpt\": \n",
    "        stream = openai.chat.completions.create(model=OPENAI_MODEL, messages=messages, stream=True)\n",
    "    else:\n",
    "        raise ValueError(\"Unknown model\")\n",
    "    \n",
    "    reply = \"\"\n",
    "    \n",
    "    if typ_llm.lower() == \"claude\":\n",
    "        with stream as stream_clde:\n",
    "            for fragment in stream_clde.text_stream:\n",
    "                reply += fragment\n",
    "                #print(fragment, end='', flush=True)\n",
    "                yield reply.replace(\"```python\\n\",\"\").replace(\"```\",\"\") \n",
    "    else:\n",
    "        for chunk in stream:\n",
    "            if chunk and chunk.choices:\n",
    "                fragment = chunk.choices[0].delta.content or \"\"\n",
    "                reply += fragment\n",
    "                #print(fragment, end='', flush=True)\n",
    "                yield reply.replace(\"```python\\n\",\"\").replace(\"```\",\"\") \n",
    "    #return reply"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 22,
   "id": "c0089d2b",
   "metadata": {},
   "outputs": [],
   "source": [
    "def stream_manager(user_msg, model):\n",
    "    result = stream_llms(user_msg, model)\n",
    "    for stream_so_far in result:\n",
    "        yield stream_so_far"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 23,
   "id": "7792fa04",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Write to python file\n",
    "def write_output(code):\n",
    "    with open(\"code.py\", \"w\") as f:\n",
    "        f.write(code)\n",
    "   \n",
    "def execute_python(code, market_name, interval):\n",
    "    tckr_symbl = MARKET_TO_TICKER[market_name] \n",
    "    # For the moment executing this values here in order to put less complexity to users\n",
    "    interval = interval\n",
    "    period=PERIOD\n",
    "    \n",
    "    code = code.replace(\"```python\",\"\").replace(\"```\",\"\")\n",
    "    output_code = f'''\n",
    "from utils import run_bt\n",
    "import backtrader as bt\n",
    "{code}\n",
    "\n",
    "\n",
    "_, _, tmp_img =run_bt(cerebro=cerebro, date={DATE}, market_name='{market_name}', save_img={SAVE_PLT}, tckr_symbl='{tckr_symbl}', interval='{interval}', auto_period='{AUTO_PERIOD}', period='{period}')\n",
    "''' \n",
    "    tmp_img = \"\"\n",
    "    write_output(code)\n",
    "    output = io.StringIO()\n",
    "    sys_stdout = sys.stdout\n",
    "    sys.stdout = output\n",
    "    try:\n",
    "        # Execute the code into its own namespace\n",
    "        namespace = {}\n",
    "        exec(output_code, namespace)\n",
    "        tmp_img = namespace.get(\"tmp_img\", None)   # ✅ retrieve from namespace\n",
    "    finally:\n",
    "        sys.stdout = sys_stdout\n",
    "\n",
    "    return output.getvalue(), tmp_img"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "e94c2b6b",
   "metadata": {},
   "source": [
    "## Gradio interface"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "94dde64e",
   "metadata": {},
   "outputs": [],
   "source": [
    "%matplotlib inline\n",
    "market_list = list(MARKET_TO_TICKER.keys())\n",
    "with gr.Blocks() as ui:\n",
    "    gr.Markdown(\"## Convert Written Strategies into Python Code\")\n",
    "    with gr.Row():\n",
    "        strategy_msg = gr.Textbox( value=\"\", label=\"Enter the description of your strategy. \", lines=10)\n",
    "        code = gr.Textbox(label=\"Python code:\", lines=10)\n",
    "    with gr.Row():\n",
    "         gen_strategy = gr.Button(\"Generate Strategy\")       \n",
    "         run_py = gr.Button(\"Run Python Code \", visible=True)\n",
    "    with gr.Row():\n",
    "        with gr.Column():\n",
    "            model = gr.Dropdown([\"GPT\", \"Claude\", \"Deepseek\", \"Gimini\",\"Qween2\", \"Qween3\", \"Grok4\"], label=\"Select model\", value=\"Deepseek\")\n",
    "            market = gr.Dropdown(market_list, label=\"Stock Name\", value=\"S&P 500 ETF\")\n",
    "            #date = gr.Textbox( value=\"2025-10-10\", label=\"End Date (yyyy-mm-dd)\", placeholder=\"yyyy-mm-dd\")\n",
    "            interval = gr.Dropdown([\"1m\",\"2m\", \"5m\", \"15m\", \"30m\", \"1h\",\"1d\"], value=\"1d\", label=\"Interval\")\n",
    "            #period = gr.Dropdown([\"30d\", \"10d\", \"60d\"], value=\"60d\", label=\"Period\")\n",
    "        with gr.Row():\n",
    "            py_out = gr.TextArea(label=\"Python result:\", elem_classes=[\"python\"])\n",
    "    with gr.Column():    \n",
    "        #image_output = gr.Image(type=\"numpy\", label=\"Chart\")\n",
    "        image_output = gr.Gallery(\n",
    "            label=\"Charts\", \n",
    "            show_label=True, \n",
    "            elem_id=\"gallery\",\n",
    "            columns=2, \n",
    "            height=\"auto\"     # Height parameter\n",
    "        )\n",
    "\n",
    "    # Select and send msg to create python outpu\n",
    "    gen_strategy.click(stream_manager, inputs=[strategy_msg, model], outputs=[code])\n",
    "    run_py.click(execute_python, inputs=[code, market, interval] , outputs=[py_out, image_output])\n",
    "            \n",
    "ui.launch(inbrowser=True, share=True, debug=True)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c3951dbd",
   "metadata": {},
   "source": [
    "## On work\n",
    "\n",
    "Format backtrading strategies for doing multi prompt learning."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "e82f32e8",
   "metadata": {},
   "outputs": [],
   "source": [
    "import inspect\n",
    "from bt_strategies import SmaCross\n",
    "import re\n",
    "# VERSION not working\n",
    "def format_class(strategy):\n",
    "    def replace_docstring(match):\n",
    "    # Replace with cleaned docstring\n",
    "        if remaining_doc:\n",
    "            return f'\"\"\"\\n{remaining_doc}\\n    \"\"\"'\n",
    "        else:\n",
    "            return '\"\"\"\"\"\"'  # Empty docstring\n",
    "    source_code = inspect.getsource(strategy)\n",
    "    #print(source_code)\n",
    "    docstring = SmaCross.__doc__\n",
    "    user_prompt_match = re.search(r'User prompt:\\s*\"([^\"]+)\"', docstring)\n",
    "    user_prompt = user_prompt_match.group(1) if user_prompt_match else \"No user prompt found.\"\n",
    "\n",
    "    call_match = re.search(r'Call:\\s*(.+)', docstring)\n",
    "    call_line = call_match.group(1) if call_match else \"cerebro.addstrategy(NotFoundStrategy)\"\n",
    "    \n",
    "    # Clean docstring\n",
    "    remaining_doc = re.sub(r'User prompt:\\s*\"[^\"]+\"\\s*\\n?', '', docstring)\n",
    "    remaining_doc = re.sub(r'Call:\\s*.+\\s*\\n?', '', remaining_doc)\n",
    "    remaining_doc = remaining_doc.strip()\n",
    "    \n",
    "    pattern = r'(\"\"\".*?\"\"\"|\\'\\'\\'.*?\\'\\'\\')'\n",
    "    clean_source = re.sub(pattern, replace_docstring, source_code, count=1, flags=re.DOTALL)\n",
    "\n",
    "\n",
    "    # ✅ Final formatted output\n",
    "    final_output = f'''\n",
    "# User prompt:\n",
    "# \"{user_prompt}\"\n",
    "\n",
    "# Generated Python code:\n",
    "import backtrader as bt\n",
    "{clean_source}\n",
    "# Initialize Cerebro\n",
    "cerebro = bt.Cerebro()\n",
    "{call_line}\n",
    "'''\n",
    "    return final_output\n",
    "\n",
    "print (format_class(SmaCross))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "f2b9ef6e",
   "metadata": {},
   "outputs": [],
   "source": [
    "import inspect\n",
    "from bt_strategies import SmaCross\n",
    "import re\n",
    "\n",
    "def format_class(strategy):\n",
    "    source_code = inspect.getsource(strategy)\n",
    "    #print(source_code)\n",
    "    docstring = SmaCross.__doc__\n",
    "    user_prompt_match = re.search(r'User prompt:\\s*\"([^\"]+)\"', docstring)\n",
    "    user_prompt = user_prompt_match.group(1) if user_prompt_match else \"No user prompt found.\"\n",
    "\n",
    "    call_match = re.search(r'Call:\\s*(.+)', docstring)\n",
    "    call_line = call_match.group(1) if call_match else \"cerebro.addstrategy(NotFoundStrategy)\"\n",
    "\n",
    "\n",
    "    # ✅ Final formatted output\n",
    "    final_output = f'''\n",
    "    # User prompt:\n",
    "    # \"{user_prompt}\"\n",
    "\n",
    "    # Generated Python code:\n",
    "    import backtrader as bt\n",
    "    {source_code}\n",
    "    # Initialize Cerebro\n",
    "    cerebro = bt.Cerebro()\n",
    "    {call_line}\n",
    "    '''\n",
    "    return final_output\n",
    "\n",
    "print (format_class(SmaCross))"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "llms",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.11.13"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}