Spaces:
Runtime error
Runtime error
| import yfinance as yf | |
| import pandas as pd | |
| import numpy as np | |
| from sklearn.linear_model import LinearRegression | |
| from sklearn.metrics import mean_squared_error | |
| import matplotlib.pyplot as plt | |
| import io | |
| import base64 | |
| # Function to fetch data and train model | |
| def predict_price(symbol): | |
| df = yf.download(symbol, period="3mo", interval="1d") # last 3 months | |
| if df.empty or len(df) < 60: | |
| return "❌ Not enough data to train model", None | |
| df = df[['Close']].dropna() | |
| df.reset_index(drop=True, inplace=True) | |
| # Create features: previous 5 days' close prices to predict next day | |
| X, y = [], [] | |
| for i in range(5, len(df)-1): | |
| X.append(df['Close'].iloc[i-5:i].values) | |
| y.append(df['Close'].iloc[i+1]) | |
| X = np.array(X) | |
| y = np.array(y) | |
| model = LinearRegression() | |
| model.fit(X, y) | |
| # Predict the next day's price | |
| last_5_days = df['Close'].iloc[-5:].values.reshape(1, -1) | |
| predicted = model.predict(last_5_days)[0] | |
| # Plot: Actual vs Predicted on last 10 days | |
| test_X = X[-10:] | |
| test_y = y[-10:] | |
| pred_y = model.predict(test_X) | |
| fig, ax = plt.subplots() | |
| ax.plot(range(10), test_y, label="Actual", marker='o') | |
| ax.plot(range(10), pred_y, label="Predicted", marker='x') | |
| ax.set_title(f"📈 Prediction vs Actual for {symbol}") | |
| ax.set_xlabel("Day") | |
| ax.set_ylabel("Price") | |
| ax.legend() | |
| return predicted, fig |