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
PDF_DOWNLOAD_FIXES.mdQUICK_START.mdindex.htmlrealtime_predictor.pyadvanced_indicators.py
index.html
Raw Download
Find: Go to:
<!DOCTYPE html>
<html lang="en">
<head>
    <!--
    Stock Market Time Series Dataset - Demo Page
    
    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
    -->
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="description" content="Stock Market Time Series Dataset with OHLCV prices and technical indicators for multiple stocks">
    <meta name="keywords" content="stock market, time series, OHLCV, technical indicators, data science, machine learning">
    <meta name="author" content="Molla Samser - RSK World">
    <title>Stock Market Time Series Dataset - RSK World</title>
    
    <!-- Bootstrap CSS -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <!-- Font Awesome -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <!-- Chart.js -->
    <script src="https://cdn.jsdelivr.net/npm/chart.js@4.3.0/dist/chart.umd.js"></script>
    
    <style>
        :root {
            --primary-color: #28a745;
            --secondary-color: #17a2b8;
            --dark-color: #343a40;
            --light-color: #f8f9fa;
        }
        
        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            padding: 20px 0;
        }
        
        .main-container {
            background: white;
            border-radius: 15px;
            box-shadow: 0 10px 40px rgba(0,0,0,0.2);
            padding: 40px;
            margin: 20px auto;
            max-width: 1200px;
        }
        
        .header {
            text-align: center;
            margin-bottom: 40px;
            padding-bottom: 30px;
            border-bottom: 3px solid var(--primary-color);
        }
        
        .header h1 {
            color: var(--dark-color);
            font-weight: bold;
            margin-bottom: 15px;
        }
        
        .header .subtitle {
            color: #6c757d;
            font-size: 1.1rem;
        }
        
        .icon-box {
            width: 80px;
            height: 80px;
            margin: 0 auto 20px;
            background: linear-gradient(135deg, var(--primary-color), var(--secondary-color));
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            color: white;
            font-size: 2.5rem;
        }
        
        .feature-card {
            border: none;
            border-radius: 10px;
            box-shadow: 0 5px 15px rgba(0,0,0,0.1);
            transition: transform 0.3s ease, box-shadow 0.3s ease;
            margin-bottom: 20px;
            height: 100%;
        }
        
        .feature-card:hover {
            transform: translateY(-5px);
            box-shadow: 0 10px 25px rgba(0,0,0,0.15);
        }
        
        .feature-icon {
            font-size: 2rem;
            color: var(--primary-color);
            margin-bottom: 15px;
        }
        
        .stock-card {
            background: #f8f9fa;
            border-radius: 10px;
            padding: 20px;
            margin-bottom: 15px;
            border-left: 4px solid var(--primary-color);
        }
        
        .stock-symbol {
            font-weight: bold;
            color: var(--primary-color);
            font-size: 1.3rem;
        }
        
        .btn-custom {
            background: linear-gradient(135deg, var(--primary-color), var(--secondary-color));
            border: none;
            color: white;
            padding: 12px 30px;
            border-radius: 25px;
            font-weight: bold;
            transition: transform 0.3s ease;
        }
        
        .btn-custom:hover {
            transform: scale(1.05);
            color: white;
        }
        
        .section-title {
            color: var(--dark-color);
            font-weight: bold;
            margin: 40px 0 20px;
            padding-bottom: 10px;
            border-bottom: 2px solid var(--primary-color);
        }
        
        .footer {
            text-align: center;
            margin-top: 50px;
            padding-top: 30px;
            border-top: 2px solid #dee2e6;
            color: #6c757d;
        }
        
        .badge-custom {
            background: var(--primary-color);
            padding: 8px 15px;
            border-radius: 20px;
            font-size: 0.9rem;
        }
        
        .chart-container {
            position: relative;
            height: 400px;
            margin: 30px 0;
        }
        
        table {
            font-size: 0.95rem;
        }
        
        .contact-info {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 30px;
            border-radius: 10px;
            margin-top: 40px;
        }
        
        .contact-info a {
            color: white;
            text-decoration: underline;
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="main-container">
            <!-- Header -->
            <div class="header">
                <div class="icon-box">
                    <i class="fas fa-chart-line"></i>
                </div>
                <h1>Stock Market Time Series Dataset</h1>
                <p class="subtitle">Historical OHLCV Data with Technical Indicators for Multiple Stocks</p>
                <div class="mt-3">
                    <span class="badge badge-custom me-2"><i class="fas fa-calendar"></i> 2020 Data</span>
                    <span class="badge badge-custom me-2"><i class="fas fa-database"></i> 5 Stocks</span>
                    <span class="badge badge-custom"><i class="fas fa-chart-bar"></i> Technical Indicators</span>
                </div>
            </div>
            
            <!-- Overview -->
            <section>
                <h2 class="section-title"><i class="fas fa-info-circle"></i> Overview</h2>
                <p>This comprehensive dataset contains historical stock market data with OHLCV (Open, High, Low, Close, Volume) prices, trading volumes, and technical indicators for multiple stocks. Perfect for time series forecasting, technical analysis, portfolio optimization, and financial modeling.</p>
            </section>
            
            <!-- Features -->
            <section>
                <h2 class="section-title"><i class="fas fa-star"></i> Key Features</h2>
                <div class="row">
                    <div class="col-md-4 mb-3">
                        <div class="card feature-card">
                            <div class="card-body text-center">
                                <div class="feature-icon"><i class="fas fa-chart-candlestick"></i></div>
                                <h5 class="card-title">OHLCV Price Data</h5>
                                <p class="card-text">Complete open, high, low, close prices and trading volume for comprehensive analysis.</p>
                            </div>
                        </div>
                    </div>
                    <div class="col-md-4 mb-3">
                        <div class="card feature-card">
                            <div class="card-body text-center">
                                <div class="feature-icon"><i class="fas fa-chart-line"></i></div>
                                <h5 class="card-title">Technical Indicators</h5>
                                <p class="card-text">Pre-calculated MA_20, MA_50, RSI, and MACD indicators for quick analysis.</p>
                            </div>
                        </div>
                    </div>
                    <div class="col-md-4 mb-3">
                        <div class="card feature-card">
                            <div class="card-body text-center">
                                <div class="feature-icon"><i class="fas fa-building"></i></div>
                                <h5 class="card-title">Multiple Stocks</h5>
                                <p class="card-text">Data for AAPL, GOOGL, MSFT, AMZN, and TSLA covering the entire 2020.</p>
                            </div>
                        </div>
                    </div>
                    <div class="col-md-4 mb-3">
                        <div class="card feature-card">
                            <div class="card-body text-center">
                                <div class="feature-icon"><i class="fas fa-robot"></i></div>
                                <h5 class="card-title">ML Ready</h5>
                                <p class="card-text">Time series formatted data ready for machine learning and forecasting models.</p>
                            </div>
                        </div>
                    </div>
                    <div class="col-md-4 mb-3">
                        <div class="card feature-card">
                            <div class="card-body text-center">
                                <div class="feature-icon"><i class="fas fa-python"></i></div>
                                <h5 class="card-title">Python Scripts</h5>
                                <p class="card-text">Complete analysis, forecasting, and visualization scripts included.</p>
                            </div>
                        </div>
                    </div>
                    <div class="col-md-4 mb-3">
                        <div class="card feature-card">
                            <div class="card-body text-center">
                                <div class="feature-icon"><i class="fas fa-book"></i></div>
                                <h5 class="card-title">Documentation</h5>
                                <p class="card-text">Comprehensive documentation and metadata for all indicators and stocks.</p>
                            </div>
                        </div>
                    </div>
                </div>
            </section>
            
            <!-- Stocks Included -->
            <section>
                <h2 class="section-title"><i class="fas fa-building"></i> Stocks Included</h2>
                <div class="row">
                    <div class="col-md-6">
                        <div class="stock-card">
                            <div class="stock-symbol"><i class="fab fa-apple"></i> AAPL</div>
                            <strong>Apple Inc.</strong><br>
                            <small class="text-muted">Technology • Consumer Electronics</small>
                            <p class="mt-2 mb-0">Leading technology company known for iPhones, Mac, and innovative products.</p>
                        </div>
                    </div>
                    <div class="col-md-6">
                        <div class="stock-card">
                            <div class="stock-symbol"><i class="fab fa-google"></i> GOOGL</div>
                            <strong>Alphabet Inc.</strong><br>
                            <small class="text-muted">Technology • Internet Services</small>
                            <p class="mt-2 mb-0">Parent company of Google, leader in search, advertising, and cloud services.</p>
                        </div>
                    </div>
                    <div class="col-md-6">
                        <div class="stock-card">
                            <div class="stock-symbol"><i class="fab fa-microsoft"></i> MSFT</div>
                            <strong>Microsoft Corporation</strong><br>
                            <small class="text-muted">Technology • Software Infrastructure</small>
                            <p class="mt-2 mb-0">Software giant with Windows, Office, Azure, and enterprise solutions.</p>
                        </div>
                    </div>
                    <div class="col-md-6">
                        <div class="stock-card">
                            <div class="stock-symbol"><i class="fab fa-amazon"></i> AMZN</div>
                            <strong>Amazon.com Inc.</strong><br>
                            <small class="text-muted">Consumer Cyclical • Internet Retail</small>
                            <p class="mt-2 mb-0">E-commerce leader with AWS cloud services and diverse business portfolio.</p>
                        </div>
                    </div>
                    <div class="col-md-6">
                        <div class="stock-card">
                            <div class="stock-symbol"><i class="fas fa-car"></i> TSLA</div>
                            <strong>Tesla Inc.</strong><br>
                            <small class="text-muted">Consumer Cyclical • Auto Manufacturers</small>
                            <p class="mt-2 mb-0">Electric vehicle pioneer and clean energy company led by Elon Musk.</p>
                        </div>
                    </div>
                </div>
            </section>
            
            <!-- Data Format -->
            <section>
                <h2 class="section-title"><i class="fas fa-table"></i> Data Format</h2>
                <div class="table-responsive">
                    <table class="table table-striped table-hover">
                        <thead class="table-dark">
                            <tr>
                                <th>Column</th>
                                <th>Description</th>
                                <th>Type</th>
                            </tr>
                        </thead>
                        <tbody>
                            <tr>
                                <td><strong>Date</strong></td>
                                <td>Trading date (YYYY-MM-DD format)</td>
                                <td>Date</td>
                            </tr>
                            <tr>
                                <td><strong>Open</strong></td>
                                <td>Opening price of the trading day</td>
                                <td>Float</td>
                            </tr>
                            <tr>
                                <td><strong>High</strong></td>
                                <td>Highest price during the trading day</td>
                                <td>Float</td>
                            </tr>
                            <tr>
                                <td><strong>Low</strong></td>
                                <td>Lowest price during the trading day</td>
                                <td>Float</td>
                            </tr>
                            <tr>
                                <td><strong>Close</strong></td>
                                <td>Closing price of the trading day</td>
                                <td>Float</td>
                            </tr>
                            <tr>
                                <td><strong>Volume</strong></td>
                                <td>Total number of shares traded</td>
                                <td>Integer</td>
                            </tr>
                            <tr>
                                <td><strong>Adj Close</strong></td>
                                <td>Adjusted closing price (splits/dividends)</td>
                                <td>Float</td>
                            </tr>
                            <tr>
                                <td><strong>MA_20</strong></td>
                                <td>20-day Simple Moving Average</td>
                                <td>Float</td>
                            </tr>
                            <tr>
                                <td><strong>MA_50</strong></td>
                                <td>50-day Simple Moving Average</td>
                                <td>Float</td>
                            </tr>
                            <tr>
                                <td><strong>RSI</strong></td>
                                <td>Relative Strength Index (momentum indicator)</td>
                                <td>Float</td>
                            </tr>
                            <tr>
                                <td><strong>MACD</strong></td>
                                <td>Moving Average Convergence Divergence</td>
                                <td>Float</td>
                            </tr>
                        </tbody>
                    </table>
                </div>
            </section>
            
            <!-- Use Cases -->
            <section>
                <h2 class="section-title"><i class="fas fa-lightbulb"></i> Use Cases</h2>
                <div class="row">
                    <div class="col-md-6">
                        <ul class="list-group list-group-flush">
                            <li class="list-group-item"><i class="fas fa-check text-success me-2"></i> Time Series Forecasting (ARIMA, LSTM, Prophet)</li>
                            <li class="list-group-item"><i class="fas fa-check text-success me-2"></i> Technical Analysis & Trading Strategies</li>
                            <li class="list-group-item"><i class="fas fa-check text-success me-2"></i> Portfolio Optimization & Asset Allocation</li>
                        </ul>
                    </div>
                    <div class="col-md-6">
                        <ul class="list-group list-group-flush">
                            <li class="list-group-item"><i class="fas fa-check text-success me-2"></i> Risk Assessment & Volatility Analysis</li>
                            <li class="list-group-item"><i class="fas fa-check text-success me-2"></i> Machine Learning Model Training</li>
                            <li class="list-group-item"><i class="fas fa-check text-success me-2"></i> Algorithmic Trading & Backtesting</li>
                        </ul>
                    </div>
                </div>
            </section>
            
            <!-- Quick Start -->
            <section>
                <h2 class="section-title"><i class="fas fa-rocket"></i> Quick Start</h2>
                <div class="card">
                    <div class="card-body">
                        <h5 class="card-title">Python Example</h5>
                        <pre class="bg-dark text-light p-3 rounded"><code>import pandas as pd

# Load stock data
df = pd.read_csv('data/AAPL.csv', parse_dates=['Date'], index_col='Date')

# Display first few rows
print(df.head())

# Calculate daily returns
df['Returns'] = df['Close'].pct_change()

# Calculate volatility
volatility = df['Returns'].std() * (252 ** 0.5)
print(f"Annualized Volatility: {volatility:.2%}")</code></pre>
                        
                        <h5 class="card-title mt-4">Using Provided Scripts</h5>
                        <pre class="bg-dark text-light p-3 rounded"><code># Load and analyze data
from scripts.load_data import StockDataLoader
from scripts.analyze import StockAnalyzer

loader = StockDataLoader()
aapl = loader.load_stock('AAPL')

analyzer = StockAnalyzer('data/AAPL.csv')
analyzer.summary_statistics()
analyzer.plot_price_history()</code></pre>
                    </div>
                </div>
            </section>
            
            <!-- Download -->
            <section class="text-center mt-5">
                <h2 class="section-title"><i class="fas fa-download"></i> Download Dataset</h2>
                <p class="mb-4">Get the complete dataset with all stock data, metadata, and Python scripts.</p>
                <a href="stock-time-series.zip" class="btn btn-custom btn-lg me-2">
                    <i class="fas fa-download me-2"></i>Download Dataset
                </a>
                <a href="https://github.com/rskworld" target="_blank" class="btn btn-outline-secondary btn-lg">
                    <i class="fab fa-github me-2"></i>View on GitHub
                </a>
            </section>
            
            <!-- Contact Information -->
            <section>
                <div class="contact-info">
                    <h3 class="mb-4"><i class="fas fa-envelope"></i> Contact Information</h3>
                    <div class="row">
                        <div class="col-md-6">
                            <p><strong><i class="fas fa-user"></i> Author:</strong> Molla Samser</p>
                            <p><strong><i class="fas fa-building"></i> Organization:</strong> RSK World</p>
                            <p><strong><i class="fas fa-user-check"></i> Designer & Tester:</strong> Rima Khatun</p>
                        </div>
                        <div class="col-md-6">
                            <p><strong><i class="fas fa-globe"></i> Website:</strong> <a href="https://rskworld.in/" target="_blank">rskworld.in</a></p>
                            <p><strong><i class="fas fa-envelope"></i> Email:</strong> <a href="mailto:help@rskworld.in">help@rskworld.in</a></p>
                            <p><strong><i class="fas fa-phone"></i> Phone:</strong> +91 93305 39277</p>
                        </div>
                    </div>
                    <p class="mt-3 mb-0"><strong><i class="fas fa-map-marker-alt"></i> Address:</strong> Nutanhat, Mongolkote, Purba Burdwan, West Bengal, India, 713147</p>
                </div>
            </section>
            
            <!-- Footer -->
            <div class="footer">
                <p class="mb-2">
                    <strong>Stock Market Time Series Dataset</strong> | Created by <a href="https://rskworld.in/" target="_blank" class="text-decoration-none">RSK World</a>
                </p>
                <p class="mb-2">
                    <a href="https://rskworld.in/" target="_blank" class="text-decoration-none me-3">
                        <i class="fas fa-globe"></i> Website
                    </a>
                    <a href="mailto:help@rskworld.in" class="text-decoration-none me-3">
                        <i class="fas fa-envelope"></i> Email
                    </a>
                    <a href="https://github.com/rskworld" target="_blank" class="text-decoration-none">
                        <i class="fab fa-github"></i> GitHub
                    </a>
                </p>
                <p class="small mt-3">
                    © 2024 RSK World. All rights reserved. | For educational and research purposes.
                </p>
            </div>
        </div>
    </div>
    
    <!-- Bootstrap JS -->
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>

501 lines•22.7 KB
markup
scripts/advanced_indicators.py
Raw Download
Find: Go to:
"""
Stock Market Time Series Dataset - Advanced Technical Indicators

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
"""

import pandas as pd
import numpy as np
from typing import Tuple
import warnings
warnings.filterwarnings('ignore')


class AdvancedIndicators:
    """
    Advanced technical indicators beyond basic MA, RSI, MACD.
    """
    
    @staticmethod
    def bollinger_bands(df: pd.DataFrame, window: int = 20, num_std: float = 2) -> pd.DataFrame:
        """
        Calculate Bollinger Bands.
        
        Args:
            df: DataFrame with price data
            window: Moving average window
            num_std: Number of standard deviations
            
        Returns:
            DataFrame with Bollinger Bands columns
        """
        df = df.copy()
        df['BB_Middle'] = df['Close'].rolling(window=window).mean()
        rolling_std = df['Close'].rolling(window=window).std()
        df['BB_Upper'] = df['BB_Middle'] + (rolling_std * num_std)
        df['BB_Lower'] = df['BB_Middle'] - (rolling_std * num_std)
        df['BB_Width'] = df['BB_Upper'] - df['BB_Lower']
        df['BB_PercentB'] = (df['Close'] - df['BB_Lower']) / (df['BB_Upper'] - df['BB_Lower'])
        return df
    
    @staticmethod
    def average_true_range(df: pd.DataFrame, window: int = 14) -> pd.Series:
        """
        Calculate Average True Range (ATR).
        
        Args:
            df: DataFrame with OHLC data
            window: ATR period
            
        Returns:
            Series with ATR values
        """
        high_low = df['High'] - df['Low']
        high_close = np.abs(df['High'] - df['Close'].shift())
        low_close = np.abs(df['Low'] - df['Close'].shift())
        
        ranges = pd.concat([high_low, high_close, low_close], axis=1)
        true_range = np.max(ranges, axis=1)
        atr = true_range.rolling(window).mean()
        
        return atr
    
    @staticmethod
    def stochastic_oscillator(df: pd.DataFrame, k_window: int = 14, d_window: int = 3) -> Tuple[pd.Series, pd.Series]:
        """
        Calculate Stochastic Oscillator.
        
        Args:
            df: DataFrame with OHLC data
            k_window: %K period
            d_window: %D period (SMA of %K)
            
        Returns:
            Tuple of (%K, %D) Series
        """
        low_min = df['Low'].rolling(window=k_window).min()
        high_max = df['High'].rolling(window=k_window).max()
        
        k_percent = 100 * (df['Close'] - low_min) / (high_max - low_min)
        d_percent = k_percent.rolling(window=d_window).mean()
        
        return k_percent, d_percent
    
    @staticmethod
    def commodity_channel_index(df: pd.DataFrame, window: int = 20) -> pd.Series:
        """
        Calculate Commodity Channel Index (CCI).
        
        Args:
            df: DataFrame with OHLC data
            window: CCI period
            
        Returns:
            Series with CCI values
        """
        typical_price = (df['High'] + df['Low'] + df['Close']) / 3
        sma = typical_price.rolling(window=window).mean()
        mean_deviation = typical_price.rolling(window=window).apply(
            lambda x: np.abs(x - x.mean()).mean()
        )
        cci = (typical_price - sma) / (0.015 * mean_deviation)
        
        return cci
    
    @staticmethod
    def on_balance_volume(df: pd.DataFrame) -> pd.Series:
        """
        Calculate On-Balance Volume (OBV).
        
        Args:
            df: DataFrame with Close and Volume
            
        Returns:
            Series with OBV values
        """
        obv = (np.sign(df['Close'].diff()) * df['Volume']).fillna(0).cumsum()
        return obv
    
    @staticmethod
    def money_flow_index(df: pd.DataFrame, window: int = 14) -> pd.Series:
        """
        Calculate Money Flow Index (MFI).
        
        Args:
            df: DataFrame with OHLCV data
            window: MFI period
            
        Returns:
            Series with MFI values
        """
        typical_price = (df['High'] + df['Low'] + df['Close']) / 3
        money_flow = typical_price * df['Volume']
        
        positive_flow = pd.Series(0.0, index=df.index)
        negative_flow = pd.Series(0.0, index=df.index)
        
        positive_flow[typical_price > typical_price.shift(1)] = money_flow[typical_price > typical_price.shift(1)]
        negative_flow[typical_price < typical_price.shift(1)] = money_flow[typical_price < typical_price.shift(1)]
        
        positive_mf = positive_flow.rolling(window=window).sum()
        negative_mf = negative_flow.rolling(window=window).sum()
        
        mfi = 100 - (100 / (1 + positive_mf / negative_mf))
        
        return mfi
    
    @staticmethod
    def williams_percent_r(df: pd.DataFrame, window: int = 14) -> pd.Series:
        """
        Calculate Williams %R.
        
        Args:
            df: DataFrame with OHLC data
            window: Period
            
        Returns:
            Series with Williams %R values
        """
        high_max = df['High'].rolling(window=window).max()
        low_min = df['Low'].rolling(window=window).min()
        
        wr = -100 * (high_max - df['Close']) / (high_max - low_min)
        
        return wr
    
    @staticmethod
    def parabolic_sar(df: pd.DataFrame, af_start: float = 0.02, 
                     af_increment: float = 0.02, af_max: float = 0.2) -> pd.Series:
        """
        Calculate Parabolic SAR (simplified version).
        
        Args:
            df: DataFrame with OHLC data
            af_start: Initial acceleration factor
            af_increment: AF increment
            af_max: Maximum AF
            
        Returns:
            Series with SAR values
        """
        high = df['High']
        low = df['Low']
        close = df['Close']
        
        sar = close.copy()
        sar.iloc[0] = close.iloc[0]
        
        is_uptrend = True
        af = af_start
        ep = high.iloc[0]  # Extreme point
        
        for i in range(1, len(df)):
            if is_uptrend:
                sar.iloc[i] = sar.iloc[i-1] + af * (ep - sar.iloc[i-1])
                
                if low.iloc[i] < sar.iloc[i]:
                    is_uptrend = False
                    sar.iloc[i] = ep
                    ep = low.iloc[i]
                    af = af_start
                else:
                    if high.iloc[i] > ep:
                        ep = high.iloc[i]
                        af = min(af + af_increment, af_max)
            else:
                sar.iloc[i] = sar.iloc[i-1] - af * (sar.iloc[i-1] - ep)
                
                if high.iloc[i] > sar.iloc[i]:
                    is_uptrend = True
                    sar.iloc[i] = ep
                    ep = high.iloc[i]
                    af = af_start
                else:
                    if low.iloc[i] < ep:
                        ep = low.iloc[i]
                        af = min(af + af_increment, af_max)
        
        return sar
    
    @staticmethod
    def ichimoku_cloud(df: pd.DataFrame) -> pd.DataFrame:
        """
        Calculate Ichimoku Cloud.
        
        Args:
            df: DataFrame with OHLC data
            
        Returns:
            DataFrame with Ichimoku components
        """
        df = df.copy()
        
        # Tenkan-sen (Conversion Line): (9-period high + 9-period low)/2
        period9_high = df['High'].rolling(window=9).max()
        period9_low = df['Low'].rolling(window=9).min()
        df['Ichimoku_Tenkan'] = (period9_high + period9_low) / 2
        
        # Kijun-sen (Base Line): (26-period high + 26-period low)/2
        period26_high = df['High'].rolling(window=26).max()
        period26_low = df['Low'].rolling(window=26).min()
        df['Ichimoku_Kijun'] = (period26_high + period26_low) / 2
        
        # Senkou Span A (Leading Span A): (Conversion Line + Base Line)/2
        df['Ichimoku_SpanA'] = ((df['Ichimoku_Tenkan'] + df['Ichimoku_Kijun']) / 2).shift(26)
        
        # Senkou Span B (Leading Span B): (52-period high + 52-period low)/2
        period52_high = df['High'].rolling(window=52).max()
        period52_low = df['Low'].rolling(window=52).min()
        df['Ichimoku_SpanB'] = ((period52_high + period52_low) / 2).shift(26)
        
        # Chikou Span (Lagging Span): Current closing price shifted back 26 periods
        df['Ichimoku_Chikou'] = df['Close'].shift(-26)
        
        return df
    
    @staticmethod
    def add_all_indicators(df: pd.DataFrame) -> pd.DataFrame:
        """
        Add all advanced indicators to DataFrame.
        
        Args:
            df: DataFrame with OHLCV data
            
        Returns:
            DataFrame with all indicators
        """
        df = df.copy()
        
        # Bollinger Bands
        df = AdvancedIndicators.bollinger_bands(df)
        
        # ATR
        df['ATR'] = AdvancedIndicators.average_true_range(df)
        
        # Stochastic
        df['Stoch_K'], df['Stoch_D'] = AdvancedIndicators.stochastic_oscillator(df)
        
        # CCI
        df['CCI'] = AdvancedIndicators.commodity_channel_index(df)
        
        # OBV
        df['OBV'] = AdvancedIndicators.on_balance_volume(df)
        
        # MFI
        df['MFI'] = AdvancedIndicators.money_flow_index(df)
        
        # Williams %R
        df['Williams_R'] = AdvancedIndicators.williams_percent_r(df)
        
        # Parabolic SAR
        df['SAR'] = AdvancedIndicators.parabolic_sar(df)
        
        # Ichimoku Cloud
        df = AdvancedIndicators.ichimoku_cloud(df)
        
        return df


if __name__ == "__main__":
    print("=" * 70)
    print("Stock Market Time Series Dataset - Advanced Indicators")
    print("=" * 70)
    print("\nAuthor: Molla Samser | RSK World")
    print("Website: https://rskworld.in/")
    print("=" * 70)
    
    # Load data
    df = pd.read_csv('data/AAPL.csv', parse_dates=['Date'], index_col='Date')
    
    print(f"\nOriginal columns: {list(df.columns)}")
    print(f"Number of columns: {len(df.columns)}")
    
    # Add all indicators
    df_enhanced = AdvancedIndicators.add_all_indicators(df)
    
    print(f"\nEnhanced columns: {list(df_enhanced.columns)}")
    print(f"Number of columns: {len(df_enhanced.columns)}")
    print(f"\nNew indicators added: {len(df_enhanced.columns) - len(df.columns)}")
    
    # Show sample data
    print(f"\nSample data with new indicators:")
    print(df_enhanced[['Close', 'BB_Upper', 'BB_Lower', 'ATR', 'Stoch_K', 
                       'CCI', 'MFI', 'Williams_R']].tail())
    
    # Save enhanced dataset
    output_path = 'data/AAPL_enhanced.csv'
    df_enhanced.to_csv(output_path)
    print(f"\nEnhanced dataset saved to: {output_path}")
    
    print("\n" + "=" * 70)
    print("Visit https://rskworld.in/ for more datasets and tools!")
    print("=" * 70)

340 lines•11.2 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