""" Chart generation functions using Plotly for financial data visualization. """ import plotly.graph_objects as go import plotly.express as px import pandas as pd import logging from typing import Dict, Optional, Union logger = logging.getLogger(__name__) def create_line_chart( data: pd.DataFrame, title: str, y_column: str = 'close_price' ) -> go.Figure: """Create an interactive line chart for financial data. Args: data: DataFrame with timestamp and price columns title: Chart title y_column: Column to plot on y-axis Returns: Plotly figure object """ if data.empty: logger.warning(f"No data provided for chart: {title}") return go.Figure().add_annotation( text="No data available", xref="paper", yref="paper", x=0.5, y=0.5, showarrow=False ) fig = go.Figure() fig.add_trace(go.Scatter( x=data['timestamp'], y=data[y_column], mode='lines', name=y_column.replace('_', ' ').title(), line=dict(width=2), hovertemplate='%{fullData.name}
' + 'Date: %{x}
' + 'Price: $%{y:,.2f}' )) fig.update_layout( title=title, xaxis_title="Date", yaxis_title="Price ($)", hovermode='x unified', showlegend=True, height=500, margin=dict(l=0, r=0, t=40, b=0) ) return fig def create_candlestick_chart(data: pd.DataFrame, title: str) -> go.Figure: """Create an interactive candlestick chart for OHLC data. Args: data: DataFrame with OHLC columns title: Chart title Returns: Plotly figure object """ if data.empty: logger.warning(f"No data provided for candlestick chart: {title}") return go.Figure().add_annotation( text="No data available", xref="paper", yref="paper", x=0.5, y=0.5, showarrow=False ) fig = go.Figure(data=go.Candlestick( x=data['timestamp'], open=data['open_price'], high=data['high_price'], low=data['low_price'], close=data['close_price'], name="OHLC" )) fig.update_layout( title=title, xaxis_title="Date", yaxis_title="Price ($)", height=500, margin=dict(l=0, r=0, t=40, b=0), xaxis_rangeslider_visible=False ) return fig def create_comparison_chart(data_dict: Dict[str, pd.DataFrame], title: str) -> go.Figure: """Create a comparison chart for multiple indices. Args: data_dict: Dictionary mapping symbol names to DataFrames title: Chart title 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 comparison chart: {title}") return go.Figure().add_annotation( text="No data available for comparison", xref="paper", yref="paper", x=0.5, y=0.5, showarrow=False ) fig = go.Figure() colors = px.colors.qualitative.Set1 for i, (symbol, data) in enumerate(data_dict.items()): if not data.empty: # Normalize to percentage change from first value first_price = data['close_price'].iloc[0] # Skip if first price is zero or invalid to avoid division by zero if first_price == 0 or pd.isna(first_price): logger.warning(f"Skipping {symbol}: invalid starting price ({first_price})") continue normalized_data = ((data['close_price'] / first_price) - 1) * 100 fig.add_trace(go.Scatter( x=data['timestamp'], y=normalized_data, mode='lines', name=symbol, line=dict(width=2, color=colors[i % len(colors)]), customdata=data['close_price'], # Add actual prices as custom data hovertemplate=f'{symbol}
' + 'Date: %{x}
' + 'Change: %{y:.2f}%
' + 'Price: $%{customdata:,.2f}' )) fig.update_layout( title=title, xaxis_title="Date", yaxis_title="Percentage Change (%)", hovermode='x unified', showlegend=True, height=500, margin=dict(l=0, r=0, t=40, b=0) ) return fig def create_volume_chart(data: pd.DataFrame, title: str) -> go.Figure: """Create a volume chart for trading volume data. Args: data: DataFrame with volume column title: Chart title Returns: Plotly figure object """ if data.empty: logger.warning(f"No data provided for volume chart: {title}") return go.Figure().add_annotation( text="No data available", xref="paper", yref="paper", x=0.5, y=0.5, showarrow=False ) fig = go.Figure() fig.add_trace(go.Bar( x=data['timestamp'], y=data['volume'], name='Volume', marker_color='lightblue', hovertemplate='Volume
' + 'Date: %{x}
' + 'Volume: %{y:,.0f}' )) fig.update_layout( title=title, xaxis_title="Date", yaxis_title="Volume", height=300, margin=dict(l=0, r=0, t=40, b=0), showlegend=False ) return fig