PyTorch example to Forcast Stock Price based on 10 days Dataset

CK CK 3788 
Created at  
654 0 0

This code starts by creating synthetic stock price data, then it proceeds to define a simple linear neural network model. The model is trained on the synthetic data, and finally, it attempts to predict the stock price for the next day based on the last 10 days of data.

Remember, this is a basic example for educational purposes. Real-world applications require careful consideration of model architecture, data preprocessing, feature selection, and potentially the use of more complex models such as LSTMs or GRUs for handling sequences in time-series data.

import torch
import torch.nn as nn
import numpy as np

# Seed for reproducibility
np.random.seed(42)
torch.manual_seed(42)

# Synthetic stock price data generation
prices = np.sin(np.arange(100) / 20.0) + np.random.normal(0, 0.1, 100) + 5

# Prepare the dataset
def create_inout_sequences(input_data, tw):
    inout_seq = []
    L = len(input_data)
    for i in range(L-tw):
        train_seq = input_data[i:i+tw]
        train_label = input_data[i+tw:i+tw+1]
        inout_seq.append((train_seq ,train_label))
    return inout_seq

seq_length = 10  # Using 10 days of prices to predict the next day
sequences = create_inout_sequences(prices, seq_length)
sequences = [(torch.tensor(s, dtype=torch.float32), torch.tensor([t], dtype=torch.float32)) for s, t in sequences]

# Model definition
class StockPredictor(nn.Module):
    def __init__(self, input_size=1, hidden_layer_size=100, output_size=1):
        super(StockPredictor, self).__init__()
        self.linear = nn.Linear(input_size * seq_length, hidden_layer_size)
        self.linear2 = nn.Linear(hidden_layer_size, output_size)

    def forward(self, input_seq):
        input_seq = input_seq.view(-1, seq_length)
        predictions = torch.relu(self.linear(input_seq))
        predictions = self.linear2(predictions)
        return predictions

# Model initialization
model = StockPredictor(input_size=1, hidden_layer_size=100, output_size=1)
loss_function = nn.MSELoss()
optimizer = torch.optim.Adam(model.parameters(), lr=0.001)

# Training the model
epochs = 150
for i in range(epochs):
    for seq, labels in sequences:
        optimizer.zero_grad()
        y_pred = model(seq)
        single_loss = loss_function(y_pred, labels)
        single_loss.backward()
        optimizer.step()
    if i % 25 == 0:
        print(f'epoch: {i:3} loss: {single_loss.item():10.8f}')

# Predicting the stock price
test_input = torch.tensor(prices[-seq_length:], dtype=torch.float32)
with torch.no_grad():
    model.eval()
    predicted_stock_price = model(test_input)
    print(f'Predicted stock price for the next day: {predicted_stock_price.item():.2f}')

 

