rioanggara's picture
test
2487585
raw
history blame
1.89 kB
import gradio as gr
import requests
import pandas as pd
import matplotlib.pyplot as plt
from datetime import datetime
API_KEY = "PJRAUD6KHJ2O097X"
def get_stock_data(symbol, start_date, end_date):
url = f"https://www.alphavantage.co/query?function=TIME_SERIES_DAILY&symbol={symbol}&apikey={API_KEY}"
response = requests.get(url)
data = response.json()
if "Time Series (Daily)" in data:
df = pd.DataFrame(data["Time Series (Daily)"]).T
df.index = pd.to_datetime(df.index)
# Convert input dates to datetime
try:
start_datetime = datetime.strptime(start_date, '%Y-%m-%d')
end_datetime = datetime.strptime(end_date, '%Y-%m-%d')
df = df.loc[start_datetime:end_datetime]
except ValueError:
return "Invalid date format. Please use YYYY-MM-DD.", None
df.columns = ["Open", "High", "Low", "Close", "Volume"]
# Plotting
plt.figure(figsize=(10, 5))
plt.plot(df['Close'], label='Close Price')
plt.title(f'Closing Price of {symbol}')
plt.xlabel('Date')
plt.ylabel('Price')
plt.legend()
plt.grid(True)
plt.xticks(rotation=45)
plt.tight_layout()
return df.to_html(), gr.Image.from_matplotlib(plt)
else:
return "Data not found or invalid stock symbol.", None
iface = gr.Interface(
fn=get_stock_data,
inputs=[
gr.Textbox(label="Stock Symbol", placeholder="Enter a stock symbol (like AAPL, MSFT)"),
gr.Textbox(label="Start Date", placeholder="YYYY-MM-DD"),
gr.Textbox(label="End Date", placeholder="YYYY-MM-DD")
],
outputs=["html", "plot"],
title="Personalized Stock Market Data App",
description="Enter a stock symbol and date range to fetch its daily time series data."
)
if __name__ == "__main__":
iface.launch()