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

NTFX Price Prediction

Uploaded by

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

NTFX Price Prediction

Uploaded by

Narenkumar. N
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 5

Netflix Stock Price Prediction:

1. Import Libraries
from flask import Flask, render_template, request, send_from_directory
import os
import datetime
import pandas as pd
import numpy as np
import joblib
from tensorflow.keras.models import load_model
import matplotlib.pyplot as plt
import matplotlib.dates as mdates

• Flask: Manages routes, handles user input, and serves templates.


• os: Manages file directories for saving prediction images.
• datetime: Handles date and time operations.
• pandas: Processes stock data.
• numpy: Handles numerical data for predictions.
• joblib: Loads the scaler used for data normalization.
• load_model: Loads the pre-trained LSTM model.
• matplotlib: Generates prediction graphs.
• mdates: Formats date labels in the prediction graph.

2. Initialize Flask App and Configurations


app = Flask( name )
app.config['PREDICTIONS_FOLDER'] = 'static/predictions'

• Creates a Flask application instance.


• Sets a folder to store prediction graphs.

3. Load Model and Data


# Load model and scaler
model = load_model('lstm_model.h5')
scaler = joblib.load('scaler.pkl')

# Load and preprocess the dataset


data = pd.read_csv('NFLX_dataset.csv')
data['Date'] = pd.to_datetime(data['Date'])
data.set_index('Date', inplace=True)
data = data[['Close']]
• Loads the LSTM model (lstm_model.h5) and the scaler (scaler.pkl).
• Reads the stock dataset (NFLX_dataset.csv), converts the Date column to
datetime, and sets it as the index.
• Keeps only the Close column (closing prices).

4. Feature Engineering
# Feature Engineering (same as during training)
data['5_MA'] = data['Close'].rolling(window=5).mean()
data['30_MA'] = data['Close'].rolling(window=30).mean()
data['Volatility'] = data['Close'].rolling(window=5).std()
data['Returns'] = data['Close'].pct_change()
data.dropna(inplace=True)

• Calculates additional features required for predictions:


– 5_MA: 5-day moving average.
– 30_MA: 30-day moving average.
– Volatility: 5-day standard deviation of prices.
– Returns: Percentage change in price.
• Removes rows with missing values introduced by moving averages.

5. Scale Data
# Scale the data with all features
data_scaled = scaler.transform(data[['Close', '5_MA', '30_MA',
'Volatility', 'Returns']])

• Uses the preloaded scaler to normalize the dataset.

6. Define Custom Prediction Function


def predict_custom_dates(custom_dates):
custom_dates_datetime = []
for date in custom_dates:
try:

custom_dates_datetime.append(datetime.datetime.strptime(date, '%d-%m-
%Y'))
except ValueError:
print(f"Invalid date format: {date}. Skipping this date.")

if not custom_dates_datetime:
return [], []

# Prepare input for prediction


last_lookback_data = data_scaled[-120:]
last_input = np.array([last_lookback_data])

custom_predictions = []
for _ in custom_dates_datetime:
prediction = model.predict(last_input)
custom_predictions.append(prediction[0, 0])

prediction_padded = np.concatenate((prediction, np.zeros((1,


4))), axis=1)
prediction_reshaped = prediction_padded.reshape(1, 1, 5)
last_input = np.concatenate([last_input[:, 1:, :],
prediction_reshaped], axis=1)

custom_predictions = np.array(custom_predictions).reshape(-1, 1)
custom_predictions =
scaler.inverse_transform(np.concatenate((custom_predictions,
np.zeros((custom_predictions.shape[0], 4))), axis=1))[:, 0]

return custom_dates_datetime, custom_predictions

• Parses user-provided dates.


• Prepares the last 120 scaled data points for predictions.
• Iteratively predicts prices for each date using:
– Current model input.
– Updated predictions for the next step.
• Converts predictions back to the original scale.

7. Generate Prediction Image


def save_prediction_image(predicted_dates, predicted_prices):
if not os.path.exists(app.config['PREDICTIONS_FOLDER']):
os.makedirs(app.config['PREDICTIONS_FOLDER'])

timestamp = datetime.datetime.now().strftime("%d%m%Y_%H%M%S")
prediction_filename = f"prediction_{timestamp}.png"
filepath = os.path.join(app.config['PREDICTIONS_FOLDER'],
prediction_filename)

# Plot actual data and predictions


plt.figure(figsize=(14, 8))
last_month_data = data[-120:]
last_month_actual = scaler.inverse_transform(data_scaled[-
120:, :])[:, 0]
plt.plot(last_month_data.index, last_month_actual, label='Actual
Price (Last 120 Days)')
plt.plot(predicted_dates, predicted_prices, label='Forecasted
Prices', marker='o')
plt.legend()
plt.savefig(filepath)
plt.close()

return prediction_filename

• Creates a graph showing:


– Actual prices for the last 120 days.
– Predicted prices for custom dates.
• Saves the graph in the predictions
folder.

8. Route for Home Page


@app.route('/', methods=['GET', 'POST'])
def index():
last_120_days_data = data[-120:]
first_price = last_120_days_data['Close'].iloc[0]
last_price = last_120_days_data['Close'].iloc[-1]
price_change = last_price - first_price
percentage_change = (price_change / first_price) * 100

insights = {
'first_price': round(first_price, 2),
'last_price': round(last_price, 2),
'price_change': round(price_change, 2),
'percentage_change': round(percentage_change, 2),
'trend': "rose" if price_change > 0 else "fell"
}

if request.method == 'POST':
date_input = request.form.get('dates')
custom_dates = [date.strip() for date in
date_input.split(",")]

predicted_dates, predicted_prices =
predict_custom_dates(custom_dates)

formatted_dates = [date.strftime('%d-%m-%Y') for date in


predicted_dates]
predictions = list(zip(formatted_dates, predicted_prices))

image_url = save_prediction_image(predicted_dates,
predicted_prices)

return render_template('index.html', image_url=image_url,


predictions=predictions, insights=insights)

return render_template('index.html', image_url=None,


insights=insights)
• GET Request: Displays the form and insights.
• POST Request:
– Processes input dates.
– Calls prediction and graph-generation functions.
– Passes results to the index.html template.

9. Serve Images
@app.route('/static/predictions/<filename>')
def display_image(filename):
return send_from_directory(app.config['PREDICTIONS_FOLDER'],
filename)

• Serves prediction images dynamically.

10. Run the App


if name == ' main
':
app.run(debug=True)
• Starts the app in debug mode for easier development.

You might also like