ajayx2006 commited on
Commit
3875d3d
Β·
verified Β·
1 Parent(s): 2aad30c

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +29 -12
app.py CHANGED
@@ -2,11 +2,13 @@ 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)
@@ -22,27 +24,36 @@ def get_ticker_symbol(company_name, api_key):
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')
@@ -55,16 +66,19 @@ def analyze_stock(ticker_symbol):
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:
@@ -73,7 +87,7 @@ def run_stock_tool(company_name, mode):
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")
@@ -93,8 +107,11 @@ def run_stock_tool(company_name, mode):
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():
 
2
  import pandas as pd
3
  import requests
4
  import json
 
 
5
  import matplotlib.pyplot as plt
6
+ import gradio as gr
7
 
8
+
9
+ # -----------------------------
10
+ # Function to get ticker symbol
11
+ # -----------------------------
12
  def get_ticker_symbol(company_name, api_key):
13
  search_url = f"https://www.alphavantage.co/query?function=SYMBOL_SEARCH&keywords={company_name}&apikey={api_key}"
14
  response = requests.get(search_url)
 
24
  return None
25
  return None
26
 
27
+
28
+ # -----------------------------
29
+ # Function to get live stock data
30
+ # -----------------------------
31
  def get_stock_data(ticker_symbol, api_key):
32
  url = f"https://www.alphavantage.co/query?function=GLOBAL_QUOTE&symbol={ticker_symbol}&apikey={api_key}"
33
  response = requests.get(url)
34
  data = response.json()
35
  return data.get("Global Quote", {})
36
 
37
+
38
+ # -----------------------------
39
+ # Function to analyze stock trends
40
+ # -----------------------------
41
  def analyze_stock(ticker_symbol):
42
  data = yf.download(ticker_symbol, start='2020-01-01', end=pd.Timestamp.now().strftime('%Y-%m-%d'))
43
 
44
  if data.empty:
45
+ return "❌ No historical data found for this ticker.", None
46
 
47
+ # Calculate metrics
48
  data['Daily Returns'] = data['Adj Close'].pct_change()
49
  avg_vol = data['Volume'].mean()
50
  volatility = data['Daily Returns'].std()
51
 
52
+ # Moving averages
53
  data['100ma'] = data['Adj Close'].rolling(window=100).mean()
54
  data['200ma'] = data['Adj Close'].rolling(window=200).mean()
55
 
56
+ # Plot chart
57
  plt.figure(figsize=(10, 5))
58
  plt.plot(data['Adj Close'], label='Adj Close', color='blue')
59
  plt.plot(data['100ma'], label='100-Day MA', color='orange')
 
66
  plt.close()
67
 
68
  summary = (
69
+ f"πŸ“Š **Ticker:** {ticker_symbol}\n\n"
70
  f"**Average Daily Volume:** {avg_vol:,.2f}\n"
71
  f"**Volatility (Std of Returns):** {volatility:.2%}\n"
72
  )
73
 
74
  return summary, "stock_plot.png"
75
 
76
+
77
+ # -----------------------------
78
+ # Combined function for Gradio
79
+ # -----------------------------
80
  def run_stock_tool(company_name, mode):
81
+ api_key = "JBQHL6764PCI6125" # Replace with your own Alpha Vantage API key
82
  ticker_symbol = get_ticker_symbol(company_name, api_key)
83
 
84
  if not ticker_symbol:
 
87
  if mode == "Live Stock Data":
88
  stock_data = get_stock_data(ticker_symbol, api_key)
89
  if not stock_data:
90
+ return f"No live data available for {ticker_symbol} right now.", None
91
 
92
  last_price = stock_data.get("05. price", "N/A")
93
  prev_close = stock_data.get("08. previous close", "N/A")
 
107
  elif mode == "Stock Analysis":
108
  return analyze_stock(ticker_symbol)
109
 
110
+
111
+ # -----------------------------
112
+ # Gradio User Interface
113
+ # -----------------------------
114
+ with gr.Blocks() as app:
115
  gr.Markdown("# πŸ“ˆ Stock Analysis Tool\nEasily fetch live stock data or analyze historical trends!")
116
 
117
  with gr.Row():