|
import yfinance as yf |
|
import pandas as pd |
|
import numpy as np |
|
import matplotlib.pyplot as plt |
|
from sklearn.model_selection import train_test_split |
|
from sklearn.linear_model import LinearRegression |
|
import gradio as gr |
|
|
|
|
|
stock_tickers = ["AAPL", "GOOGL", "MSFT", "AMZN", "TSLA", "FB", "NFLX", "NVDA", "BRK.B", "DIS"] |
|
|
|
def fetch_data(ticker, start_date, end_date): |
|
"""Fetch historical stock data.""" |
|
data = yf.download(ticker, start=start_date, end=end_date) |
|
return data |
|
|
|
def train_model(data): |
|
"""Train a Linear Regression model on the stock data.""" |
|
data['Date'] = data.index.map(pd.Timestamp.timestamp) |
|
X = data[['Date']] |
|
y = data['Close'] |
|
|
|
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42) |
|
model = LinearRegression() |
|
model.fit(X_train, y_train) |
|
|
|
return model |
|
|
|
def predict_price(model, today): |
|
"""Predict the stock price using the trained model.""" |
|
prediction = model.predict(np.array([[pd.Timestamp(today).timestamp()]])) |
|
return prediction[0] |
|
|
|
def stock_analysis(ticker, start_date, end_date): |
|
"""Perform stock analysis and predictions.""" |
|
|
|
data = fetch_data(ticker, start_date, end_date) |
|
|
|
|
|
model = train_model(data) |
|
|
|
|
|
today = pd.Timestamp.today() |
|
predicted_price = predict_price(model, today) |
|
|
|
percentage_change = ((data['Close'][-1] - data['Close'][0]) / data['Close'][0]) * 100 |
|
highest_value = data['Close'].max() |
|
lowest_value = data['Close'].min() |
|
|
|
|
|
plt.figure(figsize=(12, 6)) |
|
plt.plot(data.index, data['Close'], label='Historical Prices', color='blue') |
|
future_dates = pd.date_range(start=today, periods=90, freq='D') |
|
future_prices = [predict_price(model, date) for date in future_dates] |
|
plt.plot(future_dates, future_prices, label='Predicted Prices', color='orange') |
|
plt.title(f"{ticker} Stock Price Prediction") |
|
plt.xlabel("Date") |
|
plt.ylabel("Price") |
|
plt.legend() |
|
plt.grid() |
|
plt.xticks(rotation=45) |
|
plt.tight_layout() |
|
plt.savefig('stock_analysis.png') |
|
|
|
return ( |
|
predicted_price, |
|
percentage_change, |
|
highest_value, |
|
lowest_value, |
|
'Buy' if predicted_price > data['Close'][-1] else 'Sell', |
|
'stock_analysis.png' |
|
) |
|
|
|
|
|
inputs = [ |
|
gr.inputs.Dropdown(choices=stock_tickers, label="Select Stock Ticker"), |
|
gr.inputs.Date(label="Start Date"), |
|
gr.inputs.Date(label="End Date"), |
|
] |
|
|
|
outputs = [ |
|
gr.outputs.Textbox(label="Predicted Price"), |
|
gr.outputs.Textbox(label="Percentage Change (%)"), |
|
gr.outputs.Textbox(label="Highest Price"), |
|
gr.outputs.Textbox(label="Lowest Price"), |
|
gr.outputs.Textbox(label="Recommendation (Buy/Sell)"), |
|
gr.outputs.Image(label="Stock Price Analysis") |
|
] |
|
|
|
gr.Interface(fn=stock_analysis, inputs=inputs, outputs=outputs, title="Stock Price Predictor").launch() |
|
|