0% found this document useful (0 votes)
19 views2 pages

LSTM Crypto Price Prediction Script

The document outlines a Python script that predicts cryptocurrency prices using an LSTM model. It retrieves historical prices for Bitcoin, scales the data, trains the model, and sends an email alert if the predicted price exceeds a specified threshold. Additionally, it includes functions for data retrieval, model training, and email notification.

Uploaded by

dhxnugowdaa
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
19 views2 pages

LSTM Crypto Price Prediction Script

The document outlines a Python script that predicts cryptocurrency prices using an LSTM model. It retrieves historical prices for Bitcoin, scales the data, trains the model, and sends an email alert if the predicted price exceeds a specified threshold. Additionally, it includes functions for data retrieval, model training, and email notification.

Uploaded by

dhxnugowdaa
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd

import numpy as np

import pandas as pd
import yfinance as yf
from [Link] import MinMaxScaler
import torch
import [Link] as nn
from datetime import datetime
import smtplib
from [Link] import MIMEText
import [Link] as plt

def get_historical_prices(symbol, start_date, end_date):


df = [Link](symbol, start=start_date, end=end_date)
return df['Close'].[Link](-1, 1)
class LSTM([Link]):
def __init__(self, input_size=1, hidden_layer_size=100, output_size=1):
super().__init__()
self.hidden_layer_size = hidden_layer_size
[Link] = [Link](input_size, hidden_layer_size)
[Link] = [Link](hidden_layer_size, output_size)
self.hidden_cell = ([Link](1, 1, self.hidden_layer_size),
[Link](1, 1, self.hidden_layer_size))

def forward(self, input_seq):


lstm_out, self.hidden_cell = [Link](input_seq.view(len(input_seq), 1,
1), self.hidden_cell)
predictions = [Link](lstm_out.view(len(input_seq), -1))
return predictions[-1]

def send_email(subject, body):


sender = "dhxnugowdaa@[Link]"
receiver = "dhxnugowdaa@[Link]"
sender_password = "royd fvte qwpt cmut"
msg = MIMEText(body)
msg['Subject'] = subject
msg['From'] = sender
msg['To'] = receiver

try:
with [Link]('[Link]', 587) as server:
[Link]()
[Link](sender, sender_password)
[Link](sender, receiver, msg.as_string())
print("Email sent successfully.")
except Exception as e:
print(f"Email failed: {e}")
crypto_symbol = 'BTC-USD'
start_date = '2025-01-01'
end_date = [Link]().strftime('%Y-%m-%d')

prices = get_historical_prices(crypto_symbol, start_date, end_date)

[Link](prices)
[Link](f'{crypto_symbol} Historical Prices')
[Link]('Days')
[Link]('Price (USD)')
[Link]()
scaler = MinMaxScaler(feature_range=(0, 1))
prices_scaled = scaler.fit_transform(prices)

X_train, y_train = [], []


for i in range(60, len(prices_scaled)):
X_train.append(prices_scaled[i-60:i, 0])
y_train.append(prices_scaled[i, 0])

X_train = torch.from_numpy([Link](X_train)).float()
y_train = torch.from_numpy([Link](y_train)).float()

model = LSTM()
loss_function = [Link]()
optimizer = [Link]([Link](), lr=0.001)

epochs = 25
for epoch in range(epochs):
for seq, labels in zip(X_train, y_train):
optimizer.zero_grad()
model.hidden_cell = ([Link](1, 1, model.hidden_layer_size),
[Link](1, 1, model.hidden_layer_size))
y_pred = model(seq)
single_loss = loss_function(y_pred, labels)
single_loss.backward()
[Link]()

[Link]()
with torch.no_grad():
last_60_days = prices[-60:].reshape(-1, 1)
last_60_days_scaled = [Link](last_60_days)
X_test = torch.from_numpy(last_60_days_scaled).float()
model.hidden_cell = ([Link](1, 1, model.hidden_layer_size),
[Link](1, 1, model.hidden_layer_size))
predicted_price_scaled = model(X_test)
predicted_price =
scaler.inverse_transform([Link]([[predicted_price_scaled.item()]]))

threshold = 50000
if predicted_price[0][0] > threshold:
subject = "Crypto Price Alert"
body = f"The predicted price of {crypto_symbol} has crossed ${threshold}.\
nPredicted Price: ${predicted_price[0][0]:,.2f}"
send_email(subject, body)
else:
print(f"No alert. Predicted Price: ${predicted_price[0][0]:,.2f}")

Common questions

Powered by AI

To make new predictions, the system extracts the last 60 days of historical price data, reshapes it, and scales it with the same MinMaxScaler used during training. This scaled data is then transformed into a format compatible with the LSTM model, allowing it to generate predictions based on recent historical trends .

The LSTM model training process involves iterating over the training data for a set number of epochs (25 in this case). Key components include: initializing the hidden state for each sequence, predicting outputs using the current state of the model, calculating the loss using MSELoss, backpropagating the errors, and updating the weights using the Adam optimizer. This iterative process helps the model learn the patterns in the historical price data .

Hard-coding email credentials poses a significant security risk as it exposes sensitive information and could be exploited if the script is accessed by unauthorized users. A more secure alternative would be to use environment variables to store credentials securely or utilize a secure third-party service for authentication .

Resetting the hidden cell state before each new sequence prediction avoids leakage of information from previous sequences, ensuring that each prediction is based solely on the current input data. This practice helps maintain model integrity by not carrying over states that might contaminate new sequence predictions .

Historical price data of cryptocurrencies is obtained using the Yahoo Finance API, specifically through the `yf.download` function from the yfinance library, by specifying the symbol and the date range . The closing prices are extracted and reshaped for further processing. In predictive modeling, this data is scaled using MinMaxScaler, prepared into sequences for LSTM neural network usage, and utilized to train the model for price prediction purposes .

MinMaxScaler is used to scale the cryptocurrency price data to the range (0, 1) to ensure that all input features have a consistent influence on the performance of the neural network. This scaling prevents features with larger ranges from dominating the loss function and typically speeds up convergence .

The LSTM (Long Short-Term Memory) model is crucial for capturing long-term dependencies in sequential data, such as time series, which makes it suitable for cryptocurrency price prediction. The model is structured with an input size of 1 (price data), a hidden layer size of 100, and an output size of 1. It consists of an LSTM layer followed by a linear layer to transform the LSTM outputs into predictions .

The script uses the `inverse_transform` method of the MinMaxScaler to convert predictions from the scaled range back into the original price scale. This step is necessary to interpret the model's prediction in terms of actual market prices, providing actionable insights and comparisons to historical data .

An email alert is triggered in the scenario where the predicted price of the cryptocurrency exceeds a predefined threshold of $50,000. This threshold acts as a trigger point where a subject and body message are formatted, and the send_email function sends the message to the recipient .

PyTorch is used in this system to leverage its dynamic computation graph, which allows for flexible model building and easier debugging. Its efficient tensor computations and seamless GPU integration make it an ideal framework for training deep learning models like the LSTM used in predicting cryptocurrency prices .

You might also like