Spaces:
Sleeping
Sleeping
Download src/analysis/benchmarking.py from MikeZhang09/marketwise: direct link, hf CLI and curl.
- Browser
- Download file 18.5 kB
-
https://huggingface.co/spaces/MikeZhang09/marketwise/resolve/main/src/analysis/benchmarking.py
- Command line
-
hf download hf://spaces/MikeZhang09/marketwise/src/analysis/benchmarking.py
-
curl -L -o benchmarking.py https://huggingface.co/spaces/MikeZhang09/marketwise/resolve/main/src/analysis/benchmarking.py
18.5 kB
| """ | |
| Market benchmarking analysis for comparing performance across different indices. | |
| """ | |
| import pandas as pd | |
| import numpy as np | |
| import logging | |
| from datetime import datetime, timedelta | |
| from typing import Dict, List, Any, Optional | |
| from pathlib import Path | |
| logger = logging.getLogger(__name__) | |
| # Market indices configuration for friendly names | |
| INDICES_CONFIG = { | |
| "^GSPC": {"name": "S&P 500", "market": "US"}, | |
| "^FTSE": {"name": "FTSE 100", "market": "UK"}, | |
| "^N225": {"name": "Nikkei 225", "market": "Japan"}, | |
| "^DJI": {"name": "Dow Jones", "market": "US"}, | |
| "^IXIC": {"name": "NASDAQ", "market": "US"}, | |
| "^GDAXI": {"name": "DAX", "market": "Germany"}, | |
| "000001.SS": {"name": "SSE Composite", "market": "China"}, | |
| "^HSI": {"name": "Hang Seng", "market": "Hong Kong"}, | |
| "^AXJO": {"name": "ASX 200", "market": "Australia"}, | |
| "^FCHI": {"name": "CAC 40", "market": "France"}, | |
| "^GSPTSE": {"name": "S&P/TSX", "market": "Canada"} | |
| } | |
| def get_friendly_name(symbol: str) -> str: | |
| """Convert symbol to friendly name with country. | |
| Args: | |
| symbol: Market symbol (e.g., '^GSPC') | |
| Returns: | |
| Friendly name with country (e.g., 'S&P 500 (US)') | |
| """ | |
| if symbol in INDICES_CONFIG: | |
| config = INDICES_CONFIG[symbol] | |
| return f"{config['name']} ({config['market']})" | |
| return symbol | |
| class MarketBenchmarking: | |
| """Analyze and benchmark performance across multiple market indices.""" | |
| def __init__(self): | |
| """Initialize the market benchmarking analyzer.""" | |
| pass | |
| def calculate_relative_performance( | |
| self, | |
| data_dict: Dict[str, pd.DataFrame], | |
| base_value: float = 100.0 | |
| ) -> Dict[str, Any]: | |
| """Calculate relative performance normalized to a base value. | |
| Args: | |
| data_dict: Dictionary mapping symbols to DataFrames with timestamp and close_price | |
| base_value: Base value for normalization (default 100) | |
| Returns: | |
| Dictionary with relative performance analysis results | |
| """ | |
| if not data_dict or all(df.empty for df in data_dict.values()): | |
| logger.warning("No data provided for relative performance analysis") | |
| return {"error": "No data available"} | |
| try: | |
| results = {} | |
| for symbol, data in data_dict.items(): | |
| if data.empty or 'close_price' not in data.columns: | |
| logger.warning(f"Invalid data for {symbol}") | |
| continue | |
| # Ensure data is sorted by timestamp | |
| data = data.sort_values('timestamp').copy() | |
| data = data[data['close_price'] > 0].dropna(subset=['close_price']) | |
| if data.empty: | |
| continue | |
| # Calculate normalized performance | |
| first_price = data['close_price'].iloc[0] | |
| if first_price <= 0: | |
| continue | |
| normalized_prices = (data['close_price'] / first_price) * base_value | |
| total_return = ((data['close_price'].iloc[-1] / first_price) - 1) * 100 | |
| # Calculate volatility (annualized) | |
| daily_returns = data['close_price'].pct_change().dropna() | |
| volatility = daily_returns.std() * np.sqrt(252) * 100 # Annualized volatility | |
| results[symbol] = { | |
| 'normalized_prices': normalized_prices.tolist(), | |
| 'timestamps': data['timestamp'].tolist(), | |
| 'total_return_pct': total_return, | |
| 'volatility_pct': volatility, | |
| 'start_price': first_price, | |
| 'end_price': data['close_price'].iloc[-1], | |
| 'data_points': len(data) | |
| } | |
| return results | |
| except Exception as e: | |
| logger.error(f"Error calculating relative performance: {e}") | |
| return {"error": f"Calculation failed: {str(e)}"} | |
| def calculate_correlation_matrix( | |
| self, | |
| data_dict: Dict[str, pd.DataFrame] | |
| ) -> Dict[str, Any]: | |
| """Calculate correlation matrix between markets. | |
| Args: | |
| data_dict: Dictionary mapping symbols to DataFrames | |
| Returns: | |
| Dictionary with correlation analysis results | |
| """ | |
| if not data_dict or len(data_dict) < 2: | |
| logger.warning("Need at least 2 markets for correlation analysis") | |
| return {"error": "Insufficient data for correlation analysis"} | |
| try: | |
| # Prepare data for correlation calculation | |
| returns_data = {} | |
| for symbol, data in data_dict.items(): | |
| if data.empty or 'close_price' not in data.columns: | |
| continue | |
| data = data.sort_values('timestamp').copy() | |
| data = data[data['close_price'] > 0].dropna(subset=['close_price']) | |
| if len(data) < 2: | |
| continue | |
| # Calculate daily returns | |
| daily_returns = data['close_price'].pct_change().dropna() | |
| returns_data[symbol] = daily_returns | |
| if len(returns_data) < 2: | |
| return {"error": "Insufficient valid data for correlation"} | |
| # Create DataFrame with aligned dates | |
| returns_df = pd.DataFrame(returns_data) | |
| returns_df = returns_df.dropna() # Remove rows with any NaN values | |
| if returns_df.empty: | |
| return {"error": "No overlapping data periods"} | |
| # Calculate correlation matrix | |
| correlation_matrix = returns_df.corr() | |
| # Convert to dictionary format | |
| symbols = list(correlation_matrix.columns) | |
| correlation_dict = {} | |
| for i, symbol1 in enumerate(symbols): | |
| correlation_dict[symbol1] = {} | |
| for j, symbol2 in enumerate(symbols): | |
| correlation_dict[symbol1][symbol2] = correlation_matrix.iloc[i, j] | |
| return { | |
| 'correlation_matrix': correlation_dict, | |
| 'symbols': symbols, | |
| 'data_points': len(returns_df), | |
| 'date_range': { | |
| 'start': returns_df.index.min() if hasattr(returns_df.index, 'min') else None, | |
| 'end': returns_df.index.max() if hasattr(returns_df.index, 'max') else None | |
| } | |
| } | |
| except Exception as e: | |
| logger.error(f"Error calculating correlation matrix: {e}") | |
| return {"error": f"Correlation calculation failed: {str(e)}"} | |
| def calculate_risk_metrics( | |
| self, | |
| data_dict: Dict[str, pd.DataFrame], | |
| risk_free_rate: float = 0.02 | |
| ) -> Dict[str, Any]: | |
| """Calculate risk metrics including Sharpe ratio and max drawdown. | |
| Args: | |
| data_dict: Dictionary mapping symbols to DataFrames | |
| risk_free_rate: Annual risk-free rate for Sharpe ratio calculation | |
| Returns: | |
| Dictionary with risk metrics for each market | |
| """ | |
| if not data_dict or all(df.empty for df in data_dict.values()): | |
| logger.warning("No data provided for risk metrics analysis") | |
| return {"error": "No data available"} | |
| try: | |
| results = {} | |
| for symbol, data in data_dict.items(): | |
| if data.empty or 'close_price' not in data.columns: | |
| continue | |
| data = data.sort_values('timestamp').copy() | |
| data = data[data['close_price'] > 0].dropna(subset=['close_price']) | |
| if len(data) < 2: | |
| continue | |
| # Calculate daily returns | |
| daily_returns = data['close_price'].pct_change().dropna() | |
| if daily_returns.empty: | |
| continue | |
| # Annualized return | |
| total_days = len(daily_returns) | |
| total_return = (data['close_price'].iloc[-1] / data['close_price'].iloc[0]) - 1 | |
| annualized_return = ((1 + total_return) ** (252 / total_days)) - 1 | |
| # Volatility (annualized) | |
| volatility = daily_returns.std() * np.sqrt(252) | |
| # Sharpe ratio | |
| sharpe_ratio = (annualized_return - risk_free_rate) / volatility if volatility > 0 else 0 | |
| # Maximum drawdown | |
| cumulative_returns = (1 + daily_returns).cumprod() | |
| rolling_max = cumulative_returns.expanding().max() | |
| drawdowns = (cumulative_returns - rolling_max) / rolling_max | |
| max_drawdown = drawdowns.min() | |
| # Downside deviation (for Sortino ratio) | |
| negative_returns = daily_returns[daily_returns < 0] | |
| downside_deviation = negative_returns.std() * np.sqrt(252) if len(negative_returns) > 0 else 0 | |
| # Sortino ratio | |
| sortino_ratio = (annualized_return - risk_free_rate) / downside_deviation if downside_deviation > 0 else 0 | |
| results[symbol] = { | |
| 'annualized_return': annualized_return * 100, | |
| 'volatility': volatility * 100, | |
| 'sharpe_ratio': sharpe_ratio, | |
| 'sortino_ratio': sortino_ratio, | |
| 'max_drawdown': max_drawdown * 100, | |
| 'total_return': total_return * 100, | |
| 'data_points': len(daily_returns) | |
| } | |
| return results | |
| except Exception as e: | |
| logger.error(f"Error calculating risk metrics: {e}") | |
| return {"error": f"Risk metrics calculation failed: {str(e)}"} | |
| def calculate_performance_rankings( | |
| self, | |
| data_dict: Dict[str, pd.DataFrame] | |
| ) -> Dict[str, Any]: | |
| """Rank markets by various performance metrics. | |
| Args: | |
| data_dict: Dictionary mapping symbols to DataFrames | |
| Returns: | |
| Dictionary with performance rankings | |
| """ | |
| if not data_dict or all(df.empty for df in data_dict.values()): | |
| logger.warning("No data provided for performance rankings") | |
| return {"error": "No data available"} | |
| try: | |
| # Get risk metrics for ranking | |
| risk_metrics = self.calculate_risk_metrics(data_dict) | |
| if "error" in risk_metrics: | |
| return risk_metrics | |
| # Create ranking lists | |
| rankings = { | |
| 'by_total_return': [], | |
| 'by_sharpe_ratio': [], | |
| 'by_volatility': [], | |
| 'by_max_drawdown': [] | |
| } | |
| # Sort by total return (descending) | |
| total_return_sorted = sorted( | |
| risk_metrics.items(), | |
| key=lambda x: x[1]['total_return'], | |
| reverse=True | |
| ) | |
| rankings['by_total_return'] = [ | |
| {'symbol': symbol, 'value': metrics['total_return']} | |
| for symbol, metrics in total_return_sorted | |
| ] | |
| # Sort by Sharpe ratio (descending) | |
| sharpe_sorted = sorted( | |
| risk_metrics.items(), | |
| key=lambda x: x[1]['sharpe_ratio'], | |
| reverse=True | |
| ) | |
| rankings['by_sharpe_ratio'] = [ | |
| {'symbol': symbol, 'value': metrics['sharpe_ratio']} | |
| for symbol, metrics in sharpe_sorted | |
| ] | |
| # Sort by volatility (ascending - lower is better) | |
| volatility_sorted = sorted( | |
| risk_metrics.items(), | |
| key=lambda x: x[1]['volatility'] | |
| ) | |
| rankings['by_volatility'] = [ | |
| {'symbol': symbol, 'value': metrics['volatility']} | |
| for symbol, metrics in volatility_sorted | |
| ] | |
| # Sort by max drawdown (ascending - less negative is better) | |
| drawdown_sorted = sorted( | |
| risk_metrics.items(), | |
| key=lambda x: x[1]['max_drawdown'], | |
| reverse=True | |
| ) | |
| rankings['by_max_drawdown'] = [ | |
| {'symbol': symbol, 'value': metrics['max_drawdown']} | |
| for symbol, metrics in drawdown_sorted | |
| ] | |
| return { | |
| 'rankings': rankings, | |
| 'metrics_summary': risk_metrics | |
| } | |
| except Exception as e: | |
| logger.error(f"Error calculating performance rankings: {e}") | |
| return {"error": f"Rankings calculation failed: {str(e)}"} | |
| def generate_benchmark_insights( | |
| self, | |
| data_dict: Dict[str, pd.DataFrame] | |
| ) -> Dict[str, Any]: | |
| """Generate automated insights from benchmarking analysis. | |
| Args: | |
| data_dict: Dictionary mapping symbols to DataFrames | |
| Returns: | |
| Dictionary with generated insights | |
| """ | |
| if not data_dict or all(df.empty for df in data_dict.values()): | |
| logger.warning("No data provided for insight generation") | |
| return {"error": "No data available"} | |
| try: | |
| # Get analysis results | |
| performance = self.calculate_relative_performance(data_dict) | |
| risk_metrics = self.calculate_risk_metrics(data_dict) | |
| rankings = self.calculate_performance_rankings(data_dict) | |
| correlation = self.calculate_correlation_matrix(data_dict) | |
| if any("error" in result for result in [performance, risk_metrics, rankings, correlation]): | |
| return {"error": "Unable to generate insights due to analysis errors"} | |
| insights = [] | |
| # Performance insights | |
| if rankings and 'rankings' in rankings: | |
| best_performer = rankings['rankings']['by_total_return'][0] | |
| worst_performer = rankings['rankings']['by_total_return'][-1] | |
| best_friendly = get_friendly_name(best_performer['symbol']) | |
| worst_friendly = get_friendly_name(worst_performer['symbol']) | |
| insights.append({ | |
| 'type': 'performance', | |
| 'title': 'Top Performer', | |
| 'content': f"{best_friendly} delivered the highest total return at {best_performer['value']:.1f}%, " | |
| f"while {worst_friendly} had the lowest return at {worst_performer['value']:.1f}%." | |
| }) | |
| # Risk insights | |
| if rankings and 'rankings' in rankings: | |
| best_sharpe = rankings['rankings']['by_sharpe_ratio'][0] | |
| lowest_vol = rankings['rankings']['by_volatility'][0] | |
| best_sharpe_friendly = get_friendly_name(best_sharpe['symbol']) | |
| lowest_vol_friendly = get_friendly_name(lowest_vol['symbol']) | |
| insights.append({ | |
| 'type': 'risk', | |
| 'title': 'Risk-Adjusted Performance', | |
| 'content': f"{best_sharpe_friendly} had the best risk-adjusted returns (Sharpe ratio: {best_sharpe['value']:.2f}). " | |
| f"{lowest_vol_friendly} was the least volatile market with {lowest_vol['value']:.1f}% volatility." | |
| }) | |
| # Correlation insights | |
| if correlation and 'correlation_matrix' in correlation: | |
| symbols = correlation['symbols'] | |
| if len(symbols) >= 2: | |
| # 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['correlation_matrix'][sym1][sym2] | |
| correlations.append((sym1, sym2, corr_value)) | |
| if correlations: | |
| highest_corr = max(correlations, key=lambda x: x[2]) | |
| lowest_corr = min(correlations, key=lambda x: x[2]) | |
| highest_friendly1 = get_friendly_name(highest_corr[0]) | |
| highest_friendly2 = get_friendly_name(highest_corr[1]) | |
| lowest_friendly1 = get_friendly_name(lowest_corr[0]) | |
| lowest_friendly2 = get_friendly_name(lowest_corr[1]) | |
| insights.append({ | |
| 'type': 'correlation', | |
| 'title': 'Market Relationships', | |
| 'content': f"{highest_friendly1} and {highest_friendly2} are highly correlated ({highest_corr[2]:.2f}), " | |
| f"while {lowest_friendly1} and {lowest_friendly2} show low correlation ({lowest_corr[2]:.2f}), " | |
| f"suggesting better diversification potential." | |
| }) | |
| return { | |
| 'insights': insights, | |
| 'analysis_summary': { | |
| 'markets_analyzed': len(data_dict), | |
| 'data_points': sum(len(df) for df in data_dict.values() if not df.empty), | |
| 'analysis_types': ['performance', 'risk', 'correlation', 'rankings'] | |
| } | |
| } | |
| except Exception as e: | |
| logger.error(f"Error generating benchmark insights: {e}") | |
| return {"error": f"Insight generation failed: {str(e)}"} | |