Download app.py from ajayx2006/project: direct link, hf CLI and curl.
- Browser
- Download file 4.34 kB
-
https://huggingface.co/spaces/ajayx2006/project/resolve/main/app.py
- Command line
-
hf download hf://spaces/ajayx2006/project/app.py
-
curl -L -o app.py https://huggingface.co/spaces/ajayx2006/project/resolve/main/app.py
4.34 kB
| import yfinance as yf | |
| import pandas as pd | |
| import requests | |
| import json | |
| import matplotlib.pyplot as plt | |
| import gradio as gr | |
| # ----------------------------- | |
| # Function to get ticker symbol | |
| # ----------------------------- | |
| def 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 live stock data | |
| # ----------------------------- | |
| def 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 to analyze stock trends | |
| # ----------------------------- | |
| def 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 historical data found for this ticker.", None | |
| # Calculate metrics | |
| data['Daily Returns'] = data['Adj Close'].pct_change() | |
| avg_vol = data['Volume'].mean() | |
| volatility = data['Daily Returns'].std() | |
| # Moving averages | |
| data['100ma'] = data['Adj Close'].rolling(window=100).mean() | |
| data['200ma'] = data['Adj Close'].rolling(window=200).mean() | |
| # Plot chart | |
| 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" | |
| # ----------------------------- | |
| # Combined function for Gradio | |
| # ----------------------------- | |
| def run_stock_tool(company_name, mode): | |
| api_key = "JBQHL6764PCI6125" # Replace with your own Alpha Vantage API key | |
| 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 live 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 User Interface | |
| # ----------------------------- | |
| with gr.Blocks() 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() | |