|
import gradio as gr |
|
import yfinance as yf |
|
import pandas as pd |
|
from sklearn.linear_model import LinearRegression |
|
import plotly.graph_objects as go |
|
|
|
def train_predict_wrapper(ticker, start_date, end_date, prediction_days): |
|
|
|
data = yf.download(ticker, start=start_date, end=end_date) |
|
data = data["Close"] |
|
|
|
|
|
data.index = (data.index - pd.Timestamp("1970-01-01")) // pd.Timedelta('1s') |
|
|
|
|
|
X = data.index.values[:-prediction_days].reshape(-1, 1) |
|
y = data.values[:-prediction_days] |
|
model = LinearRegression() |
|
model.fit(X, y) |
|
|
|
|
|
last_timestamp = data.index[-1] |
|
future_timestamps = pd.date_range(start=pd.to_datetime(last_timestamp, unit='s'), |
|
periods=prediction_days, freq='D') |
|
future_timestamps = (future_timestamps - pd.Timestamp("1970-01-01")) // pd.Timedelta('1s') |
|
X_future = future_timestamps.values.reshape(-1, 1) |
|
|
|
|
|
predicted_prices = model.predict(X_future) |
|
|
|
|
|
historical_prices = go.Scatter( |
|
x=pd.to_datetime(data.index, unit='s'), |
|
y=data.values, |
|
mode="lines", |
|
name="Historical Prices" |
|
) |
|
predicted_prices_trace = go.Scatter( |
|
x=pd.to_datetime(future_timestamps, unit='s'), |
|
y=predicted_prices, |
|
mode="lines", |
|
name="Predicted Prices" |
|
) |
|
|
|
|
|
fig = go.Figure() |
|
fig.add_trace(historical_prices) |
|
fig.add_trace(predicted_prices_trace) |
|
fig.update_layout( |
|
title="Stock Price Prediction", |
|
xaxis_title="Date", |
|
yaxis_title="Price", |
|
legend_title_text="Data" |
|
) |
|
|
|
return fig |
|
|
|
|
|
interface = gr.Interface( |
|
fn=train_predict_wrapper, |
|
inputs=[ |
|
gr.Textbox(label="Ticker Symbol"), |
|
gr.Textbox(label="Start Date (YYYY-MM-DD)"), |
|
gr.Textbox(label="End Date (YYYY-MM-DD)"), |
|
gr.Slider(minimum=1, maximum=30, step=1, label="Prediction Days"), |
|
], |
|
outputs="plot" |
|
) |
|
|
|
|
|
interface.launch() |