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
/
tutorials
RSK World
stock-time-series
Stock Market Time Series Dataset - OHLCV + LSTM + Portfolio Optimization
tutorials
  • README.md2.1 KB
  • advanced_ml_tutorial.py6 KB
  • backtesting_tutorial.py8 KB
  • getting_started.py10 KB
augmentation.pygetting_started.py
tutorials/getting_started.py
Raw Download
Find: Go to:
"""
Stock Market Time Series Dataset - Getting Started Tutorial

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

This tutorial covers:
1. Loading and exploring data
2. Basic analysis and statistics
3. Visualization
4. Technical indicators
5. Forecasting
6. Portfolio analysis
"""

import sys
import os
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
import warnings
warnings.filterwarnings('ignore')

# Set style
sns.set_style('whitegrid')
plt.rcParams['figure.figsize'] = (12, 6)

print("=" * 70)
print("Stock Market Time Series Dataset - Getting Started Tutorial")
print("=" * 70)
print("\nAuthor: Molla Samser | RSK World")
print("Website: https://rskworld.in/")
print("=" * 70)

# ==============================================================================
# SECTION 1: DATA LOADING
# ==============================================================================
print("\n" + "=" * 70)
print("SECTION 1: Loading Stock Data")
print("=" * 70)

from scripts.load_data import StockDataLoader

# Initialize data loader
loader = StockDataLoader(data_dir='../data')

# Load AAPL stock data
print("\nLoading AAPL stock data...")
aapl = loader.load_stock('AAPL')

print(f"✓ Loaded {len(aapl)} trading days")
print(f"✓ Date range: {aapl.index.min()} to {aapl.index.max()}")
print(f"✓ Columns: {list(aapl.columns)}")

print("\nFirst 5 rows:")
print(aapl.head())

# ==============================================================================
# SECTION 2: BASIC STATISTICS
# ==============================================================================
print("\n" + "=" * 70)
print("SECTION 2: Basic Statistics")
print("=" * 70)

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

print("\nKey Statistics:")
print(f"{'Metric':<30} {'Value':>15}")
print("-" * 50)
print(f"{'Average Close Price:':<30} ${aapl['Close'].mean():>14.2f}")
print(f"{'Median Close Price:':<30} ${aapl['Close'].median():>14.2f}")
print(f"{'Min Close Price:':<30} ${aapl['Close'].min():>14.2f}")
print(f"{'Max Close Price:':<30} ${aapl['Close'].max():>14.2f}")
print(f"{'Price Range:':<30} ${aapl['Close'].max() - aapl['Close'].min():>14.2f}")

print(f"\n{'Average Daily Return:':<30} {aapl['Returns'].mean():>14.4f} ({aapl['Returns'].mean()*100:.2f}%)")
print(f"{'Daily Volatility:':<30} {aapl['Returns'].std():>14.4f} ({aapl['Returns'].std()*100:.2f}%)")

# Annualized metrics
annual_return = aapl['Returns'].mean() * 252
annual_volatility = aapl['Returns'].std() * np.sqrt(252)
sharpe_ratio = (annual_return - 0.02) / annual_volatility

print(f"\n{'Annualized Return:':<30} {annual_return:>14.4f} ({annual_return*100:.2f}%)")
print(f"{'Annualized Volatility:':<30} {annual_volatility:>14.4f} ({annual_volatility*100:.2f}%)")
print(f"{'Sharpe Ratio (RF=2%):':<30} {sharpe_ratio:>14.4f}")

# ==============================================================================
# SECTION 3: VISUALIZATION
# ==============================================================================
print("\n" + "=" * 70)
print("SECTION 3: Price Visualization")
print("=" * 70)

print("\nGenerating price chart with moving averages...")

plt.figure(figsize=(14, 7))
plt.plot(aapl.index, aapl['Close'], label='Close Price', linewidth=2, color='blue')
plt.plot(aapl.index, aapl['MA_20'], label='MA(20)', linewidth=1.5, linestyle='--', alpha=0.8)
plt.plot(aapl.index, aapl['MA_50'], label='MA(50)', linewidth=1.5, linestyle='--', alpha=0.8)
plt.title('AAPL Stock Price with Moving Averages', fontsize=16, fontweight='bold')
plt.xlabel('Date', fontsize=12)
plt.ylabel('Price ($)', fontsize=12)
plt.legend(loc='best')
plt.grid(True, alpha=0.3)
plt.tight_layout()
plt.savefig('tutorial_price_chart.png', dpi=300, bbox_inches='tight')
print("✓ Saved: tutorial_price_chart.png")
plt.show()

# ==============================================================================
# SECTION 4: TECHNICAL INDICATORS
# ==============================================================================
print("\n" + "=" * 70)
print("SECTION 4: Technical Indicator Analysis")
print("=" * 70)

print("\nAnalyzing RSI and MACD indicators...")

fig, axes = plt.subplots(3, 1, figsize=(14, 12))

# Price
axes[0].plot(aapl.index, aapl['Close'], linewidth=2, color='blue')
axes[0].set_title('AAPL Price', fontsize=14, fontweight='bold')
axes[0].set_ylabel('Price ($)', fontsize=12)
axes[0].grid(True, alpha=0.3)

# RSI
axes[1].plot(aapl.index, aapl['RSI'], linewidth=2, color='purple')
axes[1].axhline(70, color='red', linestyle='--', alpha=0.7, label='Overbought (70)')
axes[1].axhline(30, color='green', linestyle='--', alpha=0.7, label='Oversold (30)')
axes[1].fill_between(aapl.index, 30, 70, alpha=0.1)
axes[1].set_title('Relative Strength Index (RSI)', fontsize=14, fontweight='bold')
axes[1].set_ylabel('RSI', fontsize=12)
axes[1].legend()
axes[1].grid(True, alpha=0.3)

# MACD
axes[2].plot(aapl.index, aapl['MACD'], linewidth=2, color='blue', label='MACD')
axes[2].axhline(0, color='black', linestyle='-', alpha=0.5)
axes[2].fill_between(aapl.index, 0, aapl['MACD'], 
                     where=(aapl['MACD'] >= 0), alpha=0.3, color='green', label='Positive')
axes[2].fill_between(aapl.index, 0, aapl['MACD'], 
                     where=(aapl['MACD'] < 0), alpha=0.3, color='red', label='Negative')
axes[2].set_title('MACD', fontsize=14, fontweight='bold')
axes[2].set_ylabel('MACD', fontsize=12)
axes[2].set_xlabel('Date', fontsize=12)
axes[2].legend()
axes[2].grid(True, alpha=0.3)

plt.tight_layout()
plt.savefig('tutorial_indicators.png', dpi=300, bbox_inches='tight')
print("✓ Saved: tutorial_indicators.png")
plt.show()

# ==============================================================================
# SECTION 5: MULTIPLE STOCKS COMPARISON
# ==============================================================================
print("\n" + "=" * 70)
print("SECTION 5: Comparing Multiple Stocks")
print("=" * 70)

print("\nLoading multiple stocks...")
stocks = loader.load_multiple_stocks(['AAPL', 'GOOGL', 'MSFT', 'AMZN', 'TSLA'])
print(f"✓ Loaded {len(stocks)} stocks")

# Merge closing prices
merged = loader.merge_stocks(['AAPL', 'GOOGL', 'MSFT', 'AMZN', 'TSLA'], column='Close')

# Normalize to 100
normalized = (merged / merged.iloc[0]) * 100

print("\nGenerating comparison chart...")
plt.figure(figsize=(14, 7))
colors = ['blue', 'red', 'green', 'orange', 'purple']
for i, column in enumerate(normalized.columns):
    plt.plot(normalized.index, normalized[column], label=column, linewidth=2, color=colors[i])

plt.title('Stock Price Comparison (Normalized to 100)', fontsize=16, fontweight='bold')
plt.xlabel('Date', fontsize=12)
plt.ylabel('Normalized Price', fontsize=12)
plt.legend(loc='best')
plt.grid(True, alpha=0.3)
plt.tight_layout()
plt.savefig('tutorial_comparison.png', dpi=300, bbox_inches='tight')
print("✓ Saved: tutorial_comparison.png")
plt.show()

# Correlation analysis
print("\nCalculating correlation matrix...")
correlation = merged.corr()
print("\nCorrelation Matrix:")
print(correlation)

plt.figure(figsize=(10, 8))
sns.heatmap(correlation, annot=True, fmt='.3f', cmap='coolwarm',
           center=0, square=True, linewidths=1, cbar_kws={"shrink": 0.8})
plt.title('Stock Price Correlation Matrix', fontsize=16, fontweight='bold')
plt.tight_layout()
plt.savefig('tutorial_correlation.png', dpi=300, bbox_inches='tight')
print("✓ Saved: tutorial_correlation.png")
plt.show()

# ==============================================================================
# SECTION 6: FORECASTING
# ==============================================================================
print("\n" + "=" * 70)
print("SECTION 6: Time Series Forecasting")
print("=" * 70)

from scripts.forecast import StockForecaster

print("\nInitializing forecaster...")
forecaster = StockForecaster('../data/AAPL.csv')

print("\nGenerating 30-day forecast using Exponential Smoothing...")
forecast = forecaster.exponential_smoothing_forecast(days=30)

print("\nForecast Summary:")
print(f"Forecast Period: {len(forecast)} days")
print(f"Starting Price: ${forecast['Forecast'].iloc[0]:.2f}")
print(f"Ending Price: ${forecast['Forecast'].iloc[-1]:.2f}")
print(f"Expected Change: ${forecast['Forecast'].iloc[-1] - forecast['Forecast'].iloc[0]:.2f}")

forecaster.plot_forecast(forecast, "Exponential Smoothing", save_path='tutorial_forecast.png')
print("✓ Saved: tutorial_forecast.png")

# ==============================================================================
# SECTION 7: SUMMARY
# ==============================================================================
print("\n" + "=" * 70)
print("TUTORIAL COMPLETE!")
print("=" * 70)

print("\n📊 What You've Learned:")
print("  ✓ How to load and explore stock data")
print("  ✓ Calculate key statistics and metrics")
print("  ✓ Visualize price data with indicators")
print("  ✓ Analyze technical indicators (RSI, MACD)")
print("  ✓ Compare multiple stocks")
print("  ✓ Calculate correlations")
print("  ✓ Generate price forecasts")

print("\n📁 Files Generated:")
print("  ✓ tutorial_price_chart.png")
print("  ✓ tutorial_indicators.png")
print("  ✓ tutorial_comparison.png")
print("  ✓ tutorial_correlation.png")
print("  ✓ tutorial_forecast.png")

print("\n🚀 Next Steps:")
print("  1. Try advanced_ml_tutorial.py for machine learning")
print("  2. Try backtesting_tutorial.py for strategy testing")
print("  3. Explore portfolio optimization")
print("  4. Build your own custom analysis")

print("\n" + "=" * 70)
print("Visit https://rskworld.in/ for more datasets and tutorials!")
print("=" * 70)

print("\n✉️ Contact:")
print("  Author: Molla Samser")
print("  Email: help@rskworld.in")
print("  Phone: +91 93305 39277")
print("=" * 70)

276 lines•10 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