Skip to content

Instantly share code, notes, and snippets.

@rajvermacas
Created October 7, 2024 19:56
Show Gist options
  • Save rajvermacas/fdb5b5ed7867aa91f5df8c714e89c5da to your computer and use it in GitHub Desktop.
Save rajvermacas/fdb5b5ed7867aa91f5df8c714e89c5da to your computer and use it in GitHub Desktop.
Get stock financial ratios
import yfinance as yf
def get_stock_metrics(ticker_symbol):
# Create a Ticker object
stock = yf.Ticker(ticker_symbol)
# Fetch the data
info = stock.info
# Extract the requested metrics
metrics = {
"Price-to-Earnings Ratio": info.get("trailingPE"),
"Price-to-Book Ratio": info.get("priceToBook"),
"Price-to-Cash Flow from Operations": info.get("priceToOperatingCashFlows"),
"Price-to-Sales Ratio": info.get("priceToSalesTrailing12Months"),
"EV-to-EBITDA": info.get("enterpriseToEbitda"),
"Market Cap": info.get("marketCap"),
"Dividend Yield": info.get("dividendYield", 0) * 100 if info.get("dividendYield") else None
}
return metrics
# Example usage
ticker = "DIXON.NS" # Apple Inc.
stock_metrics = get_stock_metrics(ticker)
for metric, value in stock_metrics.items():
if value is not None:
if metric == "Market Cap":
print(f"{metric}: ${value:,.0f}")
elif metric == "Dividend Yield":
print(f"{metric}: {value:.2f}%")
else:
print(f"{metric}: {value:.2f}")
else:
print(f"{metric}: N/A")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment