Stock Price Prediction using Machine Learning in Python

Stock Price Prediction using Machine Learning in Python

Predicting stock prices is a complex task and falls into the realm of time series forecasting. Here, I'll guide you through a basic example using machine learning. However, keep in mind that predicting stock prices with high accuracy is extremely challenging and even state-of-the-art models cannot guarantee profitability in real-world trading.

For this example, we'll use the Long Short Term Memory (LSTM) network, which is a type of Recurrent Neural Network (RNN) well-suited for time series forecasting.

1. Install necessary libraries:

pip install numpy pandas tensorflow scikit-learn yfinance 

We'll use yfinance to fetch stock data.

2. Fetching and preparing the data:

import yfinance as yf import numpy as np import pandas as pd from sklearn.preprocessing import MinMaxScaler # Fetch data data = yf.download('AAPL', start='2010-01-01', end='2023-01-01') # Only use 'Close' values data = data[['Close']] # Normalize the data scaler = MinMaxScaler() scaled_data = scaler.fit_transform(data.values) # Create a dataset with 60 timesteps and 1 output X = [] y = [] for i in range(60, len(scaled_data)): X.append(scaled_data[i-60:i, 0]) y.append(scaled_data[i, 0]) X, y = np.array(X), np.array(y) X = np.reshape(X, (X.shape[0], X.shape[1], 1)) 

3. Building the LSTM model:

from tensorflow.keras.models import Sequential from tensorflow.keras.layers import LSTM, Dense, Dropout model = Sequential() model.add(LSTM(units=50, return_sequences=True, input_shape=(X.shape[1], 1))) model.add(Dropout(0.2)) model.add(LSTM(units=50, return_sequences=True)) model.add(Dropout(0.2)) model.add(LSTM(units=50)) model.add(Dropout(0.2)) model.add(Dense(units=1)) model.compile(optimizer='adam', loss='mean_squared_error') 

4. Training the model:

model.fit(X, y, epochs=25, batch_size=32) 

5. Making predictions:

test_data = yf.download('AAPL', start='2023-01-01', end='2023-10-01')['Close'].values total_dataset = pd.concat((data['Close'], yf.download('AAPL', start='2023-01-01', end='2023-10-01')['Close']), axis=0) model_inputs = total_dataset[len(total_dataset) - len(test_data) - 60:].values model_inputs = model_inputs.reshape(-1, 1) model_inputs = scaler.transform(model_inputs) # Create test data X_test = [] for i in range(60, model_inputs.shape[0]): X_test.append(model_inputs[i-60:i, 0]) X_test = np.array(X_test) X_test = np.reshape(X_test, (X_test.shape[0], X_test.shape[1], 1)) # Predict predicted_prices = model.predict(X_test) predicted_prices = scaler.inverse_transform(predicted_prices) 

6. Visualization:

import matplotlib.pyplot as plt plt.figure(figsize=(14,5)) plt.plot(test_data, color='blue', label='Actual Apple Stock Price') plt.plot(predicted_prices, color='red', label='Predicted Apple Stock Price') plt.title('Apple Stock Price Prediction') plt.xlabel('Time') plt.ylabel('Apple Stock Price') plt.legend() plt.show() 

Note: The above code provides a basic foundation. However, real-world stock price prediction requires consideration of various factors, including but not limited to financial indicators, news sentiment, and even global events. Use machine learning models responsibly and remember that using them for actual trading is risky.


More Tags

uicontrolstate symlink server-side tint androiddesignsupport sql apache-spark-sql pipes-filters libusb azureservicebus

More Programming Guides

Other Guides

More Programming Examples