Spaces:
Runtime error
Runtime error
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,65 +1,115 @@
|
|
| 1 |
-
import cv2
|
| 2 |
-
import gradio as gr
|
| 3 |
import torch
|
| 4 |
-
|
| 5 |
import numpy as np
|
| 6 |
-
|
| 7 |
-
|
| 8 |
-
|
| 9 |
-
|
| 10 |
-
|
| 11 |
|
| 12 |
-
#
|
| 13 |
-
|
| 14 |
-
pipe = StableDiffusionPipeline.from_pretrained(model_id, torch_dtype=torch.float16)
|
| 15 |
-
pipe = pipe.to("cuda")
|
| 16 |
|
| 17 |
-
#
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
|
|
|
|
|
|
| 21 |
|
| 22 |
-
#
|
| 23 |
-
def
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
prompt = tokenizer.decode(summary_ids[0], skip_special_tokens=True)
|
| 28 |
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
| 35 |
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
|
| 40 |
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 44 |
|
| 45 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 46 |
|
| 47 |
-
#
|
| 48 |
-
def
|
| 49 |
-
|
| 50 |
-
|
|
|
|
| 51 |
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 63 |
|
| 64 |
-
|
| 65 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
import torch
|
| 2 |
+
import transformers
|
| 3 |
import numpy as np
|
| 4 |
+
import gradio as gr
|
| 5 |
+
import openai
|
| 6 |
+
from sklearn.preprocessing import MinMaxScaler
|
| 7 |
+
import matplotlib.pyplot as plt
|
| 8 |
+
from datetime import datetime, timedelta
|
| 9 |
|
| 10 |
+
# Load Hugging Face model for financial insights generation
|
| 11 |
+
generator = transformers.pipeline("text-generation", model="gpt2")
|
|
|
|
|
|
|
| 12 |
|
| 13 |
+
# Sample function for fetching stock market data (you can use libraries like yfinance or Alpha Vantage)
|
| 14 |
+
def get_stock_data(symbol, start_date, end_date):
|
| 15 |
+
# This is just a placeholder. In production, use an API to get actual stock data
|
| 16 |
+
dates = np.array([start_date + timedelta(days=i) for i in range((end_date - start_date).days)])
|
| 17 |
+
prices = np.sin(np.linspace(0, 20, len(dates))) * 100 + 1000 # Placeholder for stock prices
|
| 18 |
+
return dates, prices
|
| 19 |
|
| 20 |
+
# Preprocessing stock data for prediction
|
| 21 |
+
def preprocess_data(prices):
|
| 22 |
+
scaler = MinMaxScaler(feature_range=(0, 1))
|
| 23 |
+
prices_scaled = scaler.fit_transform(prices.reshape(-1, 1))
|
| 24 |
+
return scaler, prices_scaled
|
|
|
|
| 25 |
|
| 26 |
+
# LSTM-based deep learning model for stock price prediction
|
| 27 |
+
class StockPredictor(torch.nn.Module):
|
| 28 |
+
def __init__(self, input_size=1, hidden_size=50, num_layers=1):
|
| 29 |
+
super(StockPredictor, self).__init__()
|
| 30 |
+
self.lstm = torch.nn.LSTM(input_size, hidden_size, num_layers, batch_first=True)
|
| 31 |
+
self.fc = torch.nn.Linear(hidden_size, 1)
|
| 32 |
|
| 33 |
+
def forward(self, x):
|
| 34 |
+
out, _ = self.lstm(x)
|
| 35 |
+
out = self.fc(out[:, -1, :])
|
| 36 |
+
return out
|
| 37 |
|
| 38 |
+
# Function to train the model on historical stock data
|
| 39 |
+
def train_model(prices_scaled):
|
| 40 |
+
model = StockPredictor()
|
| 41 |
+
criterion = torch.nn.MSELoss()
|
| 42 |
+
optimizer = torch.optim.Adam(model.parameters(), lr=0.001)
|
| 43 |
+
|
| 44 |
+
# Prepare data for training
|
| 45 |
+
X_train, y_train = [], []
|
| 46 |
+
for i in range(len(prices_scaled) - 1):
|
| 47 |
+
X_train.append(prices_scaled[i:i+10]) # Using the last 10 days to predict next day's price
|
| 48 |
+
y_train.append(prices_scaled[i+10])
|
| 49 |
|
| 50 |
+
X_train = torch.tensor(np.array(X_train), dtype=torch.float32)
|
| 51 |
+
y_train = torch.tensor(np.array(y_train), dtype=torch.float32)
|
| 52 |
+
|
| 53 |
+
# Train the model
|
| 54 |
+
for epoch in range(100):
|
| 55 |
+
model.train()
|
| 56 |
+
optimizer.zero_grad()
|
| 57 |
+
outputs = model(X_train)
|
| 58 |
+
loss = criterion(outputs, y_train)
|
| 59 |
+
loss.backward()
|
| 60 |
+
optimizer.step()
|
| 61 |
+
|
| 62 |
+
return model
|
| 63 |
+
|
| 64 |
+
# Predict future stock prices
|
| 65 |
+
def predict_stock(model, scaler, input_data):
|
| 66 |
+
model.eval()
|
| 67 |
+
with torch.no_grad():
|
| 68 |
+
predictions = model(torch.tensor(input_data, dtype=torch.float32))
|
| 69 |
+
return scaler.inverse_transform(predictions.detach().numpy())
|
| 70 |
|
| 71 |
+
# Generate financial insights using Hugging Face's GPT model
|
| 72 |
+
def generate_financial_insight(stock_symbol):
|
| 73 |
+
prompt = f"Generate a detailed financial report for the stock symbol {stock_symbol} based on recent market trends."
|
| 74 |
+
response = generator(prompt, max_length=150, num_return_sequences=1)
|
| 75 |
+
return response[0]['generated_text']
|
| 76 |
|
| 77 |
+
# Gradio interface function
|
| 78 |
+
def financial_advisor(symbol):
|
| 79 |
+
start_date = datetime.now() - timedelta(days=365) # Last year data
|
| 80 |
+
end_date = datetime.now()
|
| 81 |
+
|
| 82 |
+
# Get stock data (for simplicity, using dummy data here)
|
| 83 |
+
dates, prices = get_stock_data(symbol, start_date, end_date)
|
| 84 |
+
|
| 85 |
+
# Preprocess data for prediction
|
| 86 |
+
scaler, prices_scaled = preprocess_data(prices)
|
| 87 |
+
|
| 88 |
+
# Train the model on historical data
|
| 89 |
+
model = train_model(prices_scaled)
|
| 90 |
+
|
| 91 |
+
# Predict future prices (for simplicity, predicting the next 30 days)
|
| 92 |
+
future_data = prices_scaled[-10:].reshape(1, 10, 1)
|
| 93 |
+
predictions = predict_stock(model, scaler, future_data)
|
| 94 |
+
|
| 95 |
+
# Generate financial insights
|
| 96 |
+
insight = generate_financial_insight(symbol)
|
| 97 |
+
|
| 98 |
+
# Plot predicted prices
|
| 99 |
+
plt.plot(dates, prices, label="Historical Prices")
|
| 100 |
+
predicted_dates = [dates[-1] + timedelta(days=i) for i in range(1, 31)]
|
| 101 |
+
plt.plot(predicted_dates, predictions, label="Predicted Prices", linestyle="--")
|
| 102 |
+
plt.xlabel('Date')
|
| 103 |
+
plt.ylabel('Price')
|
| 104 |
+
plt.legend()
|
| 105 |
+
plt.xticks(rotation=45)
|
| 106 |
+
|
| 107 |
+
# Return results to display in Gradio
|
| 108 |
+
return plt.gcf(), f"Financial Insight for {symbol}: {insight}"
|
| 109 |
|
| 110 |
+
# Launch Gradio interface
|
| 111 |
+
gr.Interface(
|
| 112 |
+
fn=financial_advisor,
|
| 113 |
+
inputs=[gr.Textbox(label="Stock Symbol", placeholder="Enter Stock Symbol (e.g., AAPL)")],
|
| 114 |
+
outputs=[gr.Plot(), gr.Textbox()]
|
| 115 |
+
).launch()
|