Spaces:
Sleeping
Sleeping
Download src/visualization/benchmark_charts.py from MikeZhang09/marketwise: direct link, hf CLI and curl.
- Browser
- Download file 14.4 kB
-
https://huggingface.co/spaces/MikeZhang09/marketwise/resolve/main/src/visualization/benchmark_charts.py
- Command line
-
hf download hf://spaces/MikeZhang09/marketwise/src/visualization/benchmark_charts.py
-
curl -L -o benchmark_charts.py https://huggingface.co/spaces/MikeZhang09/marketwise/resolve/main/src/visualization/benchmark_charts.py
14.4 kB
| """ | |
| Specialized chart functions for benchmarking visualization. | |
| """ | |
| import plotly.graph_objects as go | |
| import plotly.express as px | |
| from plotly.subplots import make_subplots | |
| import pandas as pd | |
| import numpy as np | |
| from typing import Dict, List, Any | |
| import logging | |
| 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 | |
| def convert_data_dict_to_friendly_names(data_dict: Dict[str, pd.DataFrame]) -> Dict[str, pd.DataFrame]: | |
| """Convert data dictionary keys from symbols to friendly names. | |
| Args: | |
| data_dict: Dictionary with symbol keys | |
| Returns: | |
| Dictionary with friendly name keys | |
| """ | |
| friendly_dict = {} | |
| for symbol, data in data_dict.items(): | |
| friendly_name = get_friendly_name(symbol) | |
| friendly_dict[friendly_name] = data | |
| return friendly_dict | |
| def create_performance_comparison_chart( | |
| data_dict: Dict[str, pd.DataFrame], | |
| title: str, | |
| base_value: float = 100.0 | |
| ) -> go.Figure: | |
| """Create normalized performance comparison chart. | |
| Args: | |
| data_dict: Dictionary mapping symbol names to DataFrames | |
| title: Chart title | |
| base_value: Base value for normalization | |
| Returns: | |
| Plotly figure object | |
| """ | |
| if not data_dict or all(df.empty for df in data_dict.values()): | |
| logger.warning(f"No data provided for performance comparison chart: {title}") | |
| return go.Figure().add_annotation( | |
| text="No data available for performance comparison", | |
| xref="paper", yref="paper", | |
| x=0.5, y=0.5, showarrow=False | |
| ) | |
| # Convert to friendly names | |
| friendly_data = convert_data_dict_to_friendly_names(data_dict) | |
| fig = go.Figure() | |
| colors = px.colors.qualitative.Set1 | |
| for i, (friendly_name, data) in enumerate(friendly_data.items()): | |
| if not data.empty and 'close_price' in data.columns: | |
| # Normalize to base value | |
| first_price = data['close_price'].iloc[0] | |
| if first_price <= 0 or pd.isna(first_price): | |
| logger.warning(f"Skipping {friendly_name}: invalid starting price ({first_price})") | |
| continue | |
| normalized_data = (data['close_price'] / first_price) * base_value | |
| fig.add_trace(go.Scatter( | |
| x=data['timestamp'], | |
| y=normalized_data, | |
| mode='lines', | |
| name=friendly_name, | |
| line=dict(width=2, color=colors[i % len(colors)]), | |
| customdata=data['close_price'], | |
| hovertemplate=f'<b>{friendly_name}</b><br>' + | |
| 'Date: %{x}<br>' + | |
| f'Normalized: %{{y:.2f}} (Base {base_value})<br>' + | |
| 'Actual Price: $%{customdata:,.2f}<extra></extra>' | |
| )) | |
| fig.update_layout( | |
| title=title, | |
| xaxis_title="Date", | |
| yaxis_title=f"Normalized Performance (Base {base_value})", | |
| hovermode='x unified', | |
| showlegend=True, | |
| height=500, | |
| margin=dict(l=0, r=0, t=40, b=0) | |
| ) | |
| return fig | |
| def create_correlation_heatmap( | |
| correlation_matrix: Dict[str, Dict[str, float]], | |
| title: str | |
| ) -> go.Figure: | |
| """Create correlation heatmap visualization. | |
| Args: | |
| correlation_matrix: Nested dictionary with correlation values (using symbols) | |
| title: Chart title | |
| Returns: | |
| Plotly figure object | |
| """ | |
| if not correlation_matrix: | |
| logger.warning(f"No correlation data provided for heatmap: {title}") | |
| return go.Figure().add_annotation( | |
| text="No correlation data available", | |
| xref="paper", yref="paper", | |
| x=0.5, y=0.5, showarrow=False | |
| ) | |
| try: | |
| symbols = list(correlation_matrix.keys()) | |
| friendly_names = [get_friendly_name(symbol) for symbol in symbols] | |
| # Convert to matrix format | |
| matrix = [] | |
| for sym1 in symbols: | |
| row = [] | |
| for sym2 in symbols: | |
| row.append(correlation_matrix[sym1][sym2]) | |
| matrix.append(row) | |
| fig = go.Figure(data=go.Heatmap( | |
| z=matrix, | |
| x=friendly_names, | |
| y=friendly_names, | |
| colorscale='RdBu', | |
| zmid=0, | |
| zmin=-1, | |
| zmax=1, | |
| text=[[f"{val:.2f}" for val in row] for row in matrix], | |
| texttemplate="%{text}", | |
| textfont={"size": 12}, | |
| hovertemplate='%{y} vs %{x}<br>Correlation: %{z:.3f}<extra></extra>' | |
| )) | |
| fig.update_layout( | |
| title=title, | |
| xaxis_title="Market Index", | |
| yaxis_title="Market Index", | |
| height=500, | |
| margin=dict(l=0, r=0, t=40, b=0) | |
| ) | |
| return fig | |
| except Exception as e: | |
| logger.error(f"Error creating correlation heatmap: {e}") | |
| return go.Figure().add_annotation( | |
| text=f"Error creating heatmap: {str(e)}", | |
| xref="paper", yref="paper", | |
| x=0.5, y=0.5, showarrow=False | |
| ) | |
| def create_risk_return_scatter( | |
| risk_metrics: Dict[str, Dict[str, float]], | |
| title: str | |
| ) -> go.Figure: | |
| """Create risk vs return scatter plot. | |
| Args: | |
| risk_metrics: Dictionary with risk metrics for each symbol | |
| title: Chart title | |
| Returns: | |
| Plotly figure object | |
| """ | |
| if not risk_metrics: | |
| logger.warning(f"No risk metrics provided for scatter plot: {title}") | |
| return go.Figure().add_annotation( | |
| text="No risk metrics available", | |
| xref="paper", yref="paper", | |
| x=0.5, y=0.5, showarrow=False | |
| ) | |
| try: | |
| friendly_names = [] | |
| returns = [] | |
| volatilities = [] | |
| sharpe_ratios = [] | |
| for symbol, metrics in risk_metrics.items(): | |
| friendly_names.append(get_friendly_name(symbol)) | |
| returns.append(metrics.get('annualized_return', 0)) | |
| volatilities.append(metrics.get('volatility', 0)) | |
| sharpe_ratios.append(metrics.get('sharpe_ratio', 0)) | |
| # Color by Sharpe ratio | |
| fig = go.Figure(data=go.Scatter( | |
| x=volatilities, | |
| y=returns, | |
| mode='markers+text', | |
| text=friendly_names, | |
| textposition="top center", | |
| marker=dict( | |
| size=12, | |
| color=sharpe_ratios, | |
| colorscale='Viridis', | |
| showscale=True, | |
| colorbar=dict(title="Sharpe Ratio"), | |
| line=dict(width=1, color='white') | |
| ), | |
| hovertemplate='<b>%{text}</b><br>' + | |
| 'Return: %{y:.1f}%<br>' + | |
| 'Volatility: %{x:.1f}%<br>' + | |
| 'Sharpe Ratio: %{marker.color:.2f}<extra></extra>' | |
| )) | |
| fig.update_layout( | |
| title=title, | |
| xaxis_title="Volatility (%)", | |
| yaxis_title="Annualized Return (%)", | |
| height=500, | |
| margin=dict(l=0, r=0, t=40, b=0) | |
| ) | |
| return fig | |
| except Exception as e: | |
| logger.error(f"Error creating risk-return scatter: {e}") | |
| return go.Figure().add_annotation( | |
| text=f"Error creating scatter plot: {str(e)}", | |
| xref="paper", yref="paper", | |
| x=0.5, y=0.5, showarrow=False | |
| ) | |
| def create_rolling_correlation_chart( | |
| data_dict: Dict[str, pd.DataFrame], | |
| symbol1: str, | |
| symbol2: str, | |
| window: int = 60, | |
| title: str = None | |
| ) -> go.Figure: | |
| """Create rolling correlation chart between two markets. | |
| Args: | |
| data_dict: Dictionary mapping symbols to DataFrames | |
| symbol1: First symbol for correlation | |
| symbol2: Second symbol for correlation | |
| window: Rolling window size in days | |
| title: Chart title | |
| Returns: | |
| Plotly figure object | |
| """ | |
| friendly_name1 = get_friendly_name(symbol1) | |
| friendly_name2 = get_friendly_name(symbol2) | |
| if not title: | |
| title = f"Rolling Correlation: {friendly_name1} vs {friendly_name2}" | |
| if symbol1 not in data_dict or symbol2 not in data_dict: | |
| logger.warning(f"Missing data for correlation: {symbol1}, {symbol2}") | |
| return go.Figure().add_annotation( | |
| text="Missing data for correlation analysis", | |
| xref="paper", yref="paper", | |
| x=0.5, y=0.5, showarrow=False | |
| ) | |
| try: | |
| data1 = data_dict[symbol1] | |
| data2 = data_dict[symbol2] | |
| if data1.empty or data2.empty: | |
| return go.Figure().add_annotation( | |
| text="Insufficient data for correlation analysis", | |
| xref="paper", yref="paper", | |
| x=0.5, y=0.5, showarrow=False | |
| ) | |
| # Calculate daily returns | |
| returns1 = data1.set_index('timestamp')['close_price'].pct_change().dropna() | |
| returns2 = data2.set_index('timestamp')['close_price'].pct_change().dropna() | |
| # Align data | |
| combined = pd.DataFrame({symbol1: returns1, symbol2: returns2}).dropna() | |
| if len(combined) < window: | |
| return go.Figure().add_annotation( | |
| text=f"Insufficient data for {window}-day rolling correlation", | |
| xref="paper", yref="paper", | |
| x=0.5, y=0.5, showarrow=False | |
| ) | |
| # Calculate rolling correlation | |
| rolling_corr = combined[symbol1].rolling(window=window).corr(combined[symbol2]) | |
| rolling_corr = rolling_corr.dropna() | |
| fig = go.Figure() | |
| fig.add_trace(go.Scatter( | |
| x=rolling_corr.index, | |
| y=rolling_corr.values, | |
| mode='lines', | |
| name=f'{window}-day Rolling Correlation', | |
| line=dict(width=2, color='blue'), | |
| hovertemplate=f'Date: %{{x}}<br>Correlation: %{{y:.3f}}<br>{friendly_name1} vs {friendly_name2}<extra></extra>' | |
| )) | |
| # Add horizontal reference lines | |
| fig.add_hline(y=0, line_dash="dash", line_color="gray", opacity=0.5) | |
| fig.add_hline(y=0.5, line_dash="dot", line_color="green", opacity=0.5) | |
| fig.add_hline(y=-0.5, line_dash="dot", line_color="red", opacity=0.5) | |
| fig.update_layout( | |
| title=title, | |
| xaxis_title="Date", | |
| yaxis_title="Correlation Coefficient", | |
| yaxis=dict(range=[-1, 1]), | |
| height=400, | |
| margin=dict(l=0, r=0, t=40, b=0) | |
| ) | |
| return fig | |
| except Exception as e: | |
| logger.error(f"Error creating rolling correlation chart: {e}") | |
| return go.Figure().add_annotation( | |
| text=f"Error creating correlation chart: {str(e)}", | |
| xref="paper", yref="paper", | |
| x=0.5, y=0.5, showarrow=False | |
| ) | |
| def create_benchmark_summary_table( | |
| risk_metrics: Dict[str, Dict[str, float]] | |
| ) -> go.Figure: | |
| """Create performance metrics summary table. | |
| Args: | |
| risk_metrics: Dictionary with risk metrics for each symbol | |
| Returns: | |
| Plotly table figure | |
| """ | |
| if not risk_metrics: | |
| logger.warning("No risk metrics provided for summary table") | |
| return go.Figure().add_annotation( | |
| text="No metrics available", | |
| xref="paper", yref="paper", | |
| x=0.5, y=0.5, showarrow=False | |
| ) | |
| try: | |
| symbols = list(risk_metrics.keys()) | |
| # Prepare table data with friendly names | |
| headers = ['Market', 'Total Return (%)', 'Annualized Return (%)', | |
| 'Volatility (%)', 'Sharpe Ratio', 'Max Drawdown (%)'] | |
| table_data = [] | |
| for symbol in symbols: | |
| metrics = risk_metrics[symbol] | |
| friendly_name = get_friendly_name(symbol) | |
| row = [ | |
| friendly_name, | |
| f"{metrics.get('total_return', 0):.1f}", | |
| f"{metrics.get('annualized_return', 0):.1f}", | |
| f"{metrics.get('volatility', 0):.1f}", | |
| f"{metrics.get('sharpe_ratio', 0):.2f}", | |
| f"{metrics.get('max_drawdown', 0):.1f}" | |
| ] | |
| table_data.append(row) | |
| # Transpose for plotly table format | |
| values = list(zip(*table_data)) | |
| fig = go.Figure(data=[go.Table( | |
| header=dict( | |
| values=headers, | |
| fill_color='lightblue', | |
| align='center', | |
| font=dict(size=12, color='black') | |
| ), | |
| cells=dict( | |
| values=values, | |
| fill_color='white', | |
| align='center', | |
| font=dict(size=11) | |
| ) | |
| )]) | |
| fig.update_layout( | |
| title="Performance Metrics Summary", | |
| height=300, | |
| margin=dict(l=0, r=0, t=40, b=0) | |
| ) | |
| return fig | |
| except Exception as e: | |
| logger.error(f"Error creating summary table: {e}") | |
| return go.Figure().add_annotation( | |
| text=f"Error creating table: {str(e)}", | |
| xref="paper", yref="paper", | |
| x=0.5, y=0.5, showarrow=False | |
| ) | |