File size: 31,244 Bytes
89c85fb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3097a6c
 
 
89c85fb
3097a6c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
89c85fb
 
3097a6c
89c85fb
 
3097a6c
 
89c85fb
3097a6c
89c85fb
3097a6c
89c85fb
 
3097a6c
 
 
89c85fb
 
3097a6c
 
 
89c85fb
 
3097a6c
 
 
 
 
 
 
 
 
89c85fb
 
3097a6c
 
 
 
 
 
 
 
 
89c85fb
 
 
3097a6c
89c85fb
 
 
 
 
 
 
 
 
 
3097a6c
89c85fb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3097a6c
89c85fb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3097a6c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
89c85fb
 
 
 
 
 
 
 
 
 
 
3097a6c
 
 
 
 
 
 
 
89c85fb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3097a6c
89c85fb
 
 
 
 
 
3097a6c
89c85fb
 
3097a6c
89c85fb
 
 
 
 
 
 
 
 
3097a6c
89c85fb
 
 
 
 
 
 
 
 
3097a6c
89c85fb
3097a6c
89c85fb
 
 
 
 
 
 
 
 
d2cb9df
 
89c85fb
 
 
d2cb9df
 
 
 
 
 
 
 
 
 
 
 
89c85fb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d2cb9df
89c85fb
 
 
 
 
 
 
 
 
 
 
 
 
f257889
89c85fb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3097a6c
 
 
 
 
89c85fb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f257889
89c85fb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3097a6c
 
 
 
 
 
 
 
89c85fb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3097a6c
89c85fb
3097a6c
 
89c85fb
 
 
 
 
 
 
 
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
import gradio as gr
import yfinance as yf
import pandas as pd
import numpy as np
from datetime import datetime
import plotly.graph_objects as go
from plotly.subplots import make_subplots
import pixeltable as pxt
from pixeltable.functions import openai
import json
import os
import getpass
from typing import Dict, Any

# Set up OpenAI API key
if 'OPENAI_API_KEY' not in os.environ:
    os.environ['OPENAI_API_KEY'] = getpass.getpass('Enter your OpenAI API key: ')

class NumpyEncoder(json.JSONEncoder):
    def default(self, obj):
        if isinstance(obj, (np.int_, np.intc, np.intp, np.int8,
            np.int16, np.int32, np.int64, np.uint8,
            np.uint16, np.uint32, np.uint64)):
            return int(obj)
        elif isinstance(obj, (np.float_, np.float16, np.float32, np.float64)):
            return float(obj)
        elif isinstance(obj, (np.ndarray,)):
            return obj.tolist()
        return json.JSONEncoder.default(self, obj)

def safe_json_serialize(obj):
    return json.dumps(obj, cls=NumpyEncoder)

def calculate_basic_indicators(data: pd.DataFrame) -> pd.DataFrame:
    df = data.copy()
    
    # Moving averages
    df['MA20'] = df['Close'].rolling(window=20).mean()
    df['MA50'] = df['Close'].rolling(window=50).mean()
    df['MA200'] = df['Close'].rolling(window=200).mean()
    
    # RSI
    delta = df['Close'].diff()
    gain = (delta.where(delta > 0, 0)).rolling(window=14).mean()
    loss = (-delta.where(delta < 0, 0)).rolling(window=14).mean()
    rs = gain / loss
    df['RSI'] = 100 - (100 / (1 + rs))
    
    # MACD
    exp1 = df['Close'].ewm(span=12, adjust=False).mean()
    exp2 = df['Close'].ewm(span=26, adjust=False).mean()
    df['MACD'] = exp1 - exp2
    df['MACD_Signal'] = df['MACD'].ewm(span=9, adjust=False).mean()
    
    return df.ffill().bfill()

