yfinance-api / app.py
moonstarpaddy's picture
Update app.py
c53cf3d verified
import gradio as gr
from scraper import FinancialScraper, format_financial_data
import time
# Initialize the scraper
scraper = FinancialScraper()
def get_stock_data(symbol, data_type="summary"):
"""Get stock data using web scraping"""
if not symbol or not symbol.strip():
return "⚠️ Please enter a valid stock symbol"
symbol = symbol.upper().strip()
try:
if data_type == "summary":
data = scraper.scrape_yahoo_summary(symbol)
elif data_type == "ratios":
data = scraper.scrape_key_statistics(symbol)
elif data_type == "comprehensive":
data = scraper.scrape_financial_highlights(symbol)
else:
return "❌ Invalid data type selected"
return format_financial_data(data)
except Exception as e:
return f"❌ Scraping Error: {str(e)}\n\nπŸ’‘ Try again in a few seconds or check if the symbol is correct."
def get_multiple_stocks(symbols_text):
"""Get data for multiple stocks with rate limiting"""
if not symbols_text or not symbols_text.strip():
return "⚠️ Please enter at least one stock symbol"
try:
symbols = [s.strip().upper() for s in symbols_text.split(',') if s.strip()]
if not symbols:
return "⚠️ No valid symbols found"
if len(symbols) > 5:
return "⚠️ Please limit to 5 symbols or fewer to avoid rate limiting"
results = []
for symbol in symbols:
data = scraper.scrape_yahoo_summary(symbol)
formatted_result = format_financial_data(data)
results.append(formatted_result)
# Add extra delay between multiple requests
if len(symbols) > 1:
time.sleep(1)
return "\n" + "="*50 + "\n".join(results)
except Exception as e:
return f"❌ Error processing multiple stocks: {str(e)}"
# Create enhanced Gradio interface
with gr.Blocks(title="Financial Data Scraper", theme=gr.themes.Soft()) as demo:
gr.Markdown("""
# πŸ“ˆ Stock Market Financial Data Scraper
**Get comprehensive financial data without API limits!**
βœ… Real-time stock prices and ratios
βœ… No rate limiting issues
βœ… PE/PB ratios, market cap, margins
βœ… Multiple data sources
""")
with gr.Tab("πŸ“Š Single Stock Analysis"):
with gr.Row():
with gr.Column(scale=2):
single_symbol = gr.Textbox(
label="Stock Symbol",
value="AAPL",
placeholder="Enter symbol (e.g., AAPL, MSFT, GOOGL)",
info="Enter any valid stock ticker symbol"
)
with gr.Column(scale=1):
data_type = gr.Dropdown(
choices=[
("Basic Summary", "summary"),
("Financial Ratios", "ratios"),
("Comprehensive Data", "comprehensive")
],
value="comprehensive",
label="Data Type"
)
single_btn = gr.Button("πŸ” Get Financial Data", variant="primary", size="lg")
single_output = gr.Textbox(
label="Financial Analysis Results",
lines=20,
max_lines=30,
show_copy_button=True
)
single_btn.click(
fn=get_stock_data,
inputs=[single_symbol, data_type],
outputs=single_output
)
with gr.Tab("πŸ“‹ Multiple Stocks Comparison"):
multi_symbols = gr.Textbox(
label="Stock Symbols (comma separated)",
value="AAPL,MSFT,GOOGL",
placeholder="Enter up to 5 symbols: AAPL,MSFT,GOOGL,TSLA,AMZN",
info="Separate multiple symbols with commas (max 5 symbols)"
)
multi_btn = gr.Button("πŸ“Š Compare Stocks", variant="secondary", size="lg")
multi_output = gr.Textbox(
label="Multiple Stocks Comparison",
lines=25,
max_lines=40,
show_copy_button=True
)
multi_btn.click(
fn=get_multiple_stocks,
inputs=multi_symbols,
outputs=multi_output
)
with gr.Tab("ℹ️ About"):
gr.Markdown("""
## How It Works
This tool scrapes financial data directly from Yahoo Finance using:
**πŸ›‘οΈ Anti-Detection Features:**
- Rotating User-Agents
- Rate limiting (1-2 second delays)
- Session management
- Error handling and retries
**πŸ“ˆ Available Data:**
- Current stock prices
- Market capitalization
- P/E, P/B, P/S ratios
- Profit margins
- Return on equity/assets
- 52-week ranges
- Enterprise value metrics
**πŸ’‘ Tips:**
- Use valid stock ticker symbols
- Allow a few seconds between requests
- Limit multiple stock queries to 5 symbols
""")
# Launch the app
demo.launch(show_error=True)