python
import yfinance as yf
from tabulate import tabulate
def fetch_fundamentals(ticker):
stock = yf.Ticker(ticker)
info = stock.info
fundamentals = {
"Company Name": info.get("longName"),
"Ticker": ticker,
"Market Cap": info.get("marketCap"),
"PE Ratio (TTM)": info.get("trailingPE"),
"Forward PE": info.get("forwardPE"),
"PEG Ratio": info.get("pegRatio"),
"EPS (TTM)": info.get("trailingEps"),
"Forward EPS": info.get("forwardEps"),
"Dividend Yield": info.get("dividendYield"),
"P/B Ratio": info.get("priceToBook"),
"Beta (Volatility)": info.get("beta"),
"52W High": info.get("fiftyTwoWeekHigh"),
"52W Low": info.get("fiftyTwoWeekLow"),
"Current Price": info.get("currentPrice"),
"Analyst Recommendation": info.get("recommendationKey").title() if info.get("recommendationKey") else None
}
return fundamentals
def analyze_stock(fundamentals):
print("\n[+] Investment Analysis Summary:")
price = fundamentals["Current Price"]
pe = fundamentals["PE Ratio (TTM)"]
forward_pe = fundamentals["Forward PE"]
peg = fundamentals["PEG Ratio"]
pb = fundamentals["P/B Ratio"]
beta = fundamentals["Beta (Volatility)"]
div_yield = fundamentals["Dividend Yield"]
analysis = []
# PE Ratio
if pe and pe < 15:
analysis.append(("PE Ratio", "Attractive (Below 15)", "Undervalued potential"))
elif pe and pe > 25:
analysis.append(("PE Ratio", "Expensive (Above 25)", "Potential overvaluation"))
else:
analysis.append(("PE Ratio", "Moderate", "Fairly valued"))
# Forward PE
if forward_pe and forward_pe < pe:
analysis.append(("Forward PE", "Positive", "Expected earnings growth"))
elif forward_pe and forward_pe > pe:
analysis.append(("Forward PE", "Caution", "Earnings may decline"))
else:
analysis.append(("Forward PE", "Neutral", "No clear trend"))
# PEG Ratio
if peg and peg < 1:
analysis.append(("PEG Ratio", "Favorable (Below 1)", "Earnings growth priced in"))
elif peg and peg > 1.5:
analysis.append(("PEG Ratio", "Unfavorable (Above 1.5)", "Overvalued relative to growth"))
else:
analysis.append(("PEG Ratio", "Normal", "Balanced valuation"))
# P/B Ratio
if pb and pb < 1:
analysis.append(("P/B Ratio", "Low (<1)", "May be undervalued"))
elif pb and pb > 3:
analysis.append(("P/B Ratio", "High (>3)", "Possibly overvalued"))
else:
analysis.append(("P/B Ratio", "Normal", "Typical valuation"))
# Beta
if beta and beta < 1:
analysis.append(("Beta", "Low (<1)", "Less volatile than market"))
elif beta and beta > 1.5:
analysis.append(("Beta", "High (>1.5)", "More volatile than market"))
else:
analysis.append(("Beta", "Normal", "Market-level volatility"))
# Dividend Yield
if div_yield and div_yield > 0.025:
analysis.append(("Dividend Yield", f"{div_yield * 100:.2f}%", "Good income generation"))
elif div_yield:
analysis.append(("Dividend Yield", f"{div_yield * 100:.2f}%", "Low income"))
else:
analysis.append(("Dividend Yield", "N/A", "No dividend"))
return analysis
def display_output(fundamentals, analysis):
# Print Fundamentals
table_data = [[key, value] for key, value in fundamentals.items()]
print("\n[+] Stock Fundamentals:")
print(tabulate(table_data, headers=["Metric", "Value"], tablefmt="grid"))
# Print Analysis
analysis_table = [[metric, status, comment] for metric, status, comment in analysis]
print(tabulate(analysis_table, headers=["Metric", "Status", "Comment"], tablefmt="grid"))
def main():
ticker = input("Enter stock ticker symbol (e.g., AAPL): ").strip().upper()
print(f"\n[+] Fetching data for {ticker}...")
try:
fundamentals = fetch_fundamentals(ticker)
analysis = analyze_stock(fundamentals)
display_output(fundamentals, analysis)
except Exception as e:
print(f"[-] Error fetching data: {e}")
if __name__ == "__main__":
main()