Spaces:
Sleeping

marketwise / src /visualization /educational.py
MikeZhang69
Configure HF Spaces: LFS for db, ignore venv
e7cf9be
Raw History Blame Contribute Delete
38.5 kB
"""
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."