ajayx2006 commited on
Commit
5a97214
Β·
verified Β·
1 Parent(s): 0a9166f

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +111 -0
app.py ADDED
@@ -0,0 +1,111 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import yfinance as yf
2
+ import pandas as pd
3
+ import requests
4
+ import json
5
+ import time
6
+ import gradio as gr
7
+ import matplotlib.pyplot as plt
8
+
9
+ # Function to fetch ticker symbol
10
+ def get_ticker_symbol(company_name, api_key):
11
+ search_url = f"https://www.alphavantage.co/query?function=SYMBOL_SEARCH&keywords={company_name}&apikey={api_key}"
12
+ response = requests.get(search_url)
13
+ if response.status_code == 200:
14
+ try:
15
+ data = response.json()
16
+ if 'bestMatches' in data and len(data['bestMatches']) > 0:
17
+ ticker_symbol = data['bestMatches'][0]['1. symbol']
18
+ return ticker_symbol
19
+ else:
20
+ return None
21
+ except Exception:
22
+ return None
23
+ return None
24
+
25
+ # Function to get stock data
26
+ def get_stock_data(ticker_symbol, api_key):
27
+ url = f"https://www.alphavantage.co/query?function=GLOBAL_QUOTE&symbol={ticker_symbol}&apikey={api_key}"
28
+ response = requests.get(url)
29
+ data = response.json()
30
+ return data.get("Global Quote", {})
31
+
32
+ # Function for analysis
33
+ def analyze_stock(ticker_symbol):
34
+ data = yf.download(ticker_symbol, start='2020-01-01', end=pd.Timestamp.now().strftime('%Y-%m-%d'))
35
+
36
+ if data.empty:
37
+ return "No data found for this ticker.", None
38
+
39
+ data['Daily Returns'] = data['Adj Close'].pct_change()
40
+ avg_vol = data['Volume'].mean()
41
+ volatility = data['Daily Returns'].std()
42
+
43
+ data['100ma'] = data['Adj Close'].rolling(window=100).mean()
44
+ data['200ma'] = data['Adj Close'].rolling(window=200).mean()
45
+
46
+ plt.figure(figsize=(10, 5))
47
+ plt.plot(data['Adj Close'], label='Adj Close', color='blue')
48
+ plt.plot(data['100ma'], label='100-Day MA', color='orange')
49
+ plt.plot(data['200ma'], label='200-Day MA', color='green')
50
+ plt.title(f"{ticker_symbol} Price with Moving Averages")
51
+ plt.legend()
52
+ plt.grid(True)
53
+ plt.tight_layout()
54
+ plt.savefig("stock_plot.png")
55
+ plt.close()
56
+
57
+ summary = (
58
+ f"**Ticker:** {ticker_symbol}\n\n"
59
+ f"**Average Daily Volume:** {avg_vol:,.2f}\n"
60
+ f"**Volatility (Std of Returns):** {volatility:.2%}\n"
61
+ )
62
+
63
+ return summary, "stock_plot.png"
64
+
65
+ # Gradio logic
66
+ def run_stock_tool(company_name, mode):
67
+ api_key = "JBQHL6764PCI6125"
68
+ ticker_symbol = get_ticker_symbol(company_name, api_key)
69
+
70
+ if not ticker_symbol:
71
+ return f"❌ Could not find ticker symbol for '{company_name}'", None
72
+
73
+ if mode == "Live Stock Data":
74
+ stock_data = get_stock_data(ticker_symbol, api_key)
75
+ if not stock_data:
76
+ return f"No data available for {ticker_symbol} right now.", None
77
+
78
+ last_price = stock_data.get("05. price", "N/A")
79
+ prev_close = stock_data.get("08. previous close", "N/A")
80
+ high = stock_data.get("03. high", "N/A")
81
+ low = stock_data.get("04. low", "N/A")
82
+ volume = stock_data.get("06. volume", "N/A")
83
+
84
+ result = (
85
+ f"πŸ“ˆ **Live Stock Data for {ticker_symbol}**\n\n"
86
+ f"**Last Price:** {last_price}\n"
87
+ f"**Previous Close:** {prev_close}\n"
88
+ f"**Day Range:** {high} - {low}\n"
89
+ f"**Volume:** {volume}\n"
90
+ )
91
+ return result, None
92
+
93
+ elif mode == "Stock Analysis":
94
+ return analyze_stock(ticker_symbol)
95
+
96
+ # Gradio UI
97
+ with gr.Blocks(theme=gr.themes.Soft(), title="πŸ“Š Stock Analysis Tool") as app:
98
+ gr.Markdown("# πŸ“ˆ Stock Analysis Tool\nEasily fetch live stock data or analyze historical trends!")
99
+
100
+ with gr.Row():
101
+ company_name = gr.Textbox(label="Enter Company Name", placeholder="e.g., Apple, Tesla, Reliance...")
102
+ mode = gr.Radio(["Live Stock Data", "Stock Analysis"], label="Choose Mode")
103
+
104
+ submit_btn = gr.Button("Run Analysis πŸš€")
105
+
106
+ output_text = gr.Markdown()
107
+ output_image = gr.Image()
108
+
109
+ submit_btn.click(run_stock_tool, inputs=[company_name, mode], outputs=[output_text, output_image])
110
+
111
+ app.launch()