help@rskworld.in +91 93305 39277
RSK World
  • Home
  • Development
    • Web Development
    • Mobile Apps
    • Software
    • Games
    • Project
  • Technologies
    • Data Science
    • AI Development
    • Cloud Development
    • Blockchain
    • Cyber Security
    • Dev Tools
    • Testing Tools
  • Blog
  • About
  • Contact

Theme Settings

Color Scheme
Display Options
Font Size
100%
Back to Project
RSK World
stock-time-series
/
scripts
RSK World
stock-time-series
Stock Market Time Series Dataset - OHLCV + LSTM + Portfolio Optimization
scripts
  • __init__.py1.4 KB
  • advanced_indicators.py11.2 KB
  • analyze.py11.6 KB
  • backtesting.py17.8 KB
  • forecast.py11.5 KB
  • interactive_dashboard.py13.1 KB
  • load_data.py8.5 KB
  • ml_models.py18.1 KB
  • portfolio.py16.3 KB
  • visualize.py14.4 KB
interactive_dashboard.py
scripts/interactive_dashboard.py
Raw Download
Find: Go to:
"""
Stock Market Time Series Dataset - Interactive Dashboard

Author: Molla Samser
Organization: RSK World
Designer & Tester: Rima Khatun
Website: https://rskworld.in/
Email: help@rskworld.in
Phone: +91 93305 39277
Address: Nutanhat, Mongolkote, Purba Burdwan, West Bengal, India, 713147

Installation: pip install plotly dash
"""

import pandas as pd
import numpy as np
from pathlib import Path
import warnings
warnings.filterwarnings('ignore')

try:
    import plotly.graph_objects as go
    from plotly.subplots import make_subplots
    import plotly.express as px
    PLOTLY_AVAILABLE = True
except ImportError:
    PLOTLY_AVAILABLE = False
    print("Plotly not installed. Install with: pip install plotly")


