mr601s's picture
Update app.py
07c2fd6 verified
import gradio as gr
import requests
import numpy as np
import pandas as pd
import feedparser
import time
import random
from datetime import datetime
import os
# === CONFIG: API KEYS ===
POLYGON_API_KEY = os.getenv("POLYGON_API_KEY") or "fAhg47wPlf4FT6U2Hn23kQoQCQIyW0G_"
FINNHUB_API_KEY = "d2urs69r01qq994h1f5gd2urs69r01qq994h1f60"
# --- QUOTE SECTION ---
def fetch_polygon_quote(ticker, polygon_api_key=POLYGON_API_KEY):
url = f"https://api.polygon.io/v2/aggs/ticker/{ticker.upper()}/prev?adjusted=true&apiKey={polygon_api_key}"
try:
response = requests.get(url, timeout=10)
response.raise_for_status()
data = response.json()
if data.get("results"):
last = data["results"][0]
price = last["c"]
close_dt = datetime.utcfromtimestamp(last["t"] / 1000).strftime('%Y-%m-%d')
return f"💰 **Previous Close for {ticker.upper()} (as of {close_dt})**\n\n• **Close Price:** ${price:.2f}\n\n_(Free Polygon plan only provides prior close)_"
else:
return f"❌ Quote data unavailable for {ticker.upper()}."
except Exception as e:
return f"❌ Error: {str(e)}"
# --- FINNHUB FINANCIAL SUMMARY ---
def get_financial_summary_finnhub(ticker, finnhub_api_key=FINNHUB_API_KEY):
url = f"https://finnhub.io/api/v1/stock/metric?symbol={ticker.upper()}&metric=all&token={finnhub_api_key}"
try:
response = requests.get(url, timeout=10)
response.raise_for_status()
data = response.json()
metrics = data.get('metric', {})
if not metrics:
return f"📊 **Financial Summary for {ticker.upper()}**\n\n❌ No financial data found."
result = f"📊 **Financial Summary for {ticker.upper()}**\n\n"
if metrics.get('totalRevenueTTM'):
result += f"• **Revenue (TTM):** ${int(metrics['totalRevenueTTM']):,}\n"
if metrics.get('netIncomeTTM'):
result += f"• **Net Income (TTM):** ${int(metrics['netIncomeTTM']):,}\n"
pe = metrics.get('peNormalizedAnnual') or metrics.get('peExclExtraTTM')
if pe is not None:
result += f"• **P/E Ratio:** {pe:.2f}\n"
pb = metrics.get('pbAnnual')
if pb is not None:
result += f"• **P/B Ratio:** {pb:.2f}\n"
dy = metrics.get('dividendYieldIndicatedAnnual')
if dy is not None:
result += f"• **Dividend Yield:** {dy:.2f}%\n"
dte = metrics.get('totalDebt/totalEquityAnnual')
if dte is not None:
result += f"• **Debt/Equity:** {dte:.2f}\n"
pm = metrics.get('netProfitMarginTTM')
if pm is not None:
result += f"• **Net Profit Margin:** {pm:.2f}%\n"
mc = metrics.get('marketCapitalization')
if mc is not None:
result += f"• **Market Cap:** ${int(mc):,}\n"
if result.strip() == f"📊 **Financial Summary for {ticker.upper()}**":
return f"📊 **Financial Summary for {ticker.upper()}**\n\n❌ No data available from Finnhub."
return result
except Exception as e:
return f"📊 **Financial Summary for {ticker.upper()}**\n\n❌ Error fetching financial summary: {e}"
# --- SEC Utilities ---
class SECUtils:
def __init__(self):
self.cik_lookup_url = "https://www.sec.gov/files/company_tickers.json"
self.edgar_search_url = "https://data.sec.gov/submissions/CIK{cik}.json"
self.headers = {"User-Agent": "StockResearchMVP/1.0 (educational@example.com)"}
def get_cik(self, ticker):
try:
time.sleep(0.5)
response = requests.get(self.cik_lookup_url, headers=self.headers, timeout=20)
if response.status_code != 200:
return None
data = response.json()
for k, v in data.items():
if isinstance(v, dict) and v.get('ticker', '').upper() == ticker.upper():
return str(v['cik_str']).zfill(10)
return None
except Exception as e:
print(f"CIK lookup error: {e}")
return None
def get_recent_filings(self, ticker):
try:
cik = self.get_cik(ticker)
if not cik:
return f"📄 **SEC Filings for {ticker}**\n\n❌ CIK not found. This may be a newer company or ticker not in SEC database.\n\n💡 Try checking [SEC EDGAR directly](https://www.sec.gov/edgar/search/) for this company."
time.sleep(0.5)
url = self.edgar_search_url.format(cik=cik)
response = requests.get(url, headers=self.headers, timeout=20)
if response.status_code != 200:
return f"📄 **SEC Filings for {ticker}**\n\n❌ Unable to fetch SEC data (Status: {response.status_code}).\n\n💡 Try [SEC EDGAR search](https://www.sec.gov/edgar/search/) directly."
data = response.json()
filings = data.get('filings', {}).get('recent', {})
if not filings or not filings.get('form'):
return f"📄 **SEC Filings for {ticker}**\n\n❌ No recent filings found for CIK: {cik}."
result = f"📄 **SEC Filings for {ticker}** (CIK: {cik})\n\n"
forms = filings.get('form', [])
dates = filings.get('filingDate', [])
accessions = filings.get('accessionNumber', [])
for i in range(min(5, len(forms))):
if i < len(dates) and i < len(accessions):
form = forms[i]
filing_date = dates[i]
accession_num = accessions[i].replace('-', '')
filing_url = f"https://www.sec.gov/Archives/edgar/data/{int(cik)}/{accession_num}/"
result += f"• **{form}** - {filing_date}\n"
result += f" 📎 [View Filing]({filing_url})\n\n"
return result
except Exception as e:
return f"📄 **SEC Filings for {ticker}**\n\n❌ Error fetching SEC filings: {str(e)}\n\n💡 Try [SEC EDGAR search](https://www.sec.gov/edgar/search/) directly."
# --- News Utilities ---
class NewsUtils:
def __init__(self):
self.headers = {"User-Agent": "StockResearchMVP/1.0 (educational@example.com)"}
def get_yahoo_news(self, ticker):
try:
time.sleep(random.uniform(0.5, 1.0))
url = f"https://feeds.finance.yahoo.com/rss/2.0/headline?s={ticker}&region=US&lang=en-US"
feed = feedparser.parse(url)
if not feed.entries:
return f"📰 **Latest News for {ticker}**\n\n❌ No recent news found via RSS feed.\n\n💡 Try these alternatives:\n• [Yahoo Finance News](https://finance.yahoo.com/quote/{ticker}/news)\n• [Google Finance](https://www.google.com/finance/quote/{ticker}:NASDAQ)\n• [MarketWatch](https://www.marketwatch.com/investing/stock/{ticker})"
result = f"📰 **Latest News for {ticker}**\n\n"
for i, entry in enumerate(feed.entries[:5]):
title = getattr(entry, 'title', 'No title')
link = getattr(entry, 'link', '#')
pub_date = getattr(entry, 'published', 'Unknown date')
result += f"{i+1}. **{title}**\n"
result += f" 📅 {pub_date}\n"
result += f" 🔗 [Read More]({link})\n\n"
return result
except Exception as e:
return f"📰 **Latest News for {ticker}**\n\n❌ Error fetching news: {str(e)}\n\n💡 Try these alternatives:\n• [Yahoo Finance News](https://finance.yahoo.com/quote/{ticker}/news)\n• [Google Finance](https://www.google.com/finance/quote/{ticker}:NASDAQ)\n• [MarketWatch](https://www.marketwatch.com/investing/stock/{ticker})"
# --- TradingView Widget Chart Embed ---
def get_tradingview_embed(ticker):
ticker = ticker.strip().upper() if ticker else "AAPL"
ticker = ''.join(filter(str.isalnum, ticker))
return f"""
<iframe src="https://s.tradingview.com/widgetembed/?symbol={ticker}&interval=D&hidesidetoolbar=1&theme=light"
width="100%" height="400" frameborder="0" allowtransparency="true" scrolling="no"></iframe>
"""
# --- LESSON TOOLS ---
def simulate_order_book(side, order_type, price, size, seed=123):
np.random.seed(seed)
base_price = 100.00
levels = np.arange(base_price - 2, base_price + 2.5, 0.5)
buy_sizes = np.random.randint(1, 40, len(levels))
sell_sizes = np.random.randint(1, 40, len(levels))
buy_mask = levels < base_price
sell_mask = levels > base_price
buys = np.where(buy_mask, buy_sizes, 0)
sells = np.where(sell_mask, sell_sizes, 0)
df = pd.DataFrame({
'Price': levels,
'Buy Size': buys,
'Sell Size': sells
}).sort_values(by='Price', ascending=False).reset_index(drop=True)
fill_msg = ""
if order_type == "Market":
if side == "Buy":
best_ask = df.loc[df['Sell Size'] > 0, 'Price'].min()
filled = size
fill_msg = f"Filled {filled} @ {best_ask:.2f} (Market Buy)"
else:
best_bid = df.loc[df['Buy Size'] > 0, 'Price'].max()
filled = size
fill_msg = f"Filled {filled} @ {best_bid:.2f} (Market Sell)"
else:
if side == "Buy":
if price >= df['Price'].min():
sells_at_or_below = df[(df['Price'] <= price) & (df['Sell Size'] > 0)]
if sells_at_or_below.shape[0]:
fill_price = sells_at_or_below.iloc[0]['Price']
fill_msg = f"Filled {size} @ {fill_price:.2f} (Aggressive Limit Buy)"
else:
queue_spot = 1 + np.random.randint(0, 3)
fill_msg = f"Limit buy posted at {price:.2f}. Not immediately filled. Position in queue: #{queue_spot}"
else:
fill_msg = f"Limit buy posted below book: {price:.2f}. Not filled."
else:
if price <= df['Price'].max():
buys_at_or_above = df[(df['Price'] >= price) & (df['Buy Size'] > 0)]
if buys_at_or_above.shape[0]:
fill_price = buys_at_or_above.iloc[0]['Price']
fill_msg = f"Filled {size} @ {fill_price:.2f} (Aggressive Limit Sell)"
else:
queue_spot = 1 + np.random.randint(0, 3)
fill_msg = f"Limit sell posted at {price:.2f}. Not immediately filled. Position in queue: #{queue_spot}"
else:
fill_msg = f"Limit sell posted above book: {price:.2f}. Not filled."
return df, fill_msg
def slippage_estimator(side, order_size, seed=123):
np.random.seed(seed)
base_price = 100
levels = np.arange(base_price-2, base_price+2.5, 0.5)
if side == "Buy":
sizes = np.random.randint(10, 70, len(levels))
prices = levels[levels > base_price]
sizes = sizes[levels > base_price]
else:
sizes = np.random.randint(10, 70, len(levels))
prices = levels[levels < base_price]
sizes = sizes[levels < base_price]
remaining = order_size
fills = []
for p, s in zip(prices, sizes):
take = min(s, remaining)
fills.append((p, take))
remaining -= take
if remaining <= 0:
break
if remaining > 0:
return "Not enough liquidity to fill order!", None
df = pd.DataFrame(fills, columns=["Price", "Shares"])
avg_fill = (df["Price"] * df["Shares"]).sum() / order_size
slip = avg_fill - base_price if side == "Buy" else base_price - avg_fill
slip_pct = (slip / base_price) * 100
summary = f"Est. avg fill @ {avg_fill:.2f}; Slippage: {slip:.2f} ({slip_pct:.2f}%) from ideal {base_price}"
return summary, df
# --- Instantiate Utilities ---
sec_utils = SECUtils()
news_utils = NewsUtils()
def update_stock_info(ticker):
if not ticker or not ticker.strip():
empty_msg = "Enter a ticker symbol to see data"
return empty_msg, empty_msg, empty_msg, empty_msg, get_tradingview_embed("AAPL")
ticker = ticker.upper().strip()
quote_data = fetch_polygon_quote(ticker)
time.sleep(0.3)
news_data = news_utils.get_yahoo_news(ticker)
time.sleep(0.3)
filings_data = sec_utils.get_recent_filings(ticker)
time.sleep(0.3)
financial_data = get_financial_summary_finnhub(ticker)
time.sleep(0.3)
chart_html = get_tradingview_embed(ticker)
return quote_data, news_data, filings_data, financial_data, chart_html
css = """
.gradio-container {font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; max-width: 1400px; margin: 0 auto;}
.tab-nav button {font-size: 16px; font-weight: 600;}
"""
with gr.Blocks(css=css, theme=gr.themes.Soft(), title="Bullish Minds AI - Stock Research & Education Platform") as demo:
gr.Image("logo.png", elem_id="header-logo", show_label=False, show_download_button=False)
gr.Markdown("""
# **Bullish Minds AI**
*Stock Research Platform MVP*
**Comprehensive stock analysis, real-time data, and interactive education modules.**
🎯 Enter a stock ticker symbol (**AAPL**, **TSLA**, **MSFT**, **GOOGL**) for market data, or check out the Lessons tab for learning modules!
⚠️ **Note**: Stock quote data from Polygon (Previous Close for free plans). Financial summary from Finnhub. Charts powered by TradingView.
""")
with gr.Row():
with gr.Column(scale=3):
ticker_input = gr.Textbox(
label="Stock Ticker",
placeholder="Enter ticker (e.g., AAPL, TSLA, MSFT)",
value="AAPL"
)
with gr.Column(scale=1):
refresh_btn = gr.Button("🔄 Refresh Data", variant="primary", size="lg")
with gr.Tabs():
with gr.TabItem("💰 Quote & Overview"):
quote_output = gr.Markdown(value="Enter a ticker to see stock quote")
with gr.TabItem("📰 News"):
news_output = gr.Markdown(value="Enter a ticker to see latest news")
with gr.TabItem("📄 SEC Filings"):
filings_output = gr.Markdown(value="Enter a ticker to see SEC filings")
with gr.TabItem("📊 Financial Summary"):
financial_output = gr.Markdown(value="Enter a ticker to see financial summary")
with gr.TabItem("📈 Price Chart"):
gr.Markdown("### Interactive Price Chart")
gr.Markdown("*Powered by TradingView*")
chart_output = gr.HTML(get_tradingview_embed("AAPL"))
with gr.TabItem("🎓 Lessons"):
with gr.Tabs():
with gr.TabItem("Lesson 1: Market Venues Explained"):
gr.Markdown("## Lesson 1 — Market Venues: Exchanges, Dark Pools, Auction vs. Dealer Markets")
with gr.Accordion("Why this matters", open=True):
gr.Markdown("""
Before you place any trade, it helps to know where your order goes and who it interacts with. Understanding market venues explains why a fill is fast or slow, why prices “jump,” and why a limit order protects you.
""")
with gr.Accordion("Learning objectives", open=False):
gr.Markdown("""
By the end of this lesson, you will be able to:
- Define exchanges, dark pools (ATS), auction markets, and dealer markets.
- Explain how orders interact on a central limit order book versus with a dealer/market maker.
- Describe what happens during opening/closing auctions and why they matter.
- List pros/cons of lit exchanges and dark pools for typical retail traders.
- Choose a suitable order type (market vs. limit) based on venue dynamics.
""")
with gr.Accordion("Key terms (quick definitions)", open=False):
gr.Markdown("""
- **Exchange (lit venue):** A registered marketplace where bids/offers are displayed ("lit") and orders match by rules (e.g., price–time priority).
- **Central Limit Order Book (CLOB):** The public queue of buy/sell limit orders at each price.
- **NBBO:** National Best Bid and Offer; the best quoted prices across exchanges (US concept).
- **Auction market:** Buyers and sellers compete by submitting orders; price emerges from order interaction (e.g., NYSE open/close auctions; continuous double auctions).
- **Dealer market:** Dealers/market makers quote both bid and ask and trade against customers (e.g., wholesalers; historically Nasdaq).
- **Market maker (MM):** A dealer obligated/encouraged to quote and provide liquidity.
- **Dark pool / ATS:** Alternative Trading System where quotes are not displayed; orders often execute at or within NBBO.
- **Price improvement:** Getting a better price than the displayed NBBO.
- **Slippage:** Getting a worse execution price than expected due to fast moves or thin liquidity.
""")
with gr.Accordion("1) Big picture: Where can your order go?", open=False):
gr.Markdown("""
Your broker’s smart order router can send your order to:
- Lit exchanges (NYSE, Nasdaq, Cboe, IEX, etc.) — orders join the public book.
- Wholesalers/internalizers (dealer firms handling retail flow) — they fill against their inventory/quotes.
- Dark pools (ATS) — non‑displayed venues where orders may match at midpoint or within the spread.
You  →  Broker/Router  →  { Lit Exchange  |  Wholesaler/Dealer  |  Dark Pool }
Each path has trade‑offs in speed, price improvement, and transparency.
""")
with gr.Accordion("2) Exchanges (lit venues)", open=False):
gr.Markdown("""
What they are: Regulated marketplaces that publish quotes and trades. Orders line up on a public order book.
How matching works (simplified):
- Price–time priority: Best price first; earlier orders at the same price are ahead in the queue.
- Market orders cross the spread to fill immediately; limit orders wait in the book until hit/lifted.
**Auctions on exchanges:**
- Opening auction sets the first regular‑hours price by crossing all eligible orders at a single price.
- Closing auction sets the official closing price, often with large institutional volume.
- Benefits: concentrated liquidity, reduced slippage at the cross; transparent reference prices.
**Examples (conceptual):**
- NYSE is a hybrid: electronic CLOB plus designated market makers (DMMs) overseeing auctions.
- Nasdaq uses multiple market makers and an electronic book; it also runs opening/closing crosses.
**Pros for retail:**
- Transparent quotes (you can see the book’s top levels via Level I/II).
- Strong price discovery; reference prices (open/close) are widely used.
**Cons:**
- Quoted spreads can widen during news or at the open; fills may be partial if your limit is too tight.
""")
with gr.Accordion("3) Dark pools (ATS)", open=False):
gr.Markdown("""
What they are: Electronic venues where orders are not displayed. Often match at midpoint (between bid and ask) or within the spread.
Why they exist:
- Reduce market impact for larger orders (institutions don’t reveal hand).
- Offer potential price improvement vs. the displayed NBBO.
How they work (simplified):
- Orders reference the NBBO from lit exchanges but do not show size/price publicly.
- Your order may match passively (you rest and wait) or actively (you interact with liquidity inside).
**Pros:**
- Possible price improvement; lower signaling.
**Cons:**
- Less transparency; potential adverse selection (you trade when price is about to move against you).
- Limited size for thin names; not all orders get matched quickly.
**Myth buster:** “Dark” ≠ illegal. These are regulated ATS venues; they’re simply non‑displayed.
""")
with gr.Accordion("4) Auction vs. Dealer markets (and today’s hybrid reality)", open=False):
gr.Markdown("""
Auction market (concept):
- Price emerges from buyers and sellers competing on a book (continuous double auction).
- Open/close auctions are batch auctions that cross many orders at one price.
Dealer market (concept):
- Dealers/market makers post bid/ask and stand ready to trade from their inventory.
- Execution is against the dealer’s quote; multiple dealers may compete.
Hybrid reality:
- Modern US equities combine both: electronic order books and market makers. Nasdaq is dealer‑heavy with an order book; NYSE is auction‑centric with DMMs.
Why you care:
- In dealer interactions, you may see price improvement and fast fills; on auctions/books, you can seek transparent price with tighter control via limits.
""")
with gr.Accordion("5) Routing, best execution, and your order type", open=False):
gr.Markdown("""
Brokers must seek best execution (price, speed, likelihood of fill, etc.).
- Market orders aim for immediate fill but can be exposed to slippage in fast moves.
- Limit orders set a maximum buy or minimum sell price, protecting you from surprise fills.
For thin or volatile names, prefer limits; around the open/close, consider participating in auctions or waiting a few minutes for spreads to normalize.
""")
with gr.Accordion("6) Practical tips (beginner‑friendly)", open=False):
gr.Markdown("""
- Use limit orders by default for single‑name stocks, especially at the open.
- If placing larger orders, consider slicing (several smaller limits) to reduce impact.
- Avoid chasing during halts/news spikes; liquidity can vanish and spreads widen.
- For end‑of‑day execution, the closing auction can offer fair, liquid prices.
""")
with gr.Accordion("7) Mini‑scenarios (choose one answer)", open=False):
gr.Markdown("""
You want 200 shares, the spread is wide, and the stock is jumping around. Best choice?
A) Market buy now
B) Place a limit buy near the mid or a level you’re happy with
You need the official benchmark price for a fund’s daily report. Which event?
A) Closing auction
B) First midpoint fill you see
Which venue hides quotes but can provide price improvement?
A) Lit exchange
B) Dark pool (ATS)
In which model do market makers quote and trade against you from inventory?
A) Auction market
B) Dealer market
You dislike surprises in fast markets. Which order type reduces risk of a bad fill?
A) Market order
B) Limit order
""")
with gr.Accordion("8) Review checklist", open=False):
gr.Markdown("""
I can explain the difference between lit exchanges and dark pools.
I know what NBBO means and why it matters.
I understand auction vs. dealer markets and today’s hybrid reality.
I can choose between market and limit orders based on conditions.
I know when opening/closing auctions might be useful.
""")
with gr.Accordion("9) App‑integration hooks", open=False):
gr.Markdown("""
Interactive: Order Book Simulator (queue position, partial fills); Auction Replay (open/close cross).
Calculator: Slippage estimator (expected fill vs. NBBO); Limit‑vs‑Market decision helper.
Checklist widget: “Before you submit an order” (spread, volatility, venue notes).
Glossary popovers: NBBO, CLOB, dealer, DMM, adverse selection.
""")
with gr.Accordion("10) Glossary (recap)", open=False):
gr.Markdown("""
CLOB: Central public queue of limit orders on an exchange.
Dealer/MM: Firm quoting bid/ask and trading from inventory.
Auction: Batch or continuous matching based on order interaction.
Dark pool/ATS: Non‑displayed matching venue, often at NBBO/midpoint.
NBBO: Best national bid and offer across exchanges.
Price improvement: Better execution than the displayed best price.
Slippage: Fill worse than expected due to movement/liquidity.
""")
with gr.Accordion("11) What’s next", open=False):
gr.Markdown("""
Proceed to Lesson 2: Order Types Deep Dive (market, limit, stop, stop‑limit, trailing, OCO), then Lesson 3: Reading the Tape (Level I/II, Time & Sales).
""")
gr.Markdown("---")
gr.Markdown("*Try the tools below to visualize order book mechanics and slippage:*")
with gr.Tabs():
with gr.TabItem("Order Book Simulator"):
lesson1_order = gr.Interface(
fn=simulate_order_book,
inputs=[
gr.Dropdown(["Buy", "Sell"], label="Order Side"),
gr.Dropdown(["Market", "Limit"], label="Order Type"),
gr.Number(value=100.00, label="Order Price (for limit)"),
gr.Slider(1, 100, value=10, step=1, label="Order Size"),
gr.Number(value=123, label="Seed (optional, for replay)")
],
outputs=[
gr.Dataframe(label="Order Book (randomized)"),
gr.Textbox(label="Result / Fill Message")
],
live=False,
allow_flagging="never"
)
with gr.TabItem("Slippage Estimator"):
lesson1_slippage = gr.Interface(
fn=slippage_estimator,
inputs=[
gr.Dropdown(["Buy", "Sell"], label="Order Side"),
gr.Slider(1, 300, value=50, step=1, label="Order Size"),
gr.Number(value=123, label="Seed (for repeatability)")
],
outputs=[
gr.Textbox(label="Estimate"),
gr.Dataframe(label="Fill breakdown")
],
live=False,
allow_flagging="never"
)
with gr.TabItem("Lesson 2: Tickers, Floats, Market Cap, Sectors, Indices"):
gr.Markdown("## Lesson 2 — Tickers, Floats, Market Cap, Sectors, Indices")
with gr.Accordion("Overview", open=True):
gr.Markdown("""
This lesson explains what stock tickers are, how share float affects trading, how to compute and interpret market capitalization, how sectors organize the market, and how indices track groups of companies. Simple formulas and examples are included for day-to-day use.
""")
with gr.Accordion("Tickers", open=False):
gr.Markdown("""
A **ticker** is the short symbol used to identify a publicly traded company on an exchange (e.g. `AAPL` for Apple). Each exchange manages unique symbols, and finance apps use tickers to retrieve data.
Tickers link directly to price, news, filings, and company fundamentals.
**Quick checks:**
- Confirm the exchange if companies share similar symbols (e.g., US vs. international).
- Use the ticker consistently in screeners, EDGAR filings, and news searches.
""")
with gr.Accordion("Float (Floating Shares)", open=False):
gr.Markdown(r"""
**Definition:**
Float = Shares Outstanding − Restricted or Insider Shares
Low float means fewer shares actively trade, which boosts volatility. High float dampens price swings.
**Why float matters:**
- **Liquidity:** Higher float usually narrows the bid-ask spread; low float can cause sharp jumps.
- **Corporate actions:** Buybacks, splits, and insider sales alter float and trading dynamics.
**Example:**
Company has 20M outstanding shares, 5M are insider-restricted.
Float = 20M − 5M = **15M** shares.
""")
with gr.Accordion("Market Capitalization", open=False):
gr.Markdown(r"""
**Definition:**
Market Cap = Share Price × Shares Outstanding
Market cap reflects the total equity value of a company.
**Size buckets:**
- Micro-cap: < $250M
- Small-cap: $250M – $2B
- Mid-cap: $2B – $10B
- Large-cap: $10B – $200B
- Mega-cap: > $200B
(Cutoffs may vary).
**Example:**
Company trades at $20 with 5M shares outstanding.
Market cap = $20 × 5,000,000 = **$100M** (small-cap).
""")
with gr.Accordion("Sectors", open=False):
gr.Markdown("""
**Sectors** are broad industry groups (e.g., Information Technology, Health Care, Financials) used by analysts and index providers.
Grouping by sector makes it easier to benchmark companies and build portfolios.
**Tips:**
- Analyze peers within the same sector for meaningful comparisons.
- Sector rotation strategies try to overweight sectors based on macro trends.
""")
with gr.Accordion("Indices", open=False):
gr.Markdown("""
An **index** tracks the performance of a basket of stocks (e.g., S&P 500, Dow Jones, Nasdaq-100, Russell 2000).
**Weighting methods:**
- **Market-cap-weighted:** Larger companies have more influence.
- **Equal-weighted:** All companies have the same weight.
- **Price-weighted:** High-priced stocks move the index more.
**Why indices matter:**
- **Benchmarks:** Used to compare portfolio returns.
- **Access:** Index funds/ETFs enable diversified investing.
""")
with gr.Accordion("Putting It Together", open=False):
gr.Markdown("""
- **Ticker →** the unique handle that links all research and trading data.
- **Float →** governs real trading volume, volatility, and liquidity.
- **Market Cap →** frames company size, growth, and risk.
- **Sectors →** context for analyzing peers and market cycles.
- **Indices →** anchor performance and guide diversified investing.
""")
with gr.Accordion("Mini-Formulas and Examples", open=False):
gr.Markdown(r"""
**Float:**
\( \text{Float} = \text{Outstanding} - \text{Restricted} \)
Example: \( 10M - 3M = 7M \) tradable shares.
**Market Cap:**
\( \text{Cap} = P \times N \)
Example: \( \$50 \times 5,000,000 = \$250M \) (micro/small-cap).
**Index weight (market-cap):**
\( \text{Weight} = \frac{\text{Company Cap}}{\text{Index Cap}} \)
""")
with gr.Accordion("Red Flags and Pro Tips", open=False):
gr.Markdown("""
- Low float stocks can swing wildly on news or social buzz—use limit orders!
- Don’t compare companies on share price alone—market cap tells true size.
- Match your benchmark index’s strategy and market cap to your investment style.
""")
with gr.Accordion("Quick Quiz", open=False):
gr.Markdown("""
**Q:** Company has 50M shares outstanding; 15M are restricted. What’s the float?
**A:** 35M
**Q:** Share price is $25; outstanding shares are 80M. Market cap?
**A:** $25 × 80M = $2B (mid-cap)
**Q:** Why might two companies with the same share price be different sizes?
**A:** Because number of outstanding shares differs—changing market cap.
**Q:** Name a reason sector classification is useful.
**A:** Peer comparison, sector ETFs.
**Q:** In a market-cap-weighted index, what do bigger companies mean?
**A:** They carry more weight—move the index more.
""")
# Add future lessons here as new gr.TabItem("Lesson X: ...")
gr.Markdown("""
---
**Data Sources:** Polygon.io for quotes, Finnhub for financials, Yahoo RSS for news, SEC EDGAR for filings.
**Troubleshooting:** If you encounter errors, double-check your ticker or wait and retry.
""")
ticker_input.change(
fn=update_stock_info,
inputs=[ticker_input],
outputs=[quote_output, news_output, filings_output, financial_output, chart_output]
)
refresh_btn.click(
fn=update_stock_info,
inputs=[ticker_input],
outputs=[quote_output, news_output, filings_output, financial_output, chart_output]
)
if __name__ == "__main__":
demo.launch(show_error=True)