Tags Artificial Intelligence Data Science Deep Learning Economic Forecasting Financial Analysis Financial Modeling Linear Regression Machine Learning Neural Networks PyTorch Python Programming Quantitative Finance Stock Price Prediction Time Series Analysis Time Series Forecasting Facebook X
Comments 0
Similar posts
  1. Predicting Buyer Preferences with PyTorch: A Deep Learning Approach
    1,234
  2. Mastering Ad Budget Throttling: Static, PID, and ML Strategies
    325
  3. Ad Impression Forecasting (aka Ad Inventory Forecasting): Architecting for Scale, Speed, and Accuracy
    335
  4. AI-Powered Ad Fraud Detection: Architectural Strategies
    337
  5. Brand Safety: AI-Driven Content Moderation on AWS
    738
  6. Milvus & FAISS: Decoding Their ML Synergy
    286
  7. TikTok's Recommendation System - Monolith
    300
  8. FAISS Already Does ANN... So Why Do Top Teams Still Pay for SageMaker?
    314
  9. Building Initial Virtual Environment at Python - The first step you should do for Python Programming
    560
  10. Machine Learning Models for Ad Detection from a Video Stream
    194
  11. Image Embeddings for Vector Databases
    254
  12. Building a MCP server in PHP
    638
  13. Vector Databases: From Embeddings to Application
    322
  14. Python ML Technologies used for the target Segmentation
    381
  15. TensorRT for LLMs: Speed, Scale, and Why Startups Choose It Over TensorFlow
    467
  16. Coding Revolution with Claude Code & MoAI ADK(Agent Development Kit)
    738
  17. Demystifying FAISS: Your Guide to ANN(Approximate Nearest Neighbor) Search
    326
  18. Is PyTorch Dead? Deep Learning's Enduring Role Beyond LLMs & Essential Skills
    699
  19. Netflix's Recommendation System
    429
  20. Arm Kernel DNNs: Powering Efficient AI at the Edge
    229
  21. Autonomous Vehicle Machine Learning (AV ML): An Architectural Review
    421
  22. Why AI-DLC is the New Paradigm for Development?
    343
  23. Designing an Enterprise ML Experiment Tracking and Reproducibility Platform: System Requirements and Architecture
    318
  24. AI-DLC vs. AI-SDLC: Model-Centric vs. System-Centric AI Development
    267
  25. Forecasting with Linear Regression and KNN Regression in Python
    929
  26. Forecasting the Weather with PyTorch: A Beginner's Guide to Temperature Prediction
    1,444
  27. Reinforcement Learning–Based Methods for CTR Improvement based on Recommendation System
    273
  28. YouTube's Recommendation System
    269
  29. Mastering Model Persistence: Saving and Loading Trained Machine Learning Models in Python
    1,165
  30. Harnessing the Power of Random Forest Algorithm in Python
    659
  1. Creating mp3 audio file based on the text input with Python
    470
  2. Implementing Text To Speech / Audio with Python3 and pyttsx3
    358
  3. Python Simplified Assignment Operators
    535
  4. Trackback module used for Python Threading debugging
    847
  5. Python Flask with simple HTML files to server web pages along with API
    931
  6. Python Flask web server tutorial from the scratch
    626
  7. Simple Web Server based in Python
    381
  8. Thread Implementation in Python
    511
  9. A shell script that activates a Python virtual environment and then runs a specific Python script
    747
  10. Learning about Python Multiprocessing Technique
    594
  11. Simple Example to get the total number of records in BigQuery with Python
    668
  12. Using BigQuery in Python
    414
  13. Python Web Programming based on Django from the Scratch
    390
  14. Flink with Python: Core Concepts, Kafka Integration, and Architectural Trade-offs
    193
  15. How do I determine the client IP type in Python - IPv4 or IPv6
    766
  16. Implementing a Versatile DNS Server in Python: Handling A, AAAA, CNAME, and TXT Records
    1,078
  17. Dynamic DNS Made Easy: Building a Python-Based Solution
    796
  18. Save clustering result (aka dictionary) in JSON and Reuse loaded result
    382
  19. Uvicorn, Gunicorn: Proving Your Production Prowess
    401
  20. Understanding and Implementing K-Nearest Neighbors (KNN) Algorithm in Python
    636
  21. Mastering Random Forest Regression: A Comprehensive Guide with Python Examples
    1,104
  22. Simple Python Clustering Example based on the high school students' score
    345
  23. Getting Started with PyTorch: A Beginner's Guide to Building Your First Neural Network
    801
  24. Memory Problems with Python Arrays? Discover Dask Array
    329
  25. Python Implementation of Linear Regression
    842
  26. Mastering Supervised Machine Learning with Python: A Comprehensive Guide
    1,060
  27. Mastering AI: A Beginner's Guide to Python Programming and Beyond
    1,040
Recently updated
  1. Google OAuth Token Expiration: Causes and Solutions
    29
  2. Why 100% SEO Guarantees Better User Engagement and How to Achieve It in Your Service
    55
  3. Why SPF and DKIM Are Essential for Linux Email Servers?
    49
  4. How do I create animated background for Google Meet?
    22,913
  5. MaxMind GeoLite2 vs. DB-IP Lite vs. ip-api.com: Choosing the Right Free IP Geolocation Solution
    271
  6. Meet Valkey: Why Redis Changed Its License, Why Valkey is Better, and How to Use It as a Drop-in Replacement
    103
  7. How Rogue Web Scrapers Are Stealing My Content and Destroying My Server
    168
  8. Array of arguments passed to script in PHP
    97
  9. Invalid Auction Storms in Ad Tech
    106
  10. Building MRC-Compliant Instrumentation in Ad Tech: Implementation Steps and Key Challenges
    207
  11. The Two Clocks of Ad Server Architecture
    77
  12. Frequency Cap Architecture Overview
    526
  13. Collecting Proof-of-Play from 100,000 Screens
    152
  14. Vector Search in Relational Databases (RDBs): Trends & Usage Environments
    302
  15. What is RedisVL?
    114
  16. Designing a Skill Registry Architecture: Minimize Token Usage and Maximize AI Performance
    246
  17. TPU & GPU Cluster Management Tools
    257
  18. The Concept of Scaffolding in AI Agents
    244
  19. Beyond Static Pipelines: Architecting LLM Multi-Agent Systems for Autonomous Workflow Orchestration
    596
  20. Fine-Tuning Open-Weight LLMs: Training, Licensing, and Deploying Custom Models with Ollama
    353
  21. Inside the Next-Generation Streaming Architecture: Ultra-Low Latency, SGAI, and AI Codecs
    206
  22. Machine Learning: Training vs. Ranking
    229
  23. The Continuous Learning Machine: Designing a Loop That Actually Turns
    228
  24. The Next-Gen Low-Latency Standards: LL-HLS & MoQ
    202
  25. Designing a Data Curation System Around a Vector Database
    230
  26. Extracting Context from Live Video: The Architecture Got Simpler When We Stopped Building Features
    263
  27. The New Ad Stack Behind Live Sports Streaming: Inside SGAI, EABN, and the Standards Race to Fix Live Monetization
    672
  28. Designing MLOps Architectures to Handle Seasonal Data Drift in EV Fleet Models
    201
  29. From 15 to 40+ FPS: Accelerating PyTorch Object Detection on Automotive ECUs
    232
  30. Understanding Data Lineage
    272