class InteractiveDashboard:
    """
    Interactive visualization dashboard using Plotly.
    """
    
    def __init__(self, data_path: str):
        """
        Initialize dashboard.
        
        Args:
            data_path: Path to stock CSV file
        """
        if not PLOTLY_AVAILABLE:
            raise ImportError("Plotly is required. Install with: pip install plotly")
        
        self.data_path = Path(data_path)
        self.symbol = self.data_path.stem
        self.df = self._load_data()
    
    def _load_data(self) -> pd.DataFrame:
        """Load and prepare data."""
        df = pd.read_csv(self.data_path, parse_dates=['Date'], index_col='Date')
        df.sort_index(inplace=True)
        return df
    
    def create_candlestick_chart(self, show: bool = True):
        """
        Create interactive candlestick chart.
        
        Args:
            show: Whether to display the chart
            
        Returns:
            Plotly figure object
        """
        fig = go.Figure(data=[go.Candlestick(
            x=self.df.index,
            open=self.df['Open'],
            high=self.df['High'],
            low=self.df['Low'],
            close=self.df['Close'],
            name='OHLC'
        )])
        
        # Add moving averages if available
        if 'MA_20' in self.df.columns:
            fig.add_trace(go.Scatter(
                x=self.df.index,
                y=self.df['MA_20'],
                mode='lines',
                name='MA(20)',
                line=dict(color='orange', width=2)
            ))
        
        if 'MA_50' in self.df.columns:
            fig.add_trace(go.Scatter(
                x=self.df.index,
                y=self.df['MA_50'],
                mode='lines',
                name='MA(50)',
                line=dict(color='purple', width=2)
            ))
        
        fig.update_layout(
            title=f'{self.symbol} Interactive Candlestick Chart',
            yaxis_title='Price ($)',
            xaxis_title='Date',
            template='plotly_white',
            height=600,
            hovermode='x unified'
        )
        
        if show:
            fig.show()
        
        return fig
    
    def create_technical_indicators_dashboard(self, show: bool = True):
        """
        Create comprehensive technical indicators dashboard.
        
        Args:
            show: Whether to display the chart
            
        Returns:
            Plotly figure object
        """
        fig = make_subplots(
            rows=4, cols=1,
            shared_xaxes=True,
            vertical_spacing=0.05,
            subplot_titles=(f'{self.symbol} Price', 'Volume', 'RSI', 'MACD'),
            row_heights=[0.4, 0.2, 0.2, 0.2]
        )
        
        # Price chart
        fig.add_trace(go.Scatter(
            x=self.df.index,
            y=self.df['Close'],
            mode='lines',
            name='Close',
            line=dict(color='blue', width=2)
        ), row=1, col=1)
        
        if 'MA_20' in self.df.columns:
            fig.add_trace(go.Scatter(
                x=self.df.index,
                y=self.df['MA_20'],
                mode='lines',
                name='MA(20)',
                line=dict(color='orange', width=1.5, dash='dash')
            ), row=1, col=1)
        
        if 'MA_50' in self.df.columns:
            fig.add_trace(go.Scatter(
                x=self.df.index,
                y=self.df['MA_50'],
                mode='lines',
                name='MA(50)',
                line=dict(color='purple', width=1.5, dash='dash')
            ), row=1, col=1)
        
        # Volume
        colors = ['red' if self.df['Close'].iloc[i] < self.df['Open'].iloc[i] 
                 else 'green' for i in range(len(self.df))]
        fig.add_trace(go.Bar(
            x=self.df.index,
            y=self.df['Volume'],
            name='Volume',
            marker_color=colors,
            showlegend=False
        ), row=2, col=1)
        
        # RSI
        if 'RSI' in self.df.columns:
            fig.add_trace(go.Scatter(
                x=self.df.index,
                y=self.df['RSI'],
                mode='lines',
                name='RSI',
                line=dict(color='blue', width=2)
            ), row=3, col=1)
            
            # Add overbought/oversold lines
            fig.add_hline(y=70, line_dash="dash", line_color="red", row=3, col=1)
            fig.add_hline(y=30, line_dash="dash", line_color="green", row=3, col=1)
        
        # MACD
        if 'MACD' in self.df.columns:
            colors_macd = ['green' if val >= 0 else 'red' for val in self.df['MACD']]
            fig.add_trace(go.Bar(
                x=self.df.index,
                y=self.df['MACD'],
                name='MACD',
                marker_color=colors_macd
            ), row=4, col=1)
        
        fig.update_layout(
            title=f'{self.symbol} Technical Analysis Dashboard',
            template='plotly_white',
            height=1000,
            showlegend=True,
            hovermode='x unified'
        )
        
        fig.update_yaxes(title_text="Price ($)", row=1, col=1)
        fig.update_yaxes(title_text="Volume", row=2, col=1)
        fig.update_yaxes(title_text="RSI", row=3, col=1)
        fig.update_yaxes(title_text="MACD", row=4, col=1)
        fig.update_xaxes(title_text="Date", row=4, col=1)
        
        if show:
            fig.show()
        
        return fig
    
    def create_returns_analysis(self, show: bool = True):
        """
        Create returns analysis dashboard.
        
        Args:
            show: Whether to display the chart
            
        Returns:
            Plotly figure object
        """
        # Calculate returns
        returns = self.df['Close'].pct_change().dropna() * 100
        cumulative_returns = (1 + self.df['Close'].pct_change()).cumprod() - 1
        
        fig = make_subplots(
            rows=2, cols=2,
            subplot_titles=('Daily Returns', 'Cumulative Returns', 
                          'Returns Distribution', 'Returns Heatmap'),
            specs=[[{"type": "scatter"}, {"type": "scatter"}],
                  [{"type": "histogram"}, {"type": "heatmap"}]]
        )
        
        # Daily returns
        fig.add_trace(go.Scatter(
            x=returns.index,
            y=returns,
            mode='lines',
            name='Daily Returns',
            line=dict(color='blue', width=1)
        ), row=1, col=1)
        
        # Cumulative returns
        fig.add_trace(go.Scatter(
            x=cumulative_returns.index,
            y=cumulative_returns * 100,
            mode='lines',
            name='Cumulative Returns',
            line=dict(color='green', width=2),
            fill='tozeroy'
        ), row=1, col=2)
        
        # Returns distribution
        fig.add_trace(go.Histogram(
            x=returns,
            nbinsx=50,
            name='Distribution',
            marker_color='blue',
            showlegend=False
        ), row=2, col=1)
        
        # Returns heatmap (monthly)
        monthly_returns = self.df['Close'].resample('M').last().pct_change() * 100
        monthly_matrix = monthly_returns.values.reshape(-1, 1)
        
        fig.add_trace(go.Heatmap(
            z=monthly_matrix.T,
            colorscale='RdYlGn',
            showscale=True,
            name='Monthly Returns'
        ), row=2, col=2)
        
        fig.update_layout(
            title=f'{self.symbol} Returns Analysis',
            template='plotly_white',
            height=800,
            showlegend=True
        )
        
        if show:
            fig.show()
        
        return fig
    
    def create_volume_profile(self, show: bool = True):
        """
        Create volume profile chart.
        
        Args:
            show: Whether to display the chart
            
        Returns:
            Plotly figure object
        """
        # Calculate volume at price levels
        price_bins = np.linspace(self.df['Low'].min(), self.df['High'].max(), 50)
        volume_profile = []
        
        for i in range(len(price_bins) - 1):
            mask = (self.df['Close'] >= price_bins[i]) & (self.df['Close'] < price_bins[i+1])
            volume_profile.append(self.df.loc[mask, 'Volume'].sum())
        
        fig = go.Figure()
        
        # Price chart
        fig.add_trace(go.Scatter(
            x=self.df.index,
            y=self.df['Close'],
            mode='lines',
            name='Price',
            yaxis='y',
            line=dict(color='blue', width=2)
        ))
        
        # Volume profile
        fig.add_trace(go.Bar(
            x=volume_profile,
            y=price_bins[:-1],
            orientation='h',
            name='Volume Profile',
            yaxis='y',
            xaxis='x2',
            marker_color='rgba(0, 0, 255, 0.3)'
        ))
        
        fig.update_layout(
            title=f'{self.symbol} Price and Volume Profile',
            template='plotly_white',
            height=600,
            xaxis=dict(domain=[0, 0.7], title='Date'),
            xaxis2=dict(domain=[0.75, 1], title='Volume'),
            yaxis=dict(title='Price ($)'),
            showlegend=True
        )
        
        if show:
            fig.show()
        
        return fig


