Create app.py
Browse files123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111import yfinance as yfimport pandas as pdimport requestsimport jsonimport timeimport gradio as grimport matplotlib.pyplot as plt
# Function to fetch ticker symboldef get_ticker_symbol(company_name, api_key): search_url = f"https://www.alphavantage.co/query?function=SYMBOL_SEARCH&keywords={company_name}&apikey={api_key}" response = requests.get(search_url) if response.status_code == 200: try: data = response.json() if 'bestMatches' in data and len(data['bestMatches']) > 0: ticker_symbol = data['bestMatches'][0]['1. symbol'] return ticker_symbol else: return None except Exception: return None return None
# Function to get stock datadef get_stock_data(ticker_symbol, api_key): url = f"https://www.alphavantage.co/query?function=GLOBAL_QUOTE&symbol={ticker_symbol}&apikey={api_key}" response = requests.get(url) data = response.json() return data.get("Global Quote", {})
# Function for analysisdef analyze_stock(ticker_symbol): data = yf.download(ticker_symbol, start='2020-01-01', end=pd.Timestamp.now().strftime('%Y-%m-%d'))
if data.empty: return "No data found for this ticker.", None
data['Daily Returns'] = data['Adj Close'].pct_change() avg_vol = data['Volume'].mean() volatility = data['Daily Returns'].std()
data['100ma'] = data['Adj Close'].rolling(window=100).mean() data['200ma'] = data['Adj Close'].rolling(window=200).mean()
plt.figure(figsize=(10, 5)) plt.plot(data['Adj Close'], label='Adj Close', color='blue') plt.plot(data['100ma'], label='100-Day MA', color='orange') plt.plot(data['200ma'], label='200-Day MA', color='green') plt.title(f"{ticker_symbol} Price with Moving Averages") plt.legend() plt.grid(True) plt.tight_layout() plt.savefig("stock_plot.png") plt.close()
summary = ( f"**Ticker:** {ticker_symbol}\n\n" f"**Average Daily Volume:** {avg_vol:,.2f}\n" f"**Volatility (Std of Returns):** {volatility:.2%}\n" )
return summary, "stock_plot.png"
# Gradio logicdef run_stock_tool(company_name, mode): api_key = "JBQHL6764PCI6125" ticker_symbol = get_ticker_symbol(company_name, api_key)
if not ticker_symbol: return f"β Could not find ticker symbol for '{company_name}'", None
if mode == "Live Stock Data": stock_data = get_stock_data(ticker_symbol, api_key) if not stock_data: return f"No data available for {ticker_symbol} right now.", None
last_price = stock_data.get("05. price", "N/A") prev_close = stock_data.get("08. previous close", "N/A") high = stock_data.get("03. high", "N/A") low = stock_data.get("04. low", "N/A") volume = stock_data.get("06. volume", "N/A")
result = ( f"π **Live Stock Data for {ticker_symbol}**\n\n" f"**Last Price:** {last_price}\n" f"**Previous Close:** {prev_close}\n" f"**Day Range:** {high} - {low}\n" f"**Volume:** {volume}\n" ) return result, None
elif mode == "Stock Analysis": return analyze_stock(ticker_symbol)
# Gradio UIwith gr.Blocks(theme=gr.themes.Soft(), title="π Stock Analysis Tool") as app: gr.Markdown("# π Stock Analysis Tool\nEasily fetch live stock data or analyze historical trends!")
with gr.Row(): company_name = gr.Textbox(label="Enter Company Name", placeholder="e.g., Apple, Tesla, Reliance...") mode = gr.Radio(["Live Stock Data", "Stock Analysis"], label="Choose Mode")
submit_btn = gr.Button("Run Analysis π")
output_text = gr.Markdown() output_image = gr.Image()
submit_btn.click(run_stock_tool, inputs=[company_name, mode], outputs=[output_text, output_image])
app.launch()app.pyAdded+111