@pxt.udf
def generate_analysis_prompt(data: str, analysis_type: str, time_horizon: str, 
                           risk_tolerance: str, investment_style: str, 
                           technical_depth: str) -> list[dict]:
    """Generate a structured prompt for AI analysis"""
    
    # Create specific guidance based on parameters
    time_horizon_guidance = {
        'short': 'Focus on short-term trading opportunities within 1-3 months. Emphasize technical signals and immediate catalysts.',
        'medium': 'Balance short-term opportunities with medium-term trends over 3-12 months. Consider both technical and fundamental factors.',
        'long': 'Prioritize long-term growth potential over 1+ years. Emphasize fundamental analysis and strategic positioning.'
    }
    
    risk_tolerance_guidance = {
        'conservative': 'Prioritize capital preservation. Focus on stable, large-cap stocks with strong fundamentals. Suggest conservative options strategies like covered calls.',
        'moderate': 'Balance growth opportunities with risk management. Consider mid-cap stocks and moderate options strategies.',
        'aggressive': 'Seek high-growth opportunities. Include small-cap stocks and more aggressive options strategies in the analysis.'
    }
    
    investment_style_guidance = {
        'value': 'Focus on valuation metrics, margin of safety, and undervalued opportunities.',
        'growth': 'Emphasize revenue growth, market expansion, and future potential.',
        'momentum': 'Focus on price trends, relative strength, and technical indicators.',
        'balanced': 'Consider both value and growth factors, maintaining a balanced perspective.',
        'income': 'Prioritize dividend yield, payout ratio, and income-generating options strategies.'
    }
    
    analysis_depth = {
        'comprehensive': 'Provide detailed analysis across all categories.',
        'quantitative': 'Focus on numerical metrics and statistical analysis.',
        'technical': 'Emphasize technical analysis and chart patterns.'
    }
    
    technical_guidance = {
        'basic': 'Focus on essential technical indicators (MA, RSI, MACD).',
        'advanced': 'Include advanced technical analysis including Fibonacci levels, Elliott Wave patterns, and advanced options analysis.'
    }

    system_prompt = f'''You are a senior investment advisor and market analyst with decades of experience, holding CFA and CMT certifications. Provide analysis tailored to the following parameters:

TIME HORIZON: {time_horizon.upper()}
{time_horizon_guidance[time_horizon]}

RISK PROFILE: {risk_tolerance.upper()}
{risk_tolerance_guidance[risk_tolerance]}

INVESTMENT STYLE: {investment_style.upper()}
{investment_style_guidance[investment_style]}

ANALYSIS FOCUS: {analysis_type.upper()}
{analysis_depth[analysis_type]}

TECHNICAL DEPTH: {technical_depth.upper()}
{technical_guidance[technical_depth]}

Structure your response using EXACTLY the following format and sections:

SUMMARY
Provide a clear 2-3 sentence executive summary aligned with the specified time horizon ({time_horizon}) and risk tolerance ({risk_tolerance}).

TECHNICAL ANALYSIS
{technical_guidance[technical_depth]}
β€’ Moving Averages: Analyze trends with emphasis on {time_horizon} timeframe
β€’ RSI Analysis: Current RSI level and implications
β€’ MACD Analysis: Signal trends relevant to {time_horizon} horizon
β€’ Volume Analysis: Notable volume patterns and implications
{"β€’ Advanced Patterns: Fibonacci levels, Elliott Wave analysis" if technical_depth == "advanced" else ""}

MARKET CONTEXT
β€’ Sector Analysis: {"Long-term industry trends and positioning" if time_horizon == "long" else "Short-term sector momentum" if time_horizon == "short" else "Medium-term sector outlook"}
β€’ {"Fundamental Drivers: Key growth catalysts" if investment_style == "growth" else "Value Metrics: Key valuation catalysts" if investment_style == "value" else "Market Dynamics: Key price catalysts"}
β€’ Economic Impact: Factors relevant to {time_horizon} horizon

RISKS
β€’ Identify and quantify risks specific to {risk_tolerance} risk tolerance
β€’ Focus on {time_horizon} horizon risks
β€’ {"Include volatility analysis" if technical_depth == "advanced" else ""}

OPPORTUNITIES
β€’ Align opportunities with {investment_style} style
β€’ Focus on {time_horizon} timeline
β€’ Match risk/reward to {risk_tolerance} profile

OPTIONS STRATEGY
{"β€’ Advanced Options Analysis: Complex strategies and volatility analysis" if technical_depth == "advanced" else "β€’ Basic Options Strategies: Simple hedging and income generation"}
β€’ Tailor strategies to {risk_tolerance} risk tolerance
β€’ Focus on {time_horizon} expiration cycles
β€’ Match strategies to {investment_style} style objectives

RECOMMENDATION
β€’ Provide specific recommendations aligned with:
  - {time_horizon.capitalize()} time horizon
  - {risk_tolerance.capitalize()} risk tolerance
  - {investment_style.capitalize()} investment style
β€’ Include position sizing appropriate for risk level
β€’ Specify entry, exit, and stop-loss levels
β€’ {"Include advanced technical levels" if technical_depth == "advanced" else "Focus on key support/resistance levels"}

IMPORTANT: This analysis is for informational purposes only. All investments carry risk. Please consult with a licensed financial advisor before making investment decisions.'''

    return [
        {'role': 'system', 'content': system_prompt},
        {'role': 'user', 'content': f'Analyze this market data considering the specified parameters:\n{data}'}
    ]

def parse_analysis_response(response: str) -> Dict[str, str]:
    """Parse the structured AI response into sections with support for markdown formatting"""
    sections = {
        'SUMMARY': None,
        'TECHNICAL ANALYSIS': None,
        'MARKET CONTEXT': None,
        'RISKS': None,
        'OPPORTUNITIES': None,
        'OPTIONS STRATEGY': None,
        'RECOMMENDATION': None
    }
    
    current_section = None
    buffer = []
    
    if not response or not response.strip():
        return {k: "Analysis not available" for k in sections.keys()}
    
    for line in response.split('\n'):
        line = line.strip()
        
        matched_section = None
        for section in sections.keys():
            # Remove asterisks and check for exact match
            cleaned_line = line.replace('*', '').strip()
            if cleaned_line == section:
                matched_section = section
                break
        
        if matched_section:
            # Save previous section if exists
            if current_section and buffer:
                sections[current_section] = '\n'.join(buffer).strip()
            current_section = matched_section
            buffer = []
        elif current_section and line:
            # Clean up markdown formatting in content
            cleaned_content = line.replace('*', '').strip()
            if cleaned_content:  # Only add non-empty lines
                buffer.append(cleaned_content)
    
    if current_section and buffer:
        sections[current_section] = '\n'.join(buffer).strip()
    
    section_messages = {
        'SUMMARY': 'Market analysis summary not available',
        'TECHNICAL ANALYSIS': 'Technical analysis not available',
        'MARKET CONTEXT': 'Market context information not available',
        'RISKS': 'Risk assessment not available',
        'OPPORTUNITIES': 'Opportunity analysis not available',
        'OPTIONS STRATEGY': 'Options trading analysis not available',
        'RECOMMENDATION': 'Investment recommendation not available'
    }
    
    for key in sections:
        if sections[key] is None or not sections[key].strip():
            sections[key] = section_messages[key]
    
    return sections

def create_visualization(data: pd.DataFrame, technical_depth: str) -> go.Figure:
    fig = make_subplots(
        rows=3 if technical_depth == 'advanced' else 2,
        cols=1,
        shared_xaxes=True,
        vertical_spacing=0.05,
        subplot_titles=('Price & Moving Averages', 'Volume', 'RSI' if technical_depth == 'advanced' else None)
    )

    fig.add_trace(
        go.Candlestick(
            x=data.index,
            open=data['Open'],
            high=data['High'],
            low=data['Low'],
            close=data['Close'],
            name='Price',
            increasing_line_color='#26A69A',
            decreasing_line_color='#EF5350'
        ),
        row=1, col=1
    )

    colors = {'MA20': '#1E88E5', 'MA50': '#FFC107', 'MA200': '#7B1FA2'}
    for ma, color in colors.items():
        fig.add_trace(
            go.Scatter(
                x=data.index,
                y=data[ma],
                name=ma,
                line=dict(color=color, width=1.5)
            ),
            row=1, col=1
        )

    colors = ['#26A69A' if close >= open_price else '#EF5350' 
         for close, open_price in zip(data['Close'].values, data['Open'].values)]
    fig.add_trace(
        go.Bar(
            x=data.index,
            y=data['Volume'],
            name='Volume',
            marker_color=colors
        ),
        row=2, col=1
    )

    if technical_depth == 'advanced':
        fig.add_trace(
            go.Scatter(
                x=data.index,
                y=data['RSI'],
                name='RSI',
                line=dict(color='#7C4DFF', width=1.5)
            ),
            row=3, col=1
        )
        
        fig.add_hline(y=70, line_dash="dash", line_color="red", row=3, col=1)
        fig.add_hline(y=30, line_dash="dash", line_color="green", row=3, col=1)

    fig.update_layout(
        height=800,
        template='plotly_white',
        showlegend=True,
        legend=dict(
            orientation="h",
            yanchor="bottom",
            y=1.02,
            xanchor="right",
            x=1
        )
    )
    
    fig.update_yaxes(title_text="Price", row=1, col=1)
    fig.update_yaxes(title_text="Volume", row=2, col=1)
    if technical_depth == 'advanced':
        fig.update_yaxes(title_text="RSI", row=3, col=1)

    return fig

def process_outputs(ticker_symbol, analysis_type, time_horizon, risk_tolerance,
                   investment_style, technical_depth, include_market_context=True,
                   max_positions=3):
    try:
        # Initialize Pixeltable
        pxt.drop_dir('financial_analysis', force=True)
        pxt.create_dir('financial_analysis')

        data_table = pxt.create_table(
            'financial_analysis.stock_data',
            {
                'ticker': pxt.StringType(),
                'data': pxt.StringType(),
                'timestamp': pxt.TimestampType()
            }
        )

        # Fetch and process data
        stock = yf.Ticker(ticker_symbol.strip().upper())
        market_data = stock.history(period='1y')
        if market_data.empty:
            raise ValueError("No data found for the specified ticker symbol.")
        options_data = stock.options  # Get available expiration dates

        if len(options_data) > 0:
            nearest_expiry = options_data[0]
            opt_chain = stock.option_chain(nearest_expiry)
            options_info = {
                'Nearest Expiry': nearest_expiry,
                'Call Volume': int(opt_chain.calls['volume'].sum()),
                'Put Volume': int(opt_chain.puts['volume'].sum()),
                'Put/Call Ratio': float(opt_chain.puts['volume'].sum() / opt_chain.calls['volume'].sum()),
                'Implied Volatility': float(opt_chain.calls['impliedVolatility'].mean())
            }
        else:
            options_info = {
                'Nearest Expiry': 'N/A',
                'Call Volume': 0,
                'Put Volume': 0,
                'Put/Call Ratio': 0,
                'Implied Volatility': 0
            }

        technical_data = calculate_basic_indicators(market_data)
        market_data_json = technical_data.to_json(date_format='iso')

        # Store data and generate analysis
        data_table.insert([{
            'ticker': ticker_symbol.upper(),
            'data': market_data_json,
            'timestamp': datetime.now()
        }])

        data_table['prompt'] = generate_analysis_prompt(
            data_table.data,
            analysis_type,
            time_horizon,
            risk_tolerance,
            investment_style,
            technical_depth
        )
        data_table['analysis'] = openai.chat_completions(
            messages=data_table.prompt,
            model='gpt-4o-mini-2024-07-18',
            temperature=0.7,
            max_tokens=1000
        )

        try:
            analysis_text = data_table.select(
                analysis=data_table.analysis.choices[0].message.content
            ).tail(1)['analysis'][0]
            parsed_analysis = parse_analysis_response(analysis_text)
        except Exception as analysis_error:
            print(f"Analysis error: {str(analysis_error)}")
            parsed_analysis = parse_analysis_response("")  # This will return default messages

        # Prepare company info with proper JSON formatting
        company_info_data = {
            'Name': str(stock.info.get('longName', 'N/A')),
            'Sector': str(stock.info.get('sector', 'N/A')),
            'Industry': str(stock.info.get('industry', 'N/A')),
            'Exchange': str(stock.info.get('exchange', 'N/A'))
        }

        raw_llm_output = ""
        try:
            raw_llm_output = data_table.select(
                analysis=data_table.analysis.choices[0].message.content
            ).tail(1)['analysis'][0]
            parsed_analysis = parse_analysis_response(raw_llm_output)
        except Exception as analysis_error:
            print(f"Analysis error: {str(analysis_error)}")
            parsed_analysis = parse_analysis_response("")
            raw_llm_output = f"Error processing analysis: {str(analysis_error)}"

        try:
            current_price = float(technical_data['Close'].iloc[-1])
            previous_price = float(technical_data['Close'].iloc[-2])
            daily_change = float((current_price / previous_price - 1) * 100)
            volume = int(technical_data['Volume'].iloc[-1])
            rsi = float(technical_data['RSI'].iloc[-1])
        except (IndexError, KeyError, TypeError):
            current_price = daily_change = volume = rsi = 0

        market_stats_data = {
            'Current Price': f"${current_price:.2f}",
            'Daily Change': f"{daily_change:.2f}%",
            'Volume': f"{volume:,}",
            'RSI': f"{rsi:.2f}"
        }

        technical_data_with_time = technical_data.reset_index()
        technical_data_with_time['Date'] = technical_data_with_time['Date'].dt.strftime('%Y-%m-%d %H:%M:%S')

        # Create visualization
        plot = create_visualization(technical_data, technical_depth)

        return (
            json.dumps(company_info_data),
            json.dumps(market_stats_data),
            json.dumps(options_info),  # Add options info to return values
            plot,
            parsed_analysis['SUMMARY'],
            parsed_analysis['TECHNICAL ANALYSIS'],
            parsed_analysis['MARKET CONTEXT'],
            parsed_analysis['RISKS'],
            parsed_analysis['OPPORTUNITIES'],
            parsed_analysis['OPTIONS STRATEGY'],  # Add options strategy
            parsed_analysis['RECOMMENDATION'],
            technical_data_with_time,
            raw_llm_output
        )

    except Exception as e:
        error_msg = f"Error processing data: {str(e)}"
        empty_json = json.dumps({})
        no_data_msg = "Analysis not available due to data processing error"
        empty_df = pd.DataFrame()
        
        return (
            empty_json,
            empty_json,
            empty_json,
            None,
            no_data_msg,
            no_data_msg,
            no_data_msg,
            no_data_msg,
            no_data_msg,
            no_data_msg,
            no_data_msg,
            empty_df,
            f"Error occurred: {str(e)}"
        )

def create_interface() -> gr.Blocks:
    """Create the production-ready Gradio interface"""
    with gr.Blocks(theme=gr.themes.Base()) as demo:
        # Header      
        gr.Markdown(
            """
            # πŸ“ˆ AI Financial Analysis Platform
            
            AI-powered market analysis and technical indicators powered by OpenAI GPT models and Pixeltable.
            """
        )

        gr.HTML(
            """
            <div style="background-color: #FEE2E2; border: 1px solid #FECACA; color: #991B1B; border-radius: 8px; padding: 15px; margin: 15px 0;">
                <strong>⚠️ Important Data Reliability Notice:</strong>
                <p style="margin: 8px 0;">
                    This is a demonstration platform showcasing how to leverage LLMs for financial analysis. 
                    The accuracy of information, data retrieved from yfinance, and calculated metrics are NOT guaranteed. 
                    Use at your own risk. The creators and operators of this tool are not responsible for any financial losses or decisions made based on this analysis. This tool is intended for demonstration and educational purposes only.
                </p>
            </div>
            """
        )
        with gr.Row():
            with gr.Column():
                with gr.Accordion("🎯 What does it do?", open=False):
                    gr.Markdown("""
                    This platform provides comprehensive financial analysis tools:
                    
                    1. πŸ“Š **Technical Analysis**: Advanced indicators, e.g. RSI, and MACD
                    2. πŸ€– **AI-Powered Insights**: Intelligent market analysis/recommendations
                    3. πŸ“ˆ **Interactive Charts**: Visual representation of movements/indicators
                    4. πŸ’‘ **Investment Context**: Market conditions and sector analysis
                    5. ⚑ **Real-time Data**: Up-to-date information through Yahoo Finance
                    6. 🎯 **Personalized Analysis**: Tailored to your style/risk tolerance
                    """)
            
            with gr.Column():
                with gr.Accordion("πŸ› οΈ How does it work?", open=False):
                    gr.Markdown("""
                    The platform leverages several advanced technologies:
                    
                    1. πŸ“¦ **Data Processing**: Pixeltable manages and orchestrate data
                    2. πŸ” **Technical Indicators**: Custom algorithms calculate market metrics
                    3. πŸ€– **AI Analysis**: Advanced language models provide market insights
                    4. πŸ“Š **Visualization**: Interactive charts using Plotly
                    5. πŸ”„ **Real-time Updates**: Direct connection to market data feeds
                    6. πŸ’Ύ **Data Persistence**: Reliable storage and retrieval of insights
                    """)

        # Disclaimer
        gr.HTML(
            """
            <div style="background-color: #FFF4E5; border: 1px solid #FFE0B2; color: #663C00; border-radius: 8px; padding: 15px; margin: 15px 0;">
                <strong>⚠️ Disclaimer:</strong>
                <p style="margin: 8px 0;">
                    This tool provides financial analysis for informational purposes only and should not be considered as financial advice, please:
                </p>
                <ul style="margin: 8px 0;">
                    <li>Consult with qualified financial advisors</li>
                    <li>Conduct your own research</li>
                    <li>Consider your personal financial situation</li>
                    <li>Be aware that past performance does not guarantee future results</li>
                    <li>Understand that all investments carry risk</li>
                </ul>
            </div>
            """
        )

        with gr.Row():
            # Left sidebar for inputs
            with gr.Column(scale=1):
                with gr.Row():
                    gr.Markdown("### πŸ“Š Analysis Parameters")
                with gr.Row():
                    ticker_input = gr.Textbox(
                        label="Stock Ticker",
                        placeholder="e.g., AAPL",
                        max_lines=1
                    )
                    analysis_type = gr.Radio(
                        choices=['comprehensive', 'quantitative', 'technical'],
                        label="Analysis Type",
                        value='comprehensive'
                    )
                    technical_depth = gr.Radio(
                        choices=['basic', 'advanced'],
                        label="Technical Depth",
                        value='advanced'
                    )
                
                with gr.Row():
                    gr.Markdown("### 🎯 Investment Profile")
                with gr.Row():
                    time_horizon = gr.Radio(
                        choices=['short', 'medium', 'long'],
                        label="Time Horizon",
                        value='medium'
                    )
                    risk_tolerance = gr.Radio(
                        choices=['conservative', 'moderate', 'aggressive'],
                        label="Risk Tolerance",
                        value='moderate'
                    )
                    investment_style = gr.Dropdown(
                        choices=['value', 'growth', 'momentum', 'balanced', 'income'],
                        label="Investment Style",
                        value='balanced'
                    )

                analyze_btn = gr.Button("πŸ“Š Analyze Stock", variant="primary")

        with gr.Row():
            with gr.Column(scale=3):
                with gr.Tabs() as tabs:
                    with gr.TabItem("πŸ“Š Analysis Dashboard"):
                        # Top row with company info and market stats
                        with gr.Row(equal_height=True):
                            with gr.Column(scale=1):
                                company_info = gr.JSON(
                                    label="Company Information",
                                    height=150
                                )
                            with gr.Column(scale=1):
                                market_stats = gr.JSON(
                                    label="Market Statistics",
                                    height=150
                                )
                            with gr.Column(scale=1):
                                options_info = gr.JSON(
                                    label="Options Market Data",
                                    height=150
                                )
                        
                    with gr.TabItem("πŸ“‘ Historical Data"):
                        technical_data = gr.DataFrame(
                            headers=["Date", "Open", "High", "Low", "Close", 
                                   "Volume", "MA20", "MA50", "MA200", "RSI", 
                                   "MACD", "MACD_Signal"],
                        )
                    
                    with gr.TabItem("πŸ” Debug View"):
                        raw_output = gr.Textbox(
                            label="Raw LLM Output",
                            lines=10,
                            max_lines=20,
                            show_label=True,
                            interactive=False
                        )
                        gr.Markdown("""
                        ### Debug Information
                        This tab shows the raw output from the language model before parsing.
                        Use this to diagnose any issues with the analysis display.
                        """)
         # Technical analysis chart
        with gr.Row():
            with gr.Column(scale=1):
                with gr.Row():
                    gr.Markdown("### πŸ“ˆ Technical Analysis Chart")
                
                with gr.Row():
                    plot_output = gr.Plot()

        # AI Analysis section
        with gr.Row():
            with gr.Column(scale=2):
                with gr.Row():
                    gr.Markdown("### πŸ€– AI Analysis")
                    
                with gr.Row():
                    summary = gr.Textbox(
                        label="Executive Summary",
                        lines=3,
                        max_lines=5,
                        show_label=True
                    )
                    
                with gr.Row():
                    with gr.Column(scale=1):
                        tech_analysis = gr.Textbox(
                            label="Technical Analysis",
                            lines=8,
                            max_lines=10,
                            show_label=True
                        )
                        market_context = gr.Textbox(
                            label="Market Context",
                            lines=4,
                            max_lines=6,
                            show_label=True
                        )
                    
                    with gr.Column(scale=1):
                        risks = gr.Textbox(
                            label="Key Risks",
                            lines=5,
                            max_lines=7,
                            show_label=True
                        )
                        opportunities = gr.Textbox(
                            label="Key Opportunities",
                            lines=5,
                            max_lines=7,
                            show_label=True
                        )

                with gr.Row():
                    options_strategy = gr.Textbox(
                        label="Options Trading Strategy",
                        lines=8,
                        max_lines=10,
                        show_label=True
                    )
                
                with gr.Row():
                    recommendation = gr.Textbox(
                        label="Investment Recommendation",
                        lines=3,
                        max_lines=5,
                        show_label=True
                    )
        
        gr.Examples(
            examples=[
                ["AAPL", "comprehensive", "medium", "moderate", "balanced", "advanced"],
                ["MSFT", "technical", "short", "aggressive", "momentum", "basic"],
                ["GOOGL", "quantitative", "long", "conservative", "value", "advanced"]
            ],
            inputs=[
                ticker_input, analysis_type, time_horizon, risk_tolerance,
                investment_style, technical_depth
            ]
        )

        # Footer
        gr.HTML(
            """
            <div style="margin-top: 2rem; padding-top: 1rem; border-top: 1px solid #e5e7eb;">
                <div style="display: flex; justify-content: space-between; align-items: center; flex-wrap: wrap; gap: 1rem;">
                    <div style="flex: 1;">
                        <h4 style="margin: 0; color: #374151;">πŸš€ Built with Pixeltable</h4>
                        <p style="margin: 0.5rem 0; color: #6b7280;">
                            Open Source AI Data infrastructure for building intelligent applications.
                        </p>
                    </div>
                    <div style="flex: 1;">
                        <h4 style="margin: 0; color: #374151;">πŸ”— Resources</h4>
                        <div style="display: flex; gap: 1.5rem; margin-top: 0.5rem;">
                            <a href="https://github.com/pixeltable/pixeltable" target="_blank" style="color: #4F46E5; text-decoration: none; display: flex; align-items: center; gap: 0.25rem;">
                                πŸ’» GitHub
                            </a>
                            <a href="https://docs.pixeltable.com" target="_blank" style="color: #4F46E5; text-decoration: none; display: flex; align-items: center; gap: 0.25rem;">
                                πŸ“š Documentation
                            </a>
                            <a href="https://huggingface.co/Pixeltable" target="_blank" style="color: #4F46E5; text-decoration: none; display: flex; align-items: center; gap: 0.25rem;">
                                πŸ€— Hugging Face
                            </a>
                        </div>
                    </div>
                </div>
                <p style="margin: 1rem 0 0; text-align: center; color: #9CA3AF; font-size: 0.875rem;">
                    Β© 2024 AI Financial Analysis Platform powered by Pixeltable. 
                    This work is licensed under the Apache License 2.0.
                </p>
            </div>
            """
        )

        analyze_btn.click(
            process_outputs,
            inputs=[
                ticker_input, analysis_type, time_horizon, risk_tolerance,
                investment_style, technical_depth
            ],
            outputs=[
                company_info, market_stats, options_info, plot_output,
                summary, tech_analysis, market_context,
                risks, opportunities, options_strategy, recommendation,
                technical_data, raw_output
            ]
        )

    return demo

if __name__ == "__main__":
    demo = create_interface()
    demo.launch()