DCF Approximation
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © kulitam

//@version=5
indicator("DCF approximation")
// Set the forecast period (in years) and the margin of safety
period = 10
margin_of_safety = 0.2

// Get values for stock statistics
totalEquity = request.financial(syminfo.tickerid, "TOTAL_EQUITY", "FY")
totalDebt = request.financial(syminfo.tickerid, "TOTAL_DEBT", "FY")
totalOperExpense = request.financial(syminfo.tickerid, "TOTAL_OPER_EXPENSE", "FY")
capitExpenditues = request.financial(syminfo.tickerid, "CAPITAL_EXPENDITURES", "FY")
//free_fcf = request.financial(syminfo.tickerid, "FREE_CASH_FLOW", "FQ")

// Calculate the WACC using the following formula:
// WACC = (Weight of Equity * Cost of Equity + Weight of Debt * Cost of Debt) * (1 - Tax Rate)
weight_of_equity = totalEquity
cost_of_equity = 0.12
weight_of_debt = 0.4
cost_of_debt = totalDebt
tax_rate = 0.3
wacc = (weight_of_equity * cost_of_equity + weight_of_debt * cost_of_debt) * (1 - tax_rate)

// Calculate the discount rate by adding the margin of safety to the WACC
discount_rate = wacc + margin_of_safety

// Calculate the annual free cash flow (FCF) using the following formula:
// FCF = (Revenue - Operating Expenses - Capital Expenditures - Taxes) / (1 - Tax Rate)
revenue = close * volume
operating_expenses = totalOperExpense
capital_expenditures = capitExpenditues
annual_fcf = (revenue - operating_expenses - capital_expenditures) / (1 - tax_rate)

// Calculate the total discounted cash flow (DCF) by summing the discounted annual FCFs
dcf = 0.0
for i = 1 to period
    dcf := dcf + annual_fcf / math.pow((1 + discount_rate), i)

// Calculate the current price percentage relative to the DCF
price_percent = close / dcf
// Plot the DCF on the chart in different colors depending on the value of the current price percentage
plot(dcf, "DCF", color=price_percent > 1.10 ? color.green : price_percent < 0.90 ? color.red : color.orange, linewidth=2)


//Unused code - Previous versions
// 