Dividend Yield
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © Ron_C

//@version=5
indicator("Dividend Yield")

//----- Inputs {

dividendSchedule = input.string("Annual", title="Dividend Payment Frequency",options=["Annual","Semi-Annual", "Quarterly", "Monthly"])
desiredYieldPercent = input.float(7.5, title="Desired Yield %", step=0.1)

//}

//----- Variables {

var dividendFrequency = 0
dividend = request.dividends(syminfo.tickerid)
var resultsTable = table.new(position = position.top_right, columns = 2, rows = 2)
var divFreqNum = int(na)
var annualIncome = float(na)
var annualYield = float(na)
//}

//----- Converting Percent into Decmial {

desiredYield = desiredYieldPercent/100

//}


//----- Determining Number Annual Dividends {

if dividendSchedule == "Annual"
    dividendFrequency := 1
else if dividendSchedule == "Semi-Annual"
    dividendFrequency := 2
else if dividendSchedule == "Quarterly"
    dividendFrequency := 4
else 
    dividendFrequency := 12
    
//}

//----- Determining Stock Price Required for Desired Yield {

stockPrice = dividend * dividendFrequency / desiredYield

//}

//----- Plot Stock Price {
  
plot(stockPrice, title="Required Price for Desired Yield")

//}

//-------- Determining Annual Yield {

annualIncome := dividend * dividendFrequency
annualYield := math.round((annualIncome / close) * 100, 2)
annualYieldString = str.tostring(annualYield)

//}

//-------- Display Results Table {

table.cell(resultsTable, column = 0, row = 0, text = "")
table.cell(resultsTable, column = 0, row = 1, bgcolor = color.white, text = "Current Yield")
table.cell(resultsTable, column = 1, row = 1, bgcolor = color.white, text = annualYieldString + "%")

//}

