Spaces:
Sleeping
Sleeping
Download src/visualization/charts.py from MikeZhang09/marketwise: direct link, hf CLI and curl.
- Browser
- Download file 5.74 kB
-
https://huggingface.co/spaces/MikeZhang09/marketwise/resolve/main/src/visualization/charts.py
- Command line
-
hf download hf://spaces/MikeZhang09/marketwise/src/visualization/charts.py
-
curl -L -o charts.py https://huggingface.co/spaces/MikeZhang09/marketwise/resolve/main/src/visualization/charts.py
5.74 kB
| """ | |
| 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='<b>%{fullData.name}</b><br>' + | |
| 'Date: %{x}<br>' + | |
| 'Price: $%{y:,.2f}<extra></extra>' | |
| )) | |
| 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'<b>{symbol}</b><br>' + | |
| 'Date: %{x}<br>' + | |
| 'Change: %{y:.2f}%<br>' + | |
| 'Price: $%{customdata:,.2f}<extra></extra>' | |
| )) | |
| 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='<b>Volume</b><br>' + | |
| 'Date: %{x}<br>' + | |
| 'Volume: %{y:,.0f}<extra></extra>' | |
| )) | |
| 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 | |