File size: 4,311 Bytes
0dfdfb5 b0bd1b7 9e7913b f2f0925 22f5b92 f2f0925 22f5b92 b0bd1b7 f2f0925 22f5b92 f2f0925 b0bd1b7 22f5b92 f2f0925 22f5b92 f2f0925 b0bd1b7 22f5b92 f2f0925 22f5b92 f2f0925 22f5b92 f2f0925 22f5b92 70363ab f2f0925 22f5b92 70363ab f2f0925 22f5b92 f2f0925 70363ab f2f0925 22f5b92 f2f0925 22f5b92 f2f0925 22f5b92 f2f0925 0dfdfb5 22f5b92 0dfdfb5 f2f0925 b0bd1b7 f2f0925 22f5b92 f2f0925 b0bd1b7 f2f0925 22f5b92 b0bd1b7 f2f0925 22f5b92 f2f0925 22f5b92 f2f0925 971d03b 22f5b92 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 |
import yfinance as yf
import pandas as pd
# Fetch stock data from Yahoo Finance
def get_stock_data(ticker, start_date, end_date):
stock_data = yf.download(ticker, start=start_date, end=end_date)
if stock_data.empty:
raise ValueError("No data found for the given ticker and date range.")
return stock_data
# Example usage
ticker = 'AAPL'
start_date = '2023-01-01'
end_date = '2024-01-01'
data = get_stock_data(ticker, start_date, end_date)
print(data.head())
from sklearn.preprocessing import MinMaxScaler
# Preprocess stock data
def preprocess_data(stock_data):
scaler = MinMaxScaler(feature_range=(0, 1)) # Normalizing the close prices
scaled_data = scaler.fit_transform(stock_data[['Close']].values)
return scaled_data, scaler
# Preprocess the stock data
scaled_data, scaler = preprocess_data(data)
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import LSTM, Dense
# Define and train an LSTM model
def create_lstm_model(input_shape):
model = Sequential()
model.add(LSTM(units=50, return_sequences=True, input_shape=input_shape))
model.add(LSTM(units=50))
model.add(Dense(units=1)) # Predicting stock price
model.compile(optimizer='adam', loss='mean_squared_error')
return model
# Prepare data for training the model
def train_model(stock_data, window_size=60):
X_train, y_train = [], []
for i in range(window_size, len(stock_data)):
X_train.append(stock_data[i-window_size:i, 0])
y_train.append(stock_data[i, 0])
X_train, y_train = np.array(X_train), np.array(y_train)
X_train = X_train.reshape((X_train.shape[0], X_train.shape[1], 1))
model = create_lstm_model((X_train.shape[1], 1))
model.fit(X_train, y_train, epochs=10, batch_size=32)
return model
# Train the LSTM model
lstm_model = train_model(scaled_data)
import numpy as np
def predict_future_prices(model, scaler, recent_data, days_to_predict=90):
predictions = []
input_data = recent_data[-60:].reshape(1, 60, 1) # Using the last 60 days to predict
for _ in range(days_to_predict):
pred_price = model.predict(input_data)[0, 0]
predictions.append(pred_price)
input_data = np.append(input_data[:, 1:, :], [[pred_price]], axis=1)
# Inverse transform to get the original prices
predicted_prices = scaler.inverse_transform(np.array(predictions).reshape(-1, 1))
return predicted_prices
# Predict future stock prices
recent_data = scaled_data[-60:]
future_prices = predict_future_prices(lstm_model, scaler, recent_data)
import gradio as gr
import matplotlib.pyplot as plt
# Gradio function to predict stock prices and display results
def stock_prediction_app(ticker, start_date, end_date):
stock_data = get_stock_data(ticker, start_date, end_date)
scaled_data, scaler = preprocess_data(stock_data)
# Train the model on the selected stock data
model = train_model(scaled_data)
# Make predictions for the next 90 days
future_prices = predict_future_prices(model, scaler, scaled_data)
# Plot the historical and future stock prices
plt.figure(figsize=(10, 6))
plt.plot(stock_data.index, stock_data['Close'], label='Historical Prices')
future_dates = pd.date_range(end=stock_data.index[-1], periods=90)
plt.plot(future_dates, future_prices, label='Predicted Prices', linestyle='--')
plt.title(f'{ticker} Stock Price Prediction')
plt.xlabel('Date')
plt.ylabel('Price')
plt.legend()
plt.savefig('stock_prediction.png')
return f"The predicted stock price for the next 3 months is shown in the graph.", 'stock_prediction.png'
# Define Gradio interface
tickers = ['AAPL', 'MSFT', 'GOOGL', 'TSLA', 'AMZN', 'FB', 'NFLX', 'NVDA', 'INTC', 'IBM']
app = gr.Blocks()
with app:
gr.Markdown("# Stock Buy/Sell Prediction App")
ticker = gr.Dropdown(tickers, label="Select Stock Ticker")
start_date = gr.Date(label="Start Date")
end_date = gr.Date(label="End Date")
predict_button = gr.Button("Predict")
output_text = gr.Textbox(label="Prediction Result")
output_image = gr.Image(label="Stock Price Graph")
predict_button.click(fn=stock_prediction_app, inputs=[ticker, start_date, end_date], outputs=[output_text, output_image])
app.launch()
|