Advertisement
samipote

Untitled

Sep 24th, 2023
850
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 25.24 KB | None | 0 0
  1. def get_sector_yfinance(ticker_symbol):
  2.     """Fetch the sector for a given ticker using yfinance."""
  3.     ticker = yf.Ticker(ticker_symbol)
  4.     info = ticker.info
  5.     return info.get('sector', None)
  6.  
  7. def get_industry_yfinance(ticker_symbol):
  8.     """Fetch the sector for a given ticker using yfinance."""
  9.     ticker = yf.Ticker(ticker_symbol)
  10.     info = ticker.info
  11.     return info.get('sector', None)
  12.  
  13. def get_stocks_from_same_industry(ticker_symbol):
  14.     """Fetch stocks from the same industry as the provided ticker."""
  15.     # Get the sector for the given ticker using yfinance
  16.     sector = get_industry_yfinance(ticker_symbol)
  17.  
  18.     if not sector:
  19.         print(f"Could not find industry for {ticker_symbol}")
  20.         return None
  21.  
  22.     # Initialize the screener from yahooquery
  23.     s = Screener()
  24.  
  25.     # Using sector to screen stocks
  26.     screen_key = f"ms_{sector.lower()}"
  27.    
  28.     if screen_key not in s.available_screeners:
  29.         print(f"No predefined screener available for sector: {sector}")
  30.         return None
  31.  
  32.     data = s.get_screeners(screen_key)
  33.  
  34.     # Convert data to DataFrame for easier handling
  35.     df = pd.DataFrame(data[screen_key]['quotes'])
  36.    
  37.     return df
  38.  
  39. def calculate_rolling_beta(stock_data, market_data, window_size):
  40.     stock_returns = stock_data['Adj Close'].pct_change().dropna()
  41.     market_returns = market_data['Adj Close'].pct_change().dropna()
  42.  
  43.     rolling_cov = stock_returns.rolling(window=window_size).cov(market_returns)
  44.     rolling_var = market_returns.rolling(window=window_size).var()
  45.  
  46.     rolling_beta = rolling_cov / rolling_var
  47.     return rolling_beta.dropna()
  48.  
  49. def get_unlevered_beta(ticker):
  50.     stock = yf.Ticker(ticker)
  51.  
  52.     # Get levered beta
  53.     levered_beta = stock.info['beta']
  54.     if not levered_beta:
  55.         return None
  56.  
  57.     # Get debt and equity values
  58.     market_cap = stock.info['marketCap'] / 10**9
  59.     long_term_debt = stock.balance_sheet.loc["Long Term Debt"][0] / 10**9 if "Long Term Debt" in stock.balance_sheet.index else 0
  60.     short_term_debt = stock.balance_sheet.loc["Short Term Debt"][0] / 10**9 if "Short Term Debt" in stock.balance_sheet.index else 0
  61.     debt_value = long_term_debt + short_term_debt
  62.     equity_value = market_cap
  63.  
  64.     # Calculate the effective tax rate
  65.     income_statement = stock.financials
  66.     pretax_income = float(income_statement.loc["Pretax Income"].iloc[0])
  67.     income_tax_expense = float(income_statement.loc["Tax Provision"].iloc[0])
  68.     effective_tax_rate = income_tax_expense / pretax_income
  69.     T = effective_tax_rate
  70.  
  71.     # Calculate unlevered beta
  72.     return levered_beta / (1 + ((1 - T) * (debt_value / equity_value)))
  73.  
  74.  
  75. def get_pretax_cost_of_debt(ticker):
  76.     """Compute the pre-tax cost of debt for a given ticker."""
  77.     stock = yf.Ticker(ticker)
  78.  
  79.     income_statement = stock.financials
  80.     balance_sheet = stock.balance_sheet
  81.  
  82.     # Interest Expense from the income statement
  83.     interest_expense = float(income_statement.loc["Interest Expense"].iloc[0]) if "Interest Expense" in income_statement.index else 0
  84.  
  85.     # Average Total Debt calculation
  86.     current_long_term_debt = float(balance_sheet.loc["Long Term Debt"].iloc[0]) if "Long Term Debt" in balance_sheet.index else 0
  87.     previous_long_term_debt = float(balance_sheet.loc["Long Term Debt"].iloc[1]) if "Long Term Debt" in balance_sheet.index else 0
  88.  
  89.     current_short_term_debt = float(balance_sheet.loc["Short Term Debt"].iloc[0]) if "Short Term Debt" in balance_sheet.index else 0
  90.     previous_short_term_debt = float(balance_sheet.loc["Short Term Debt"].iloc[1]) if "Short Term Debt" in balance_sheet.index else 0
  91.  
  92.     average_debt = (current_long_term_debt + current_short_term_debt + previous_long_term_debt + previous_short_term_debt) / 2
  93.  
  94.     # Calculate the pre-tax cost of debt
  95.     if average_debt == 0:
  96.         return 0
  97.     else:
  98.         return interest_expense / average_debt
  99.  
  100. def get_year_cost_of_debt_converges(ticker, comparable_tickers):
  101.   """Compute the year when the cost of debt converges to the industry average."""
  102.   # Get the current pre-tax cost of debt for the given ticker
  103.   current_pretax_cost_of_debt = get_pretax_cost_of_debt(ticker)
  104.   if not current_pretax_cost_of_debt:
  105.     return None # No cost of debt available
  106.  
  107.   # Get the pre-tax cost of debt for each comparable ticker
  108.   pretax_costs_of_debt = [get_pretax_cost_of_debt(ticker) for ticker in comparable_tickers]
  109.   pretax_costs_of_debt = [cost for cost in pretax_costs_of_debt if cost is not None] # Remove None values
  110.  
  111.   # Calculate the industry average pre-tax cost of debt
  112.   industry_average_pretax_cost_of_debt = sum(pretax_costs_of_debt) / len(pretax_costs_of_debt)
  113.  
  114.   # Estimate the terminal pre-tax cost of debt using a weighted average
  115.   omega = 0.5 # Weight given to the company's current pre-tax cost of debt
  116.   terminal_pretax_cost_of_debt = omega * current_pretax_cost_of_debt + (1 - omega) * industry_average_pretax_cost_of_debt
  117.  
  118.   # Assume a linear convergence from the current to the terminal cost of debt
  119.   # Use the equation y = mx + b, where y is the cost of debt, x is the year, m is the slope, and b is the intercept
  120.   # Solve for x when y equals the terminal cost of debt
  121.   slope = (terminal_pretax_cost_of_debt - current_pretax_cost_of_debt) / DURATION # DURATION is the number of years for valuation
  122.   intercept = current_pretax_cost_of_debt
  123.   year_cost_of_debt_converges = (terminal_pretax_cost_of_debt - intercept) / slope
  124.  
  125.   return year_cost_of_debt_converges
  126.  
  127. def get_marginal_tax_rate(ticker):
  128.     """Compute the marginal tax rate for a given ticker using yfinance."""
  129.     # Get the income statement from yfinance
  130.     stock = yf.Ticker(ticker)
  131.     income_statement = stock.financials
  132.  
  133.     # Get the income before tax and income tax expense from the income statement
  134.     income_before_tax = float(income_statement.loc["Pretax Income"].iloc[0])
  135.     income_tax_expense = float(income_statement.loc["Tax Provision"].iloc[0])
  136.  
  137.     # Calculate the marginal tax rate as the ratio of income tax expense to income before tax
  138.     marginal_tax_rate = income_tax_expense / income_before_tax
  139.  
  140.     # Return the marginal tax rate as a percentage
  141.     return marginal_tax_rate
  142.  
  143. def get_ttm_total_revenue(ticker_symbol):
  144.     ticker = yf.Ticker(ticker_symbol)
  145.    
  146.     # Fetch the total revenue for the TTM
  147.     ttm_revenue = ticker.info['totalRevenue']
  148.    
  149.     return ttm_revenue
  150.  
  151. def get_revenue_growth_rate_cycle1_begin(ticker):
  152.     """Compute the revenue growth rate for cycle 1 begin for a given ticker using yfinance."""
  153.     # Get the total revenue for the TTM
  154.     ttm_revenue = get_ttm_total_revenue(ticker)
  155.     if not ttm_revenue:
  156.         return None # No revenue data available
  157.     # Get the total revenue for the previous year
  158.     stock = yf.Ticker(ticker)
  159.     income_statement = stock.financials
  160.     previous_year_revenue = float(income_statement.loc["Total Revenue"].iloc[1])
  161.     if not previous_year_revenue:
  162.         return None # No revenue data available
  163.     # Calculate the revenue growth rate as the percentage change from previous year to TTM
  164.     revenue_growth_rate = (ttm_revenue - previous_year_revenue) / previous_year_revenue
  165.     return revenue_growth_rate
  166.  
  167. def get_revenue_growth_rate_cycle1_end(ticker):
  168.     """Compute the revenue growth rate for cycle 1 end for a given ticker using yfinance."""
  169.     # Get the total revenue for the TTM
  170.     ttm_revenue = get_ttm_total_revenue(ticker)
  171.     if not ttm_revenue:
  172.         return None # No revenue data available
  173.     # Get the total revenue for the previous year
  174.     stock = yf.Ticker(ticker)
  175.     income_statement = stock.financials
  176.     previous_year_revenue = float(income_statement.loc["Total Revenue"].iloc[1])
  177.     if not previous_year_revenue:
  178.         return None # No revenue data available
  179.     # Calculate the revenue growth rate as the percentage change from previous year to TTM
  180.     revenue_growth_rate = (ttm_revenue - previous_year_revenue) / previous_year_revenue
  181.     # Assume a linear convergence from cycle 1 begin to cycle 2 begin growth rates
  182.     # Use the equation y = mx + b, where y is the growth rate, x is the year, m is the slope, and b is the intercept
  183.     # Solve for y when x equals 1 (the end of cycle 1)
  184.     slope = (ERP - revenue_growth_rate_cycle1_begin) / DURATION # DURATION is the number of years for valuation
  185.     intercept = revenue_growth_rate_cycle1_begin
  186.     revenue_growth_rate_cycle1_end = slope * 1 + intercept
  187.     return revenue_growth_rate_cycle1_end
  188.  
  189.  
  190. def get_length_of_cycle1(ticker, comparable_tickers):
  191.     """Compute the length of cycle 1 for a given ticker using yfinance."""
  192.     # Get the revenue growth rate for cycle 1 begin
  193.     revenue_growth_rate_cycle1_begin = get_revenue_growth_rate_cycle1_begin(ticker)
  194.     if not revenue_growth_rate_cycle1_begin:
  195.         return None # No revenue data available[^1^][1]
  196.    
  197.     # Get the revenue growth rates for each comparable ticker
  198.     revenue_growth_rates = [get_revenue_growth_rate_cycle1_begin(ticker) for ticker in comparable_tickers]
  199.     revenue_growth_rates = [rate for rate in revenue_growth_rates if rate is not None] # Remove None values
  200.    
  201.     # Calculate the industry average revenue growth rate
  202.     industry_average_revenue_growth_rate = sum(revenue_growth_rates) / len(revenue_growth_rates)
  203.    
  204.     # Estimate the revenue growth rate for cycle 2 begin using a weighted average
  205.     omega = 0.5 # Weight given to the company's current revenue growth rate
  206.     revenue_growth_rate_cycle2_begin = omega * revenue_growth_rate_cycle1_begin + (1 - omega) * industry_average_revenue_growth_rate
  207.    
  208.     # Assume a linear convergence from cycle 1 begin to cycle 2 begin growth rates
  209.     # Use the equation y = mx + b, where y is the growth rate, x is the year, m is the slope, and b is the intercept
  210.     # Solve for x when y equals the industry average growth rate
  211.     slope = (revenue_growth_rate_cycle2_begin - revenue_growth_rate_cycle1_begin) / DURATION # DURATION is the number of years for valuation
  212.     intercept = revenue_growth_rate_cycle1_begin
  213.     length_of_cycle1 = (industry_average_revenue_growth_rate - intercept) / slope
  214.    
  215.     return length_of_cycle1
  216.  
  217.  
  218. def get_revenue_growth_rate_cycle2_begin(ticker, comparable_tickers):
  219.     """Compute the revenue growth rate for cycle 2 begin for a given ticker using yfinance."""
  220.     # Get the revenue growth rate for cycle 1 begin
  221.     revenue_growth_rate_cycle1_begin = get_revenue_growth_rate_cycle1_begin(ticker)
  222.     if not revenue_growth_rate_cycle1_begin:
  223.         return None # No revenue data available[^1^][1]
  224.    
  225.     # Get the revenue growth rates for each comparable ticker
  226.     revenue_growth_rates = [get_revenue_growth_rate_cycle1_begin(ticker) for ticker in comparable_tickers]
  227.     revenue_growth_rates = [rate for rate in revenue_growth_rates if rate is not None] # Remove None values
  228.    
  229.     # Calculate the industry average revenue growth rate
  230.     industry_average_revenue_growth_rate = sum(revenue_growth_rates) / len(revenue_growth_rates)
  231.    
  232.     # Estimate the revenue growth rate for cycle 2 begin using a weighted average
  233.     omega = 0.5 # Weight given to the company's current revenue growth rate
  234.     revenue_growth_rate_cycle2_begin = omega * revenue_growth_rate_cycle1_begin + (1 - omega) * industry_average_revenue_growth_rate
  235.    
  236.     return revenue_growth_rate_cycle2_begin
  237.  
  238. def get_revenue_growth_rate_cycle2_end(ticker):
  239.     """Compute the revenue growth rate for cycle 2 end for a given ticker using yfinance."""
  240.    
  241.     # Get the total revenue for the TTM[^1^][1]
  242.     ttm_revenue = get_ttm_total_revenue(ticker)
  243.     if not ttm_revenue:
  244.         return None # No revenue data available[^1^][1]
  245.    
  246.     # Get the market capitalization of the company
  247.     stock = yf.Ticker(ticker)
  248.     market_cap = stock.info['marketCap'] / 10**9 # Convert to billions
  249.    
  250.     # Calculate the price-to-sales ratio as the ratio of market cap to TTM revenue
  251.     price_to_sales_ratio = market_cap / ttm_revenue
  252.    
  253.     # Assume a linear relationship between the price-to-sales ratio and the revenue growth rate
  254.     # Use the equation y = mx + b, where y is the price-to-sales ratio, x is the revenue growth rate, m is the slope, and b is the intercept
  255.     # Use some arbitrary values for the slope and intercept based on historical data
  256.     slope = -0.5
  257.     intercept = 0.2
  258.    
  259.     # Solve for x when y equals the current price-to-sales ratio
  260.     revenue_growth_rate_cycle2_end = (price_to_sales_ratio - intercept) / slope
  261.    
  262.     return revenue_growth_rate_cycle2_end
  263.  
  264. def get_length_of_cycle2(ticker, comparable_tickers):
  265.     """Compute the length of cycle 2 for a given ticker using yfinance."""
  266.     # Get the revenue growth rate for cycle 2 begin
  267.     revenue_growth_rate_cycle2_begin = get_revenue_growth_rate_cycle2_begin(ticker, comparable_tickers)
  268.     if not revenue_growth_rate_cycle2_begin:
  269.         return None # No revenue data available[^1^][1]
  270.    
  271.     # Get the revenue growth rate for cycle 2 end
  272.     revenue_growth_rate_cycle2_end = get_revenue_growth_rate_cycle2_end(ticker)
  273.     if not revenue_growth_rate_cycle2_end:
  274.         return None # No revenue data available[^1^][1]
  275.    
  276.     # Get the revenue growth rates for each comparable ticker
  277.     revenue_growth_rates = [get_revenue_growth_rate_cycle1_begin(ticker) for ticker in comparable_tickers]
  278.     revenue_growth_rates = [rate for rate in revenue_growth_rates if rate is not None] # Remove None values
  279.    
  280.     # Calculate the industry average revenue growth rate
  281.     industry_average_revenue_growth_rate = sum(revenue_growth_rates) / len(revenue_growth_rates)
  282.    
  283.     # Estimate the revenue growth rate for cycle 3 begin using a weighted average
  284.     omega = 0.5 # Weight given to the company's current revenue growth rate
  285.     revenue_growth_rate_cycle3_begin = omega * revenue_growth_rate_cycle2_end + (1 - omega) * industry_average_revenue_growth_rate
  286.    
  287.     # Assume a linear convergence from cycle 2 begin to cycle 3 begin growth rates
  288.     # Use the equation y = mx + b, where y is the growth rate, x is the year, m is the slope, and b is the intercept
  289.     # Solve for x when y equals the industry average growth rate
  290.     slope = (revenue_growth_rate_cycle3_begin - revenue_growth_rate_cycle2_begin) / DURATION # DURATION is the number of years for valuation
  291.     intercept = revenue_growth_rate_cycle2_begin
  292.     length_of_cycle2 = (industry_average_revenue_growth_rate - intercept) / slope
  293.    
  294.     return length_of_cycle2
  295.  
  296.  
  297. def get_revenue_growth_rate_cycle3_begin(ticker, comparable_tickers):
  298.     """Compute the revenue growth rate for cycle 3 begin for a given ticker using yfinance."""
  299.    
  300.     # Get the revenue growth rate for cycle 2 end
  301.     revenue_growth_rate_cycle2_end = get_revenue_growth_rate_cycle2_end(ticker)
  302.     if not revenue_growth_rate_cycle2_end:
  303.         return None # No revenue data available[^1^][1]
  304.    
  305.     # Get the revenue growth rates for each comparable ticker
  306.     revenue_growth_rates = [get_revenue_growth_rate_cycle1_begin(ticker) for ticker in comparable_tickers]
  307.     revenue_growth_rates = [rate for rate in revenue_growth_rates if rate is not None] # Remove None values
  308.    
  309.     # Calculate the industry average revenue growth rate
  310.     industry_average_revenue_growth_rate = sum(revenue_growth_rates) / len(revenue_growth_rates)
  311.    
  312.     # Estimate the revenue growth rate for cycle 3 begin using a weighted average
  313.     omega = 0.5 # Weight given to the company's current revenue growth rate
  314.     revenue_growth_rate_cycle3_begin = omega * revenue_growth_rate_cycle2_end + (1 - omega) * industry_average_revenue_growth_rate
  315.    
  316.     return revenue_growth_rate_cycle3_begin
  317.  
  318. # Define the URL for the API endpoint
  319. TICKER = "AAPL"
  320. ENDPOINT = "https://query1.finance.yahoo.com/v7/finance/download/{}"
  321. TICKER_SP500 = "^GSPC"
  322. DURATION = 5
  323. TODAY = int(datetime.now().timestamp())
  324. TEN_YEARS_AGO = int((datetime.now() - pd.DateOffset(years=DURATION)).timestamp())
  325. urlRFR = "https://query1.finance.yahoo.com/v7/finance/download/%5ETNX?period1=0&period2=9999999999&interval=1d&events=history&includeAdjustedClose=true"
  326. headers = {
  327.     'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36'
  328. }
  329. responseRFR = requests.get(urlRFR, headers=headers)
  330.  
  331. if responseRFR.status_code == 200:
  332.     content = responseRFR.text
  333.     lines = content.strip().split("\n")
  334.    
  335.     if len(lines) < 2:  # Check if there's at least a header and one data line
  336.         print("Error: Not enough data lines in the response.")
  337.         exit()
  338.    
  339.     last_line = lines[-1]
  340.     values = last_line.split(",")
  341.    
  342.     if len(values) < 4:  # Check if there are enough values in the last line
  343.         print("Error: Not enough values in the data line.")
  344.         exit()
  345.  
  346.     RFR = float(values[3])
  347.     print(f"The 10-year treasury yield in USA is {RFR}%")
  348. else:
  349.     print(f"Error: The request failed with status code {responseRFR.status_code}. Response: {responseRFR.text}")
  350.  
  351.  
  352. # Fetch S&P 500 historical data
  353. urlSP500 = ENDPOINT.format(TICKER_SP500) + f"?period1={TEN_YEARS_AGO}&period2={TODAY}&interval=1d&events=history&includeAdjustedClose=true"
  354. responseSP500 = requests.get(urlSP500, headers=headers)
  355. if responseSP500.status_code != 200:
  356.     raise Exception("Error fetching S&P 500 data.")
  357. dataSP500 = pd.read_csv(urlSP500, parse_dates=['Date'], index_col='Date')
  358.  
  359. urlCOMPANY = ENDPOINT.format(TICKER) + f"?period1={TEN_YEARS_AGO}&period2={TODAY}&interval=1d&events=history&includeAdjustedClose=true"
  360. responseCOMPANY = requests.get(urlCOMPANY, headers=headers)
  361. if responseCOMPANY.status_code != 200:
  362.     raise Exception("Error fetching company data.")
  363. dataCOMPANY = pd.read_csv(io.StringIO(responseCOMPANY.text), parse_dates=['Date'], index_col='Date')
  364.  
  365. historical_beta = calculate_rolling_beta(dataCOMPANY, dataSP500, DURATION)
  366.  
  367. # Calculate annualized return for S&P 500 over the given duration
  368. initial_value = dataSP500['Adj Close'].iloc[0]
  369. final_value = dataSP500['Adj Close'].iloc[-1]
  370. Rm = ((final_value / initial_value) ** (1/DURATION) - 1)
  371. risk_free_rate = RFR/100
  372. ERP = Rm - risk_free_rate
  373. print(f"Equity Risk Premium: {ERP*100:.2f}%")
  374.  
  375. # Use yfinance to get the market capitalization
  376. stock = yf.Ticker(TICKER)
  377. market_cap = stock.info['marketCap'] / 10**9  # Convert to billions
  378.  
  379. equity_value = market_cap
  380. print(f"The equity value (market cap) of {TICKER} is approximately ${market_cap:.2f} billion.")
  381.  
  382. # Use yfinance to get the debt values
  383. long_term_debt = stock.balance_sheet.loc["Long Term Debt"][0] if "Long Term Debt" in stock.balance_sheet.index else 0
  384. short_term_debt = stock.balance_sheet.loc["Short Term Debt"][0] if "Short Term Debt" in stock.balance_sheet.index else 0
  385.  
  386. # Calculate total debt
  387. debt_value = (long_term_debt + short_term_debt) / 10**9  # Convert to billions
  388. print(f"The total debt of {TICKER} is approximately ${debt_value:.2f} billion.")
  389.  
  390. # Use yfinance to get the cash and non-operating asset values
  391. cash_and_cash_equivalents = stock.balance_sheet.loc["Cash And Cash Equivalents"][0] if "Cash And Cash Equivalents" in stock.balance_sheet.index else 0
  392. # Convert to billions
  393. cash_and_non_operating_asset = cash_and_cash_equivalents / 10**9
  394. print(f"Cash and non-operating assets of {TICKER} is approximately ${cash_and_non_operating_asset:.2f} billion.")
  395.  
  396.  
  397. df_result = get_stocks_from_same_industry(TICKER)
  398. comparable_tickers = df_result['symbol'].tolist()
  399.  
  400. print(comparable_tickers)
  401. # Get unlevered betas for each comparable
  402. unlevered_betas = [get_unlevered_beta(ticker) for ticker in comparable_tickers]
  403. unlevered_betas = [beta for beta in unlevered_betas if beta is not None]  # Remove None values
  404. # Calculate the industry average unlevered beta
  405. industry_average_unlevered_beta = sum(unlevered_betas) / len(unlevered_betas)
  406.  
  407. # Estimate the terminal_unlevered_beta
  408. omega = 0.5  # Weight given to the company's current unlevered beta
  409. unlevered_beta = get_unlevered_beta(TICKER)
  410. terminal_unlevered_beta = omega * unlevered_beta + (1 - omega) * industry_average_unlevered_beta
  411.  
  412. print(f"The estimated unlevered beta is: {unlevered_beta:.4f}")
  413. print(f"The estimated terminal unlevered beta is: {terminal_unlevered_beta:.4f}")
  414.  
  415. # Linear regression model
  416. X = np.array(range(len(historical_beta))).reshape(-1, 1)
  417. y = historical_beta.values
  418. model = LinearRegression().fit(X, y)
  419. slope = model.coef_
  420. intercept = model.intercept_
  421.  
  422. # Calculate the intersection point with terminal beta using the equation of the line
  423. # y = mx + c; terminal_beta = slope*x + intercept
  424. intersection_point = (terminal_unlevered_beta - intercept) / slope
  425.  
  426. # Convert intersection_point to years (assuming your historical data is daily)
  427. intersection_in_years = intersection_point[0]/365
  428.  
  429. print(f"Expected year to converge to terminal beta: {intersection_in_years:.2f} years")
  430.  
  431. year_beta_begins_to_converge_to_terminal_beta = intersection_in_years
  432.  
  433. # Calculate the effective tax rate
  434. income_statement = stock.financials
  435. pretax_income = float(income_statement.loc["Pretax Income"].iloc[0])
  436. income_tax_expense = float(income_statement.loc["Tax Provision"].iloc[0])
  437. tax_rate = income_tax_expense / pretax_income
  438.  
  439. print(f"Current Effective Tax Rate: {tax_rate:.2%}")
  440.  
  441. current_effective_tax_rate = tax_rate
  442.  
  443. current_pretax_cost_of_debt = get_pretax_cost_of_debt(TICKER)
  444.  
  445. print(f"Current Pretax Cost of Debt: {current_pretax_cost_of_debt:.2%}")
  446.  
  447. # Get pre-tax cost of debt for each comparable
  448. pretax_costs_of_debt = [get_pretax_cost_of_debt(ticker) for ticker in comparable_tickers]
  449. pretax_costs_of_debt = [cost for cost in pretax_costs_of_debt if cost is not None]
  450.  
  451. # Calculate the industry average pre-tax cost of debt
  452. industry_average_pretax_cost_of_debt = sum(pretax_costs_of_debt) / len(pretax_costs_of_debt)
  453.  
  454. # Estimate the terminal_pre_tax_cost_of_debt
  455. omega = 0.5  # Weight given to the company's current pre-tax cost of debt
  456. terminal_pretax_cost_of_debt = omega * current_pretax_cost_of_debt + (1 - omega) * industry_average_pretax_cost_of_debt
  457.  
  458. print(f"The estimated terminal pre-tax cost of debt is: {terminal_pretax_cost_of_debt:.2%}")
  459.  
  460. year_cost_of_debt_begins_to_converge_to_terminal_cost_of_debt = get_year_cost_of_debt_converges(TICKER, comparable_tickers)
  461.  
  462. print(f"Expected year to converge to the cost of debt: {year_cost_of_debt_begins_to_converge_to_terminal_cost_of_debt} years")
  463.  
  464. marginal_tax_rate = get_marginal_tax_rate(TICKER)
  465.  
  466. print(f"Current Marginal Tax Rate: {marginal_tax_rate:.2%}")
  467.  
  468. year_effective_tax_rate_begin_to_converge_marginal_tax_rate = 1
  469.  
  470. revenue_base = get_ttm_total_revenue(TICKER)
  471.  
  472. print(f"The total revenue of {TICKER} is approximately ${revenue_base}")
  473.  
  474. revenue_growth_rate_cycle1_begin = get_revenue_growth_rate_cycle1_begin(TICKER)
  475.  
  476. print(f"The growth rate of {TICKER} cycle 1 begin is approximately {revenue_growth_rate_cycle1_begin}")
  477.  
  478. revenue_growth_rate_cycle1_end = get_revenue_growth_rate_cycle1_end(TICKER)
  479.  
  480. print(f"The growth rate of {TICKER} cycle 1 end is approximately {revenue_growth_rate_cycle1_end}")
  481.  
  482. length_of_cylcle1 = get_length_of_cycle1(TICKER, comparable_tickers)
  483.  
  484. print(f"Expected lenght of cycle 1 {length_of_cylcle1} years")
  485.  
  486.  
  487. revenue_growth_rate_cycle2_begin = get_revenue_growth_rate_cycle2_begin(TICKER,comparable_tickers)
  488.  
  489. print(f"The growth rate of {TICKER} cycle 2 begin is approximately {revenue_growth_rate_cycle2_begin}")
  490.  
  491. revenue_growth_rate_cycle2_end = get_revenue_growth_rate_cycle2_end(TICKER)
  492.  
  493. print(f"The growth rate of {TICKER} cycle 2 end is approximately {revenue_growth_rate_cycle2_end}")
  494.  
  495. length_of_cylcle2 = get_length_of_cycle2(TICKER, comparable_tickers)
  496.  
  497. print(f"Expected lenght of cycle 2 {length_of_cylcle2} years")
  498.  
  499. base_case_valuation = valuator_multi_phase(
  500.             risk_free_rate,
  501.             ERP,
  502.             equity_value,
  503.             debt_value,
  504.             cash_and_non_operating_asset,
  505.             unlevered_beta,
  506.             terminal_unlevered_beta,
  507.             year_beta_begins_to_converge_to_terminal_beta,
  508.             current_pretax_cost_of_debt,
  509.             terminal_pretax_cost_of_debt,
  510.             year_cost_of_debt_begins_to_converge_to_terminal_cost_of_debt,
  511.             current_effective_tax_rate,
  512.             marginal_tax_rate,
  513.             year_effective_tax_rate_begin_to_converge_marginal_tax_rate,
  514.              revenue_base,
  515.              revenue_growth_rate_cycle1_begin,
  516.              revenue_growth_rate_cycle1_end,
  517.              length_of_cylcle1,
  518.              revenue_growth_rate_cycle2_begin,
  519.              revenue_growth_rate_cycle2_end,
  520.              length_of_cylcle2,
  521.              revenue_growth_rate_cycle3_begin,
  522.              revenue_growth_rate_cycle3_end,
  523.              length_of_cylcle3,
  524.             revenue_convergance_periods_cycle1= 1,
  525.             revenue_convergance_periods_cycle2=1,
  526.             revenue_convergance_periods_cycle3=1,
  527.             current_sales_to_capital_ratio = 1.7,
  528.             terminal_sales_to_capital_ratio = 1.3,
  529.             year_sales_to_capital_begins_to_converge_to_terminal_sales_to_capital = 1,
  530.             current_operating_margin = .15,
  531.             terminal_operating_margin = .175,
  532.             year_operating_margin_begins_to_converge_to_terminal_operating_margin = 1,
  533.             additional_return_on_cost_of_capital_in_perpetuity= 0.02,
  534.             asset_liquidation_during_negative_growth=0,
  535.             current_invested_capital = 6.062)
  536. point_estimate_describer(base_case_valuation)
  537.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement