Spaces:
Sleeping

File size: 38,546 Bytes
e7cf9be
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""
Educational content generation and market insights.
"""
import pandas as pd
import numpy as np
from typing import Dict, List, Optional, Any
import logging
import sys
from pathlib import Path

# Add src to path for imports
sys.path.append(str(Path(__file__).parent.parent))

try:
    from analysis.investment_scenarios import InvestmentAnalyzer
except ImportError:
    # Fallback for when running tests
    InvestmentAnalyzer = None

logger = logging.getLogger(__name__)


class EducationalInsights:
    """Generate educational content and market insights for ordinary investors."""
    
    def __init__(self):
        """Initialize the educational insights generator."""
        if InvestmentAnalyzer:
            self.analyzer = InvestmentAnalyzer()
        else:
            self.analyzer = None
        self.market_contexts = {
            '^GSPC': {
                'name': 'S&P 500',
                'description': 'Tracks the 500 largest US companies by market value',
                'significance': 'Often considered the best representation of the overall US stock market'
            },
            '^FTSE': {
                'name': 'FTSE 100',
                'description': 'Tracks the 100 largest UK companies',
                'significance': 'Key indicator of UK economic health and market performance'
            },
            '^N225': {
                'name': 'Nikkei 225',
                'description': 'Tracks 225 major Japanese companies',
                'significance': 'Primary indicator of Japanese stock market performance'
            },
            '^DJI': {
                'name': 'Dow Jones',
                'description': 'Tracks 30 major US companies',
                'significance': 'One of the oldest and most watched US market indicators'
            },
            '^IXIC': {
                'name': 'NASDAQ',
                'description': 'Tracks technology-heavy companies',
                'significance': 'Key indicator for technology and growth company performance'
            },
            '^GDAXI': {
                'name': 'DAX',
                'description': 'Tracks 40 major German companies',
                'significance': 'Primary indicator of German and European economic health'
            },
            '000001.SS': {
                'name': 'Shanghai Composite',
                'description': 'Tracks all stocks on Shanghai Stock Exchange',
                'significance': 'Key indicator of Chinese market performance'
            },
            '^HSI': {
                'name': 'Hang Seng',
                'description': 'Tracks major Hong Kong companies',
                'significance': 'Important indicator for Asian markets and Chinese companies'
            },
            '^AXJO': {
                'name': 'ASX 200',
                'description': 'Tracks 200 largest Australian companies',
                'significance': 'Primary indicator of Australian market performance'
            },
            '^FCHI': {
                'name': 'CAC 40',
                'description': 'Tracks 40 major French companies',
                'significance': 'Key indicator of French and European market health'
            },
            '^GSPTSE': {
                'name': 'TSX Composite',
                'description': 'Tracks major Canadian companies',
                'significance': 'Primary indicator of Canadian market performance'
            }
        }
    
    def generate_trend_insight(self, data: pd.DataFrame, symbol: str) -> str:
        """Analyze data and generate plain-language trend insights.
        
        Args:
            data: Historical price data
            symbol: Market index symbol
            
        Returns:
            Educational insight text
        """
        if data.empty:
            return "No data available for analysis."
        
        try:
            # Calculate basic metrics
            start_price = data['close_price'].iloc[0]
            end_price = data['close_price'].iloc[-1]
            
            # Validate prices to avoid division by zero
            if start_price == 0 or pd.isna(start_price) or pd.isna(end_price):
                return "Unable to calculate returns due to invalid price data."
            
            total_return = ((end_price / start_price) - 1) * 100
            
            # Calculate volatility (standard deviation of daily returns)
            daily_returns = data['close_price'].pct_change().dropna()
            volatility = daily_returns.std() * np.sqrt(252) * 100  # Annualized
            
            # Determine trend direction
            if total_return > 10:
                trend = "strong upward"
            elif total_return > 0:
                trend = "modest upward"
            elif total_return > -10:
                trend = "modest downward"
            else:
                trend = "strong downward"
            
            # Generate insight
            market_name = self.market_contexts.get(symbol, {}).get('name', symbol)
            
            insight = f"""
            **Market Trend Analysis for {market_name}**
            
            Over the selected period, this market showed a **{trend} trend** with a total return of **{total_return:.1f}%**.
            
            **What this means for investors:**
            - The market {'gained' if total_return > 0 else 'lost'} {abs(total_return):.1f}% in value over this period
            - Volatility was {volatility:.1f}% annually, which is {'high' if volatility > 20 else 'moderate' if volatility > 15 else 'low'}
            - {'This suggests steady growth with manageable risk' if 0 < total_return < 15 and volatility < 20 else 'This indicates significant market movements' if abs(total_return) > 15 or volatility > 25 else 'This shows typical market behavior'}
            
            **Investment Lesson:**
            {'Markets can provide positive returns over time, but patience is key.' if total_return > 0 else 'Markets can decline, highlighting the importance of diversification and long-term thinking.'}
            """
            
            return insight.strip()
            
        except Exception as e:
            logger.error(f"Error generating trend insight: {e}")
            return "Unable to generate trend analysis at this time."
    
    def generate_comparison_insight(self, data_dict: Dict[str, pd.DataFrame]) -> str:
        """Generate insights for multi-index comparison.
        
        Args:
            data_dict: Dictionary mapping symbols to their data
            
        Returns:
            Comparison insight text
        """
        if not data_dict or all(df.empty for df in data_dict.values()):
            return "No data available for comparison."
        
        try:
            returns = {}
            volatilities = {}
            
            for symbol, data in data_dict.items():
                if not data.empty:
                    start_price = data['close_price'].iloc[0]
                    end_price = data['close_price'].iloc[-1]
                    
                    # Skip symbols with invalid price data
                    if start_price == 0 or pd.isna(start_price) or pd.isna(end_price):
                        logger.warning(f"Skipping {symbol} in comparison: invalid price data")
                        continue
                        
                    returns[symbol] = ((end_price / start_price) - 1) * 100
                    
                    daily_returns = data['close_price'].pct_change().dropna()
                    volatilities[symbol] = daily_returns.std() * np.sqrt(252) * 100
            
            if not returns:
                return "No valid data for comparison."
            
            # Find best and worst performers
            best_performer = max(returns.keys(), key=lambda x: returns[x])
            worst_performer = min(returns.keys(), key=lambda x: returns[x])
            
            best_return = returns[best_performer]
            worst_return = returns[worst_performer]
            
            # Generate comparison insight
            insight = f"""
            **Market Comparison Analysis**
            
            **Performance Leaders:**
            - **Best Performer:** {self.market_contexts.get(best_performer, {}).get('name', best_performer)} (+{best_return:.1f}%)
            - **Weakest Performer:** {self.market_contexts.get(worst_performer, {}).get('name', worst_performer)} ({worst_return:+.1f}%)
            
            **Key Insights:**
            - Performance difference: {best_return - worst_return:.1f} percentage points
            - This shows {'significant variation' if abs(best_return - worst_return) > 20 else 'moderate variation' if abs(best_return - worst_return) > 10 else 'similar performance'} across markets
            
            **Investment Lesson:**
            Different markets can perform very differently over the same period. This is why diversification across 
            multiple markets and regions can help reduce risk while capturing growth opportunities.
            
            **What this means:**
            - Global diversification can help smooth out returns
            - No single market consistently outperforms all others
            - Regional economic factors significantly impact market performance
            """
            
            return insight.strip()
            
        except Exception as e:
            logger.error(f"Error generating comparison insight: {e}")
            return "Unable to generate comparison analysis at this time."
    
    def get_market_context(self, symbol: str) -> str:
        """Provide educational context about a specific market index.
        
        Args:
            symbol: Market index symbol
            
        Returns:
            Market context information
        """
        context = self.market_contexts.get(symbol)
        
        if not context:
            return f"Market index {symbol} - Educational information not available."
        
        return f"""
        **About {context['name']} ({symbol})**
        
        **What it tracks:** {context['description']}
        
        **Why it matters:** {context['significance']}
        
        **For investors:** This index helps you understand the performance of {context['name'].split()[0]} markets 
        and can be useful for diversification and regional exposure in your investment strategy.
        """
    
    def get_investment_basics(self) -> str:
        """Provide basic investment education content.
        
        Returns:
            Investment basics text
        """
        return """
        **Investment Basics for Beginners**
        
        **What are Market Indices?**
        Market indices are like scorecards that track how groups of stocks are performing. Think of them as 
        measuring the "temperature" of different stock markets around the world.
        
        **Key Concepts:**
        
        **📈 Diversification**
        Don't put all your eggs in one basket. Spreading investments across different markets and regions 
        can help reduce risk.
        
        **⏰ Time Horizon**
        Markets can be volatile in the short term but tend to grow over longer periods. The longer you 
        can invest, the more you can benefit from market growth.
        
        **📊 Volatility**
        Markets go up and down - this is normal! Volatility measures how much prices fluctuate. 
        Higher volatility means more risk but potentially higher returns.
        
        **💡 Dollar-Cost Averaging**
        Investing the same amount regularly (like monthly) can help smooth out market ups and downs 
        over time.
        
        **🎯 Long-term Thinking**
        Successful investing is usually about patience and consistency, not trying to time the market 
        perfectly.
        """
    
    def generate_holding_period_insight(self, data: pd.DataFrame, symbol: str) -> str:
        """Generate insights about holding period returns.
        
        Args:
            data: Historical price data
            symbol: Market index symbol
            
        Returns:
            Educational insight text about holding periods
        """
        if data.empty:
            return "No data available for holding period analysis."
        
        if not self.analyzer:
            return "Investment analysis not available."
        
        try:
            analysis = self.analyzer.calculate_holding_period_returns(data)
            
            if 'error' in analysis:
                return f"Unable to calculate holding period analysis: {analysis['error']}"
            
            market_name = self.market_contexts.get(symbol, {}).get('name', symbol)
            
            # Extract key insights
            insights = []
            for period_key, period_data in analysis.items():
                if period_key.endswith('_year') and isinstance(period_data, dict):
                    years = period_data['period_years']
                    positive_prob = period_data['positive_probability']
                    avg_return = period_data['avg_annualized_return']
                    
                    insights.append(f"**{years}-Year Holding**: {positive_prob:.0f}% chance of positive returns, {avg_return:.1f}% average annual return")
            
            insight_text = f"""
            **Time Heals All Wounds: The Power of Holding Period**
            
            Analysis of {market_name} shows how holding period dramatically affects investment success:
            
            {chr(10).join(insights)}
            
            **Key Takeaway**: The longer you hold, the higher your probability of success. Short-term volatility 
            becomes less important over longer time horizons, demonstrating why patience is crucial for investors.
            
            **What this means for you**: Consider your investment timeline carefully. If you can invest for 10+ years, 
            historical data suggests you have excellent odds of positive returns.
            """
            
            return insight_text.strip()
            
        except Exception as e:
            logger.error(f"Error generating holding period insight: {e}")
            return "Unable to generate holding period analysis at this time."
    
    def generate_dca_insight(self, data: pd.DataFrame, symbol: str, monthly_amount: float = 1000) -> str:
        """Generate insights about dollar-cost averaging.
        
        Args:
            data: Historical price data
            symbol: Market index symbol
            monthly_amount: Monthly investment amount
            
        Returns:
            Educational insight text about DCA
        """
        if data.empty:
            return "No data available for dollar-cost averaging analysis."
        
        if not self.analyzer:
            return "Investment analysis not available."
        
        try:
            analysis = self.analyzer.calculate_dca_analysis(data, monthly_amount)
            
            if 'error' in analysis:
                return f"Unable to calculate DCA analysis: {analysis['error']}"
            
            market_name = self.market_contexts.get(symbol, {}).get('name', symbol)
            
            total_invested = analysis['total_invested']
            final_value = analysis['final_portfolio_value']
            total_return_pct = analysis['total_return_pct']
            periods = analysis['investment_periods']
            
            insight_text = f"""
            **Dollar-Cost Averaging: The Power of Consistency**
            
            Investing ${monthly_amount:,.0f} monthly in {market_name} over {periods} periods:
            
            **Results:**
            - **Total Invested**: ${total_invested:,.0f}
            - **Final Portfolio Value**: ${final_value:,.0f}
            - **Total Return**: {total_return_pct:+.1f}% (${final_value - total_invested:+,.0f})
            
            **Why DCA Works:**
            - **Reduces timing risk**: You buy more shares when prices are low, fewer when high
            - **Emotional discipline**: Removes the stress of trying to time the market
            - **Compound growth**: Regular investing harnesses the power of compounding over time
            
            **Key Lesson**: Consistency beats timing. Regular investing, regardless of market conditions, 
            has historically been one of the most effective wealth-building strategies for ordinary investors.
            """
            
            return insight_text.strip()
            
        except Exception as e:
            logger.error(f"Error generating DCA insight: {e}")
            return "Unable to generate DCA analysis at this time."
    
    def generate_worst_timing_insight(self, data: pd.DataFrame, symbol: str, annual_amount: float = 10000) -> str:
        """Generate insights about worst timing scenario.
        
        Args:
            data: Historical price data
            symbol: Market index symbol
            annual_amount: Annual investment amount
            
        Returns:
            Educational insight text about worst timing
        """
        if data.empty:
            return "No data available for worst timing analysis."
        
        if not self.analyzer:
            return "Investment analysis not available."
        
        try:
            analysis = self.analyzer.calculate_worst_timing_analysis(data, annual_amount)
            
            if 'error' in analysis:
                return f"Unable to calculate worst timing analysis: {analysis['error']}"
            
            market_name = self.market_contexts.get(symbol, {}).get('name', symbol)
            
            total_invested = analysis['total_invested']
            final_value = analysis['final_portfolio_value']
            total_return_pct = analysis['total_return_pct']
            investment_years = analysis['investment_years']
            recovery_months = analysis.get('recovery_months')
            
            insight_text = f"""
            **Worst Possible Timing: Buying at Each Year's Peak**
            
            Even with the worst luck - investing ${annual_amount:,.0f} at each year's highest price in {market_name}:
            
            **Results:**
            - **Total Invested**: ${total_invested:,.0f} over {investment_years} years
            - **Final Portfolio Value**: ${final_value:,.0f}
            - **Total Return**: {total_return_pct:+.1f}%
            {f"- **Recovery Time**: {recovery_months} months to break even" if recovery_months else ""}
            
            **Remarkable Insight**: Even with terrible timing, long-term investing in quality markets has 
            historically rewarded patient investors. This shows the resilience of market growth over time.
            
            **Key Lesson**: Perfect timing isn't necessary for investment success. Time in the market 
            is more important than timing the market. Even the unluckiest investor can succeed with patience.
            """
            
            return insight_text.strip()
            
        except Exception as e:
            logger.error(f"Error generating worst timing insight: {e}")
            return "Unable to generate worst timing analysis at this time."
    
    def generate_market_timing_cost_insight(self, data: pd.DataFrame, symbol: str, initial_amount: float = 10000) -> str:
        """Generate insights about the cost of market timing.
        
        Args:
            data: Historical price data
            symbol: Market index symbol
            initial_amount: Initial investment amount
            
        Returns:
            Educational insight text about market timing costs
        """
        if data.empty:
            return "No data available for market timing cost analysis."
        
        if not self.analyzer:
            return "Investment analysis not available."
        
        try:
            analysis = self.analyzer.calculate_market_timing_cost(data, initial_amount)
            
            if 'error' in analysis:
                return f"Unable to calculate market timing cost: {analysis['error']}"
            
            market_name = self.market_contexts.get(symbol, {}).get('name', symbol)
            
            buy_hold_value = analysis['buy_hold_final_value']
            buy_hold_return = analysis['buy_hold_return_pct']
            
            # Get the worst scenario (missing 30 days)
            worst_scenario = analysis['scenarios'].get('missed_30_days')
            if worst_scenario:
                missed_value = worst_scenario['final_value']
                opportunity_cost = worst_scenario['opportunity_cost_dollars']
                
                insight_text = f"""
                **The Cost of Market Timing: Missing the Best Days**
                
                Starting with ${initial_amount:,.0f} invested in {market_name}:
                
                **Buy & Hold Strategy**: ${buy_hold_value:,.0f} ({buy_hold_return:+.1f}% return)
                
                **Missing Best 30 Days**: ${missed_value:,.0f}
                **Opportunity Cost**: ${opportunity_cost:,.0f}
                
                **Critical Insight**: Missing just the best 30 trading days dramatically reduces returns. 
                Since the best days often follow the worst days, trying to time the market by avoiding 
                downturns often means missing the recovery.
                
                **Key Lesson**: Stay invested. The cost of being out of the market during the best days 
                far outweighs the benefit of avoiding the worst days. Market timing is extremely difficult 
                and expensive for ordinary investors.
                """
            else:
                insight_text = f"""
                **The Cost of Market Timing: Missing the Best Days**
                
                Analysis shows that missing the best trading days in {market_name} significantly 
                reduces long-term returns. The best days often occur during volatile periods, 
                making market timing extremely risky for ordinary investors.
                """
            
            return insight_text.strip()
            
        except Exception as e:
            logger.error(f"Error generating market timing cost insight: {e}")
            return "Unable to generate market timing cost analysis at this time."
    
    def generate_yearly_returns_insight(self, data: pd.DataFrame, symbol: str) -> str:
        """Generate insights about year-by-year returns.
        
        Args:
            data: Historical price data
            symbol: Market index symbol
            
        Returns:
            Educational insight text about yearly returns
        """
        if data.empty:
            return "No data available for yearly returns analysis."
        
        if not self.analyzer:
            return "Investment analysis not available."
        
        try:
            analysis = self.analyzer.calculate_yearly_returns(data)
            
            if 'error' in analysis:
                return f"Unable to calculate yearly returns: {analysis['error']}"
            
            market_name = self.market_contexts.get(symbol, {}).get('name', symbol)
            
            total_years = analysis['total_years']
            positive_years = analysis['positive_years']
            positive_pct = analysis['positive_percentage']
            avg_return = analysis['avg_return']
            best_year = analysis['best_year']
            worst_year = analysis['worst_year']
            
            insight_text = f"""
            **Year-by-Year Market Returns: The Long-Term Picture**
            
            Historical analysis of {market_name} over {total_years} years:
            
            **Performance Summary:**
            - **Positive Years**: {positive_years} out of {total_years} ({positive_pct:.0f}%)
            - **Average Annual Return**: {avg_return:+.1f}%
            - **Best Year**: {best_year['year']} ({best_year['return_pct']:+.1f}%)
            - **Worst Year**: {worst_year['year']} ({worst_year['return_pct']:+.1f}%)
            
            **Key Insights:**
            - Positive years significantly outnumber negative years
            - Short-term volatility is normal and expected
            - Long-term trend has been consistently upward
            
            **Investment Wisdom**: While individual years can be unpredictable, the historical pattern 
            shows that patient, long-term investors have been rewarded. Focus on decades, not individual years.
            """
            
            return insight_text.strip()
            
        except Exception as e:
            logger.error(f"Error generating yearly returns insight: {e}")
            return "Unable to generate yearly returns analysis at this time."
    
    def generate_performance_insights(self, performance_data: Dict[str, Dict]) -> str:
        """Generate insights from comparative performance analysis.
        
        Args:
            performance_data: Performance analysis results from benchmarking
            
        Returns:
            Educational insight text about performance comparison
        """
        if not performance_data or 'error' in performance_data:
            return "No performance data available for analysis."
        
        try:
            # Extract performance metrics
            returns = {}
            volatilities = {}
            
            for symbol, data in performance_data.items():
                if isinstance(data, dict) and 'total_return_pct' in data:
                    returns[symbol] = data['total_return_pct']
                    volatilities[symbol] = data.get('volatility_pct', 0)
            
            if not returns:
                return "No valid performance data for comparison."
            
            # Find best and worst performers
            best_performer = max(returns.keys(), key=lambda x: returns[x])
            worst_performer = min(returns.keys(), key=lambda x: returns[x])
            
            best_return = returns[best_performer]
            worst_return = returns[worst_performer]
            
            # Get friendly names
            best_friendly = self.market_contexts.get(best_performer, {}).get('name', best_performer)
            worst_friendly = self.market_contexts.get(worst_performer, {}).get('name', worst_performer)
            
            # Calculate performance spread
            performance_spread = best_return - worst_return
            
            insight_text = f"""
            **Performance Comparison Insights**
            
            **Market Leaders:**
            - **Top Performer**: {best_friendly} ({best_return:+.1f}%)
            - **Underperformer**: {worst_friendly} ({worst_return:+.1f}%)
            - **Performance Gap**: {performance_spread:.1f} percentage points
            
            **What This Means:**
            {'Significant performance differences across markets highlight the importance of diversification.' if performance_spread > 20 else 'Moderate performance differences show markets can vary but not dramatically.' if performance_spread > 10 else 'Similar performance across markets suggests correlated global conditions.'}
            
            **Investment Implications:**
            - Different markets reward investors differently over the same period
            - Geographic diversification can help capture the best-performing regions
            - No single market consistently outperforms all others over time
            
            **Key Takeaway**: This analysis reinforces why spreading investments across multiple markets 
            and regions is a fundamental principle of sound investing.
            """
            
            return insight_text.strip()
            
        except Exception as e:
            logger.error(f"Error generating performance insights: {e}")
            return "Unable to generate performance insights at this time."
    
    def generate_correlation_insights(self, correlation_data: Dict[str, Any]) -> str:
        """Generate insights from market correlation analysis.
        
        Args:
            correlation_data: Correlation analysis results from benchmarking
            
        Returns:
            Educational insight text about market relationships
        """
        if not correlation_data or 'error' in correlation_data or 'correlation_matrix' not in correlation_data:
            return "No correlation data available for analysis."
        
        try:
            correlation_matrix = correlation_data['correlation_matrix']
            symbols = correlation_data['symbols']
            
            if len(symbols) < 2:
                return "Need at least 2 markets for correlation analysis."
            
            # Find highest and lowest correlations
            correlations = []
            for i, sym1 in enumerate(symbols):
                for j, sym2 in enumerate(symbols):
                    if i < j:  # Avoid duplicates and self-correlation
                        corr_value = correlation_matrix[sym1][sym2]
                        correlations.append((sym1, sym2, corr_value))
            
            if not correlations:
                return "Unable to calculate market correlations."
            
            highest_corr = max(correlations, key=lambda x: x[2])
            lowest_corr = min(correlations, key=lambda x: x[2])
            
            # Calculate average correlation
            avg_correlation = sum(corr[2] for corr in correlations) / len(correlations)
            
            insight_text = f"""
            **Market Correlation Analysis**
            
            **Relationship Patterns:**
            - **Most Correlated**: {self.market_contexts.get(highest_corr[0], {}).get('name', highest_corr[0])} & {self.market_contexts.get(highest_corr[1], {}).get('name', highest_corr[1])} ({highest_corr[2]:.2f})
            - **Least Correlated**: {self.market_contexts.get(lowest_corr[0], {}).get('name', lowest_corr[0])} & {self.market_contexts.get(lowest_corr[1], {}).get('name', lowest_corr[1])} ({lowest_corr[2]:.2f})
            - **Average Correlation**: {avg_correlation:.2f}
            
            **What Correlation Means:**
            - **High correlation (>0.7)**: Markets move together - less diversification benefit
            - **Moderate correlation (0.3-0.7)**: Some relationship but still diversification value
            - **Low correlation (<0.3)**: Markets move independently - excellent diversification
            
            **Diversification Insights:**
            {'These markets show strong relationships, suggesting limited diversification benefits during market stress.' if avg_correlation > 0.7 else 'Moderate correlations indicate good diversification potential while maintaining some global market exposure.' if avg_correlation > 0.4 else 'Low correlations suggest excellent diversification opportunities across these markets.'}
            
            **Investment Strategy**: Focus on markets with lower correlations to build a more resilient, 
            diversified portfolio that can weather regional economic storms.
            """
            
            return insight_text.strip()
            
        except Exception as e:
            logger.error(f"Error generating correlation insights: {e}")
            return "Unable to generate correlation insights at this time."
    
    def generate_risk_insights(self, risk_metrics: Dict[str, Dict]) -> str:
        """Generate insights from risk-adjusted return analysis.
        
        Args:
            risk_metrics: Risk metrics from benchmarking analysis
            
        Returns:
            Educational insight text about risk and volatility
        """
        if not risk_metrics or 'error' in risk_metrics:
            return "No risk metrics available for analysis."
        
        try:
            # Extract risk metrics
            sharpe_ratios = {}
            volatilities = {}
            max_drawdowns = {}
            
            for symbol, metrics in risk_metrics.items():
                if isinstance(metrics, dict):
                    sharpe_ratios[symbol] = metrics.get('sharpe_ratio', 0)
                    volatilities[symbol] = metrics.get('volatility', 0)
                    max_drawdowns[symbol] = metrics.get('max_drawdown', 0)
            
            if not sharpe_ratios:
                return "No valid risk metrics for analysis."
            
            # Find best and worst risk-adjusted performers
            best_sharpe = max(sharpe_ratios.keys(), key=lambda x: sharpe_ratios[x])
            worst_sharpe = min(sharpe_ratios.keys(), key=lambda x: sharpe_ratios[x])
            
            # Find lowest and highest volatility
            lowest_vol = min(volatilities.keys(), key=lambda x: volatilities[x])
            highest_vol = max(volatilities.keys(), key=lambda x: volatilities[x])
            
            insight_text = f"""
            **Risk-Adjusted Performance Analysis**
            
            **Risk Champions:**
            - **Best Risk-Adjusted Returns**: {self.market_contexts.get(best_sharpe, {}).get('name', best_sharpe)} (Sharpe: {sharpe_ratios[best_sharpe]:.2f})
            - **Lowest Volatility**: {self.market_contexts.get(lowest_vol, {}).get('name', lowest_vol)} ({volatilities[lowest_vol]:.1f}% volatility)
            
            **Risk Considerations:**
            - **Highest Volatility**: {self.market_contexts.get(highest_vol, {}).get('name', highest_vol)} ({volatilities[highest_vol]:.1f}% volatility)
            - **Poorest Risk-Adjusted Returns**: {self.market_contexts.get(worst_sharpe, {}).get('name', worst_sharpe)} (Sharpe: {sharpe_ratios[worst_sharpe]:.2f})
            
            **Understanding Risk Metrics:**
            - **Sharpe Ratio**: Measures return per unit of risk (higher is better)
            - **Volatility**: How much prices fluctuate (lower is generally better for stability)
            - **Max Drawdown**: Worst peak-to-trough decline (shows downside risk)
            
            **Investment Wisdom**: Don't just chase the highest returns. Consider how much risk you're 
            taking to achieve those returns. The best investments often provide good returns with 
            manageable risk levels.
            
            **Risk Management**: Diversification across different risk profiles can help balance 
            your portfolio between growth potential and stability.
            """
            
            return insight_text.strip()
            
        except Exception as e:
            logger.error(f"Error generating risk insights: {e}")
            return "Unable to generate risk insights at this time."
    
    def generate_diversification_insights(self, correlation_data: Dict, risk_metrics: Dict) -> str:
        """Generate portfolio diversification recommendations.
        
        Args:
            correlation_data: Correlation analysis results
            risk_metrics: Risk metrics for each market
            
        Returns:
            Educational insight text about diversification strategy
        """
        if not correlation_data or not risk_metrics:
            return "Insufficient data for diversification analysis."
        
        try:
            correlation_matrix = correlation_data.get('correlation_matrix', {})
            symbols = correlation_data.get('symbols', [])
            
            if len(symbols) < 3:
                return "Need at least 3 markets for meaningful diversification analysis."
            
            # Find markets with low correlations for diversification
            low_corr_pairs = []
            for i, sym1 in enumerate(symbols):
                for j, sym2 in enumerate(symbols):
                    if i < j:
                        corr_value = correlation_matrix[sym1][sym2]
                        if corr_value < 0.5:  # Low correlation threshold
                            low_corr_pairs.append((sym1, sym2, corr_value))
            
            # Find markets with good risk-adjusted returns
            good_sharpe_markets = []
            for symbol, metrics in risk_metrics.items():
                if isinstance(metrics, dict) and metrics.get('sharpe_ratio', 0) > 0.5:
                    good_sharpe_markets.append(symbol)
            
            insight_text = f"""
            **Portfolio Diversification Strategy**
            
            **Diversification Opportunities:**
            {f"Found {len(low_corr_pairs)} market pairs with low correlation (<0.5)" if low_corr_pairs else "Most markets show high correlation - diversification benefits may be limited"}
            
            **Recommended Core Holdings:**
            {chr(10).join([f"- {self.market_contexts.get(symbol, {}).get('name', symbol)} (Good risk-adjusted returns)" for symbol in good_sharpe_markets[:4]])}
            
            **Diversification Principles:**
            
            **Geographic Spread**: Include markets from different regions (US, Europe, Asia-Pacific)
            to reduce regional economic risk.
            
            **Correlation Awareness**: Combine markets that don't move in lockstep to smooth 
            overall portfolio volatility.
            
            **Risk Balance**: Mix higher-growth markets with more stable, lower-volatility options.
            
            **Rebalancing**: Periodically adjust holdings to maintain your target allocation as 
            markets perform differently over time.
            
            **Practical Approach**: Start with 3-4 major markets representing different regions, 
            then gradually expand as your portfolio grows and you gain experience.
            
            **Remember**: Diversification doesn't guarantee profits or prevent losses, but it can 
            help reduce the impact of poor performance in any single market on your overall portfolio.
            """
            
            return insight_text.strip()
            
        except Exception as e:
            logger.error(f"Error generating diversification insights: {e}")
            return "Unable to generate diversification insights at this time."