Stock Price Predictor using python

🧠 Build a Stock Price Predictor Using Python in 10 Easy Steps
Have you ever wondered if you could predict the stock market using Python? While we can’t promise you’ll become the next Wall Street guru, building a stock price predictor is a great way to sharpen your data science and Python skills.
In this post, you’ll learn how to use real stock data, clean it, train a simple machine learning model, and predict future prices — all using Python.
🚀 What You'll Build
We’ll create a simple app that:
Pulls real-time stock data (e.g., Apple)
Trains a Linear Regression model
Predicts the stock’s price for the next 30 days
Plots the results
🧰 Tools You’ll Need
Install these libraries if you haven’t yet:
bashCopyEditpip install yfinance pandas numpy scikit-learn matplotlib seaborn
🔟 Step-by-Step Guide
1. 📦 Import Libraries
Start by importing the necessary packages:
pythonCopyEditimport yfinance as yf
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from sklearn.linear_model import LinearRegression
from sklearn.model_selection import train_test_split
from sklearn.metrics import mean_squared_error
2. 📈 Download Stock Data
We’ll use Apple (AAPL) stock for this example:
pythonCopyEditstock_symbol = 'AAPL'
data = yf.download(stock_symbol, start="2018-01-01", end="2024-12-31")
data = data[['Close']] # Use only the 'Close' price
3. 🔮 Add a Prediction Column
Let’s predict the closing price 30 days into the future:
pythonCopyEditfuture_days = 30
data['Prediction'] = data[['Close']].shift(-future_days)
4. 🎯 Prepare the Data
Separate the data into features
and labels
:
pythonCopyEditX = np.array(data.drop(['Prediction'], axis=1))[:-future_days]
y = np.array(data['Prediction'])[:-future_days]
5. 🧪 Train/Test Split
Split the data for training and testing:
pythonCopyEditX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)
6. 🧠 Train the Model
Now let’s fit our model:
pythonCopyEditmodel = LinearRegression()
model.fit(X_train, y_train)
7. 📊 Make Predictions
Test it on unseen data:
pythonCopyEditpredictions = model.predict(X_test)
mse = mean_squared_error(y_test, predictions)
print(f"Mean Squared Error: {mse}")
8. 📅 Predict Future Prices
Use the last 30 days to predict the next 30:
pythonCopyEditx_future = data.drop(['Prediction'], axis=1)[-future_days:]
future_pred = model.predict(x_future)
9. 🖼️ Visualize the Prediction
Let’s see the results:
pythonCopyEditplt.figure(figsize=(14,6))
plt.plot(data['Close'], label='Original Price')
plt.plot(data.index[-future_days:], future_pred, label='Predicted Price (Next 30 Days)', linestyle='--')
plt.title(f"{stock_symbol} Stock Price Prediction")
plt.xlabel("Date")
plt.ylabel("Price (USD)")
plt.legend()
plt.grid()
plt.show()
📈 Output
You'll see a graph that shows:
The historical closing prices
The predicted prices for the next 30 days
🧠 What You Learned
How to fetch real stock data with
yfinance
How to prepare and clean data for ML
Basics of Linear Regression
How to plot predictions using
matplotlib
💡 Bonus: Take It Further
Use more features like
Open
,High
,Volume
Try advanced models like LSTM or Random Forest
Add a GUI using Streamlit
🔚 Conclusion
Predicting stock prices isn't easy — but understanding the process using Python gives you a strong foundation in both data science and finance. Try tweaking this model, test different stocks, and explore deeper insights.
Subscribe to my newsletter
Read articles from Notz directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
