moonstarpaddy commited on
Commit
c53cf3d
Β·
verified Β·
1 Parent(s): 2593295

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +133 -60
app.py CHANGED
@@ -1,83 +1,156 @@
1
- import yfinance as yf
2
  import gradio as gr
3
- import pandas as pd
4
- import json
5
 
6
- def get_stock_history(symbol, period="1mo"):
7
- try:
8
- ticker = yf.Ticker(symbol.upper())
9
- data = ticker.history(period=period)
10
- if data.empty:
11
- return f"No data found for {symbol.upper()}"
12
- return data.to_string()
13
- except Exception as e:
14
- return f"Error: {str(e)}"
15
 
16
- def get_stock_info(symbol):
 
 
 
 
 
 
17
  try:
18
- ticker = yf.Ticker(symbol.upper())
19
- info = ticker.info
 
 
 
 
 
 
20
 
21
- key_info = {
22
- 'Company': info.get('longName', 'N/A'),
23
- 'Symbol': info.get('symbol', 'N/A'),
24
- 'Current Price': f"${info.get('currentPrice', 'N/A')}",
25
- 'Market Cap': info.get('marketCap', 'N/A'),
26
- 'PE Ratio': info.get('trailingPE', 'N/A'),
27
- 'Sector': info.get('sector', 'N/A'),
28
- '52 Week High': f"${info.get('fiftyTwoWeekHigh', 'N/A')}",
29
- '52 Week Low': f"${info.get('fiftyTwoWeekLow', 'N/A')}"
30
- }
31
 
32
- return "\n".join([f"{k}: {v}" for k, v in key_info.items()])
33
  except Exception as e:
34
- return f"Error: {str(e)}"
35
 
36
  def get_multiple_stocks(symbols_text):
 
 
 
 
37
  try:
38
  symbols = [s.strip().upper() for s in symbols_text.split(',') if s.strip()]
39
  if not symbols:
40
- return "Please enter at least one symbol"
 
 
 
41
 
42
- data = yf.download(symbols, period="5d", group_by='ticker')
43
- if data.empty:
44
- return "No data found for the provided symbols"
 
 
 
 
 
 
 
 
 
45
 
46
- return data.to_string()
47
  except Exception as e:
48
- return f"Error: {str(e)}"
49
 
50
- # Enhanced UI
51
- with gr.Blocks(title="YFinance API", theme=gr.themes.Soft()) as demo:
52
- gr.Markdown("# πŸ“ˆ YFinance Stock Market API")
53
- gr.Markdown("Get real-time stock data from Yahoo Finance")
54
 
55
- with gr.Tab("πŸ“Š Single Stock History"):
56
- with gr.Row():
57
- hist_symbol = gr.Textbox(label="Stock Symbol", value="AAPL")
58
- hist_period = gr.Dropdown(
59
- choices=["1d", "5d", "1mo", "3mo", "6mo", "1y", "2y"],
60
- value="1mo",
61
- label="Time Period"
62
- )
63
- hist_btn = gr.Button("Get History", variant="primary")
64
- hist_output = gr.Textbox(label="Historical Data", lines=12)
65
- hist_btn.click(get_stock_history, [hist_symbol, hist_period], hist_output)
66
 
67
- with gr.Tab("ℹ️ Company Information"):
68
- info_symbol = gr.Textbox(label="Stock Symbol", value="MSFT")
69
- info_btn = gr.Button("Get Company Info", variant="primary")
70
- info_output = gr.Textbox(label="Company Details", lines=10)
71
- info_btn.click(get_stock_info, info_symbol, info_output)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
72
 
73
- with gr.Tab("πŸ“‹ Multiple Stocks"):
74
  multi_symbols = gr.Textbox(
75
- label="Stock Symbols (comma separated)",
76
  value="AAPL,MSFT,GOOGL",
77
- placeholder="Enter symbols like: AAPL,MSFT,TSLA"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
78
  )
79
- multi_btn = gr.Button("Get Multiple Stocks", variant="primary")
80
- multi_output = gr.Textbox(label="Multiple Stock Data", lines=15)
81
- multi_btn.click(get_multiple_stocks, multi_symbols, multi_output)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
82
 
83
- demo.launch()
 
 
 
1
  import gradio as gr
2
+ from scraper import FinancialScraper, format_financial_data
3
+ import time
4
 
5
+ # Initialize the scraper
6
+ scraper = FinancialScraper()
 
 
 
 
 
 
 
7
 
8
+ def get_stock_data(symbol, data_type="summary"):
9
+ """Get stock data using web scraping"""
10
+ if not symbol or not symbol.strip():
11
+ return "⚠️ Please enter a valid stock symbol"
12
+
13
+ symbol = symbol.upper().strip()
14
+
15
  try:
16
+ if data_type == "summary":
17
+ data = scraper.scrape_yahoo_summary(symbol)
18
+ elif data_type == "ratios":
19
+ data = scraper.scrape_key_statistics(symbol)
20
+ elif data_type == "comprehensive":
21
+ data = scraper.scrape_financial_highlights(symbol)
22
+ else:
23
+ return "❌ Invalid data type selected"
24
 
25
+ return format_financial_data(data)
 
 
 
 
 
 
 
 
 
26
 
 
27
  except Exception as e:
28
+ return f"❌ Scraping Error: {str(e)}\n\nπŸ’‘ Try again in a few seconds or check if the symbol is correct."
29
 
30
  def get_multiple_stocks(symbols_text):
31
+ """Get data for multiple stocks with rate limiting"""
32
+ if not symbols_text or not symbols_text.strip():
33
+ return "⚠️ Please enter at least one stock symbol"
34
+
35
  try:
36
  symbols = [s.strip().upper() for s in symbols_text.split(',') if s.strip()]
37
  if not symbols:
38
+ return "⚠️ No valid symbols found"
39
+
40
+ if len(symbols) > 5:
41
+ return "⚠️ Please limit to 5 symbols or fewer to avoid rate limiting"
42
 
43
+ results = []
44
+
45
+ for symbol in symbols:
46
+ data = scraper.scrape_yahoo_summary(symbol)
47
+ formatted_result = format_financial_data(data)
48
+ results.append(formatted_result)
49
+
50
+ # Add extra delay between multiple requests
51
+ if len(symbols) > 1:
52
+ time.sleep(1)
53
+
54
+ return "\n" + "="*50 + "\n".join(results)
55
 
 
56
  except Exception as e:
57
+ return f"❌ Error processing multiple stocks: {str(e)}"
58
 
59
+ # Create enhanced Gradio interface
60
+ with gr.Blocks(title="Financial Data Scraper", theme=gr.themes.Soft()) as demo:
61
+ gr.Markdown("""
62
+ # πŸ“ˆ Stock Market Financial Data Scraper
63
 
64
+ **Get comprehensive financial data without API limits!**
 
 
 
 
 
 
 
 
 
 
65
 
66
+ βœ… Real-time stock prices and ratios
67
+ βœ… No rate limiting issues
68
+ βœ… PE/PB ratios, market cap, margins
69
+ βœ… Multiple data sources
70
+ """)
71
+
72
+ with gr.Tab("πŸ“Š Single Stock Analysis"):
73
+ with gr.Row():
74
+ with gr.Column(scale=2):
75
+ single_symbol = gr.Textbox(
76
+ label="Stock Symbol",
77
+ value="AAPL",
78
+ placeholder="Enter symbol (e.g., AAPL, MSFT, GOOGL)",
79
+ info="Enter any valid stock ticker symbol"
80
+ )
81
+ with gr.Column(scale=1):
82
+ data_type = gr.Dropdown(
83
+ choices=[
84
+ ("Basic Summary", "summary"),
85
+ ("Financial Ratios", "ratios"),
86
+ ("Comprehensive Data", "comprehensive")
87
+ ],
88
+ value="comprehensive",
89
+ label="Data Type"
90
+ )
91
+
92
+ single_btn = gr.Button("πŸ” Get Financial Data", variant="primary", size="lg")
93
+ single_output = gr.Textbox(
94
+ label="Financial Analysis Results",
95
+ lines=20,
96
+ max_lines=30,
97
+ show_copy_button=True
98
+ )
99
+
100
+ single_btn.click(
101
+ fn=get_stock_data,
102
+ inputs=[single_symbol, data_type],
103
+ outputs=single_output
104
+ )
105
 
106
+ with gr.Tab("πŸ“‹ Multiple Stocks Comparison"):
107
  multi_symbols = gr.Textbox(
108
+ label="Stock Symbols (comma separated)",
109
  value="AAPL,MSFT,GOOGL",
110
+ placeholder="Enter up to 5 symbols: AAPL,MSFT,GOOGL,TSLA,AMZN",
111
+ info="Separate multiple symbols with commas (max 5 symbols)"
112
+ )
113
+
114
+ multi_btn = gr.Button("πŸ“Š Compare Stocks", variant="secondary", size="lg")
115
+ multi_output = gr.Textbox(
116
+ label="Multiple Stocks Comparison",
117
+ lines=25,
118
+ max_lines=40,
119
+ show_copy_button=True
120
+ )
121
+
122
+ multi_btn.click(
123
+ fn=get_multiple_stocks,
124
+ inputs=multi_symbols,
125
+ outputs=multi_output
126
  )
127
+
128
+ with gr.Tab("ℹ️ About"):
129
+ gr.Markdown("""
130
+ ## How It Works
131
+
132
+ This tool scrapes financial data directly from Yahoo Finance using:
133
+
134
+ **πŸ›‘οΈ Anti-Detection Features:**
135
+ - Rotating User-Agents
136
+ - Rate limiting (1-2 second delays)
137
+ - Session management
138
+ - Error handling and retries
139
+
140
+ **πŸ“ˆ Available Data:**
141
+ - Current stock prices
142
+ - Market capitalization
143
+ - P/E, P/B, P/S ratios
144
+ - Profit margins
145
+ - Return on equity/assets
146
+ - 52-week ranges
147
+ - Enterprise value metrics
148
+
149
+ **πŸ’‘ Tips:**
150
+ - Use valid stock ticker symbols
151
+ - Allow a few seconds between requests
152
+ - Limit multiple stock queries to 5 symbols
153
+ """)
154
 
155
+ # Launch the app
156
+ demo.launch(show_error=True)