def create_multi_stock_comparison(stock_paths: list, normalize: bool = True, show: bool = True):
    """
    Create interactive comparison of multiple stocks.
    
    Args:
        stock_paths: List of paths to stock CSV files
        normalize: Whether to normalize prices
        show: Whether to display the chart
        
    Returns:
        Plotly figure object
    """
    if not PLOTLY_AVAILABLE:
        print("Plotly not installed. Install with: pip install plotly")
        return None
    
    fig = go.Figure()
    
    for path in stock_paths:
        df = pd.read_csv(path, parse_dates=['Date'], index_col='Date')
        symbol = Path(path).stem
        
        prices = df['Close']
        if normalize:
            prices = (prices / prices.iloc[0]) * 100
        
        fig.add_trace(go.Scatter(
            x=df.index,
            y=prices,
            mode='lines',
            name=symbol,
            line=dict(width=2)
        ))
    
    title = 'Stock Price Comparison'
    if normalize:
        title += ' (Normalized to 100)'
    
    fig.update_layout(
        title=title,
        xaxis_title='Date',
        yaxis_title='Price ($)' if not normalize else 'Normalized Price',
        template='plotly_white',
        height=600,
        hovermode='x unified'
    )
    
    if show:
        fig.show()
    
    return fig


if __name__ == "__main__":
    if not PLOTLY_AVAILABLE:
        print("=" * 70)
        print("Plotly is not installed!")
        print("=" * 70)
        print("\nInstall Plotly with:")
        print("pip install plotly")
        print("\nFor Dash web dashboard:")
        print("pip install dash")
        print("=" * 70)
    else:
        print("=" * 70)
        print("Stock Market Time Series Dataset - Interactive Dashboard")
        print("=" * 70)
        print("\nAuthor: Molla Samser | RSK World")
        print("Website: https://rskworld.in/")
        print("=" * 70)
        
        # Create interactive dashboard
        dashboard = InteractiveDashboard('data/AAPL.csv')
        
        print("\n1. Creating interactive candlestick chart...")
        dashboard.create_candlestick_chart()
        
        print("\n2. Creating technical indicators dashboard...")
        dashboard.create_technical_indicators_dashboard()
        
        print("\n3. Creating returns analysis...")
        dashboard.create_returns_analysis()
        
        print("\n4. Creating volume profile...")
        dashboard.create_volume_profile()
        
        print("\n5. Creating multi-stock comparison...")
        create_multi_stock_comparison([
            'data/AAPL.csv',
            'data/GOOGL.csv',
            'data/MSFT.csv',
            'data/AMZN.csv',
            'data/TSLA.csv'
        ])
        
        print("\n" + "=" * 70)
        print("Visit https://rskworld.in/ for more datasets and tools!")
        print("=" * 70)

436 lines•13.1 KB
python

About RSK World

Founded by Molla Samser, with Designer & Tester Rima Khatun, RSK World is your one-stop destination for free programming resources, source code, and development tools.

Founder: Molla Samser
Designer & Tester: Rima Khatun

Development

  • Game Development
  • Web Development
  • Mobile Development
  • AI Development
  • Development Tools

Legal

  • Terms & Conditions
  • Privacy Policy
  • Disclaimer

Contact Info

Nutanhat, Mongolkote
Purba Burdwan, West Bengal
India, 713147

+91 93305 39277

hello@rskworld.in
support@rskworld.in

© 2026 RSK World. All rights reserved.

Content used for educational purposes only. View Disclaimer