Below is an example Python script that uses the popular yfinance library to fetch stock fundamentals for a given ticker and performs a basic investment analysis. The script:
- Prompts you for a ticker symbol.
- Fetches the stock’s fundamentals (such as current price, market cap, P/E ratio, dividend yield, beta, etc.).
- Conducts a simple analysis based on common valuation and risk metrics.
- Prints out both the raw fundamentals and a brief interpretation.
Before running the script, install the necessary dependency with:
pip install yfinance
Here is the complete script:
import yfinance as yf
import sys
def fetch_fundamentals(ticker_symbol):
"""
Uses yfinance to fetch stock fundamentals for the given ticker.
"""
try:
stock = yf.Ticker(ticker_symbol)
info = stock.info
# If the ticker is invalid or info is empty, raise an error.
if not info or "regularMarketPrice" not in info:
raise ValueError("No valid market data found. Check the ticker symbol.")
return info
except Exception as e:
print(f"Error fetching data for {ticker_symbol}: {e}")
sys.exit(1)
def analyze_stock(info):
"""
Performs a basic analysis using common investment metrics.
Note: This is a very simplistic analysis and should not be construed
as investment advice.
"""
analysis = []
# Price and valuation metrics
current_price = info.get("regularMarketPrice")
trailing_pe = info.get("trailingPE")
forward_pe = info.get("forwardPE")
market_cap = info.get("marketCap")
price_to_book = info.get("priceToBook")
# Dividend and growth metrics
dividend_yield = info.get("dividendYield")
earnings_growth = info.get("earningsQuarterlyGrowth")
# Risk metric
beta = info.get("beta")
analysis.append(f"Current Price: ${current_price}")
analysis.append(f"Market Cap: {market_cap:,}" if market_cap else "Market Cap: N/A")
# P/E Analysis
if trailing_pe:
analysis.append(f"Trailing P/E: {trailing_pe:.2f}")
if trailing_pe < 15:
analysis.append("=> The stock has a relatively low P/E ratio, which might indicate it is undervalued.")
elif trailing_pe > 25:
analysis.append("=> The stock's P/E ratio is high, which could signal high growth expectations or potential overvaluation.")
else:
analysis.append("=> The P/E ratio appears moderate.")
else:
analysis.append("Trailing P/E: N/A")
if forward_pe:
analysis.append(f"Forward P/E: {forward_pe:.2f}")
else:
analysis.append("Forward P/E: N/A")
# Price-to-Book Analysis
if price_to_book:
analysis.append(f"Price-to-Book Ratio: {price_to_book:.2f}")
if price_to_book < 1:
analysis.append("=> A P/B ratio below 1 might indicate that the stock is undervalued relative to its book value.")
else:
analysis.append("=> The P/B ratio is above 1.")
else:
analysis.append("Price-to-Book Ratio: N/A")
# Dividend Analysis
if dividend_yield is not None:
# dividendYield is usually provided as a fraction (e.g., 0.02 for 2%).
div_yield_percent = dividend_yield * 100
analysis.append(f"Dividend Yield: {div_yield_percent:.2f}%")
if div_yield_percent >= 2:
analysis.append("=> A dividend yield of 2% or higher can be attractive for income-focused investors.")
else:
analysis.append("=> Dividend yield is low; this stock might be more growth-oriented or not focused on income.")
else:
analysis.append("Dividend Yield: N/A")
# Growth Analysis
if earnings_growth:
# earningsQuarterlyGrowth might be expressed as a decimal.
growth_percent = earnings_growth * 100
analysis.append(f"Earnings Quarterly Growth: {growth_percent:.2f}%")
if growth_percent > 10:
analysis.append("=> Strong earnings growth.")
else:
analysis.append("=> Modest earnings growth.")
else:
analysis.append("Earnings Quarterly Growth: N/A")
# Beta Analysis (risk)
if beta:
analysis.append(f"Beta: {beta:.2f}")
if beta < 1:
analysis.append("=> A beta less than 1 indicates lower volatility compared to the market (less risk).")
elif beta > 1:
analysis.append("=> A beta greater than 1 indicates higher volatility compared to the market (more risk).")
else:
analysis.append("=> The stock's volatility is comparable to the market.")
else:
analysis.append("Beta: N/A")
return analysis
def main():
ticker_symbol = input("Enter the stock ticker symbol (e.g., AAPL): ").strip().upper()
print(f"\nFetching data for {ticker_symbol}...\n")
fundamentals = fetch_fundamentals(ticker_symbol)
print("=== Stock Fundamentals ===")
keys_of_interest = [
"regularMarketPrice", "marketCap", "trailingPE", "forwardPE",
"dividendYield", "beta", "priceToBook", "earningsQuarterlyGrowth"
]
for key in keys_of_interest:
value = fundamentals.get(key, "N/A")
# Format the output for some fields.
if key == "dividendYield" and value != "N/A":
value = f"{value*100:.2f}%"
elif key == "trailingPE" and value != "N/A":
value = f"{value:.2f}"
elif key == "forwardPE" and value != "N/A":
value = f"{value:.2f}"
elif key == "beta" and value != "N/A":
value = f"{value:.2f}"
elif key == "priceToBook" and value != "N/A":
value = f"{value:.2f}"
print(f"{key}: {value}")
print("\n=== Investment Analysis ===")
analysis_output = analyze_stock(fundamentals)
for line in analysis_output:
print(line)
print("\nDisclaimer: This analysis is simplistic and for demonstration purposes only. Always perform your own research or consult with a financial advisor before making investment decisions.")
if __name__ == "__main__":
main()
How It Works
-
Fetching Data:
The fetch_fundamentals function uses yf.Ticker(ticker_symbol) to get the stock’s details. It then checks for essential data (like regularMarketPrice) to ensure the ticker is valid.
-
Analysis:
The analyze_stock function examines various metrics:
- P/E Ratios: Compares trailing and forward P/E ratios against common thresholds.
- Price-to-Book Ratio: Provides a hint on valuation.
- Dividend Yield: Indicates if the stock might be suitable for income investors.
- Earnings Growth: Speaks to the company’s recent performance.
- Beta: Helps analyze the stock’s volatility relative to the market.
-
Output:
Both raw metrics and a brief analysis commentary are printed out.
Remember that this script offers a basic starting point. In practice, more robust analysis would include additional data points, trend analysis, and industry comparisons. Always do thorough research and consider multiple factors when evaluating an investment.