Spaces:
Sleeping
Sleeping
Create app.py
Browse files
app.py
ADDED
|
@@ -0,0 +1,95 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import yfinance as yf
|
| 2 |
+
import pandas as pd
|
| 3 |
+
import numpy as np
|
| 4 |
+
import matplotlib.pyplot as plt
|
| 5 |
+
import gradio as gr
|
| 6 |
+
from sklearn.linear_model import LinearRegression
|
| 7 |
+
from transformers import pipeline
|
| 8 |
+
|
| 9 |
+
# Load Hugging Face summarization pipeline
|
| 10 |
+
summarizer = pipeline("summarization", model="facebook/bart-large-cnn")
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
# Step 1: Fetch historical stock data
|
| 14 |
+
def get_stock_data(ticker):
|
| 15 |
+
df = yf.download(ticker, start="2020-01-01", end="2024-12-31")
|
| 16 |
+
return df[['Close']]
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
# Step 2: Prepare training data
|
| 20 |
+
def prepare_data(df):
|
| 21 |
+
df['Target'] = df['Close'].shift(-1)
|
| 22 |
+
df = df.dropna()
|
| 23 |
+
X = df[['Close']]
|
| 24 |
+
y = df['Target']
|
| 25 |
+
return X, y
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
# Step 3: Train a simple regression model
|
| 29 |
+
def train_model(X, y):
|
| 30 |
+
model = LinearRegression()
|
| 31 |
+
model.fit(X, y)
|
| 32 |
+
return model
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
# Step 4: Predict future prices (next 7 days)
|
| 36 |
+
def predict_future(model, last_price, days=7):
|
| 37 |
+
predictions = []
|
| 38 |
+
current = last_price
|
| 39 |
+
for _ in range(days):
|
| 40 |
+
next_price = model.predict([[current]])[0]
|
| 41 |
+
predictions.append(next_price)
|
| 42 |
+
current = next_price
|
| 43 |
+
return predictions
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
# Step 5: Generate AI explanation using Hugging Face summarizer
|
| 47 |
+
def generate_explanation(df_tail):
|
| 48 |
+
text_data = df_tail.to_string()
|
| 49 |
+
summary = summarizer(text_data, max_length=100, min_length=30, do_sample=False)
|
| 50 |
+
return summary[0]['summary_text']
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
# Step 6: Combine all into a Gradio interface function
|
| 54 |
+
def stock_predictor(ticker):
|
| 55 |
+
try:
|
| 56 |
+
df = get_stock_data(ticker)
|
| 57 |
+
X, y = prepare_data(df)
|
| 58 |
+
model = train_model(X, y)
|
| 59 |
+
last_price = X.iloc[-1][0]
|
| 60 |
+
predictions = predict_future(model, last_price)
|
| 61 |
+
|
| 62 |
+
# Convert predictions to a plot
|
| 63 |
+
plt.figure()
|
| 64 |
+
plt.plot(range(1, 8), predictions, marker='o')
|
| 65 |
+
plt.title(f"{ticker} Stock Price Predictions (Next 7 Days)")
|
| 66 |
+
plt.xlabel("Days")
|
| 67 |
+
plt.ylabel("Predicted Price")
|
| 68 |
+
plt.grid(True)
|
| 69 |
+
plot_path = "prediction_plot.png"
|
| 70 |
+
plt.savefig(plot_path)
|
| 71 |
+
plt.close()
|
| 72 |
+
|
| 73 |
+
# Generate explanation using last 5 days of data
|
| 74 |
+
explanation = generate_explanation(df.tail())
|
| 75 |
+
|
| 76 |
+
return plot_path, predictions, explanation
|
| 77 |
+
|
| 78 |
+
except Exception as e:
|
| 79 |
+
return None, [], f"Error: {str(e)}"
|
| 80 |
+
|
| 81 |
+
|
| 82 |
+
# Step 7: Gradio Interface
|
| 83 |
+
interface = gr.Interface(
|
| 84 |
+
fn=stock_predictor,
|
| 85 |
+
inputs=gr.Textbox(label="Enter Stock Ticker (e.g., AAPL)"),
|
| 86 |
+
outputs=[
|
| 87 |
+
gr.Image(label="📈 Predicted Price Plot"),
|
| 88 |
+
gr.Textbox(label="📊 Predicted Prices (Next 7 Days)"),
|
| 89 |
+
gr.Textbox(label="🧠 AI Explanation of Recent Trends")
|
| 90 |
+
],
|
| 91 |
+
title="Stock Price Predictor + AI Insight Generator",
|
| 92 |
+
description="Enter a stock ticker (like AAPL or GOOG) to see predicted prices and a natural language explanation of recent trends using Hugging Face models."
|
| 93 |
+
)
|
| 94 |
+
|
| 95 |
+
interface.launch()
|