use crate::mathx;
use crate::params::ModelParams;
use super::tick::TickCompany;
pub const DIVIDEND_PERIOD: i64 = 63;
pub const DECLARATION_LEAD: i64 = 21;
pub const PRICE_EMA_HALF_LIFE: f64 = 21.0;
#[derive(Debug, Clone, Copy, Default, PartialEq)]
#[non_exhaustive]
pub struct DividendState {
pub payout: f64,
pub target_yield: f64,
pub price_ema: f64,
pub amount: f64,
pub declared: bool,
pub accrual: f64,
pub paid_today: f64,
}
pub const STATE_WIDTH: usize = 7;
impl DividendState {
pub fn to_array(&self) -> [f64; STATE_WIDTH] {
[
self.payout,
self.target_yield,
self.price_ema,
self.amount,
if self.declared { 1.0 } else { 0.0 },
self.accrual,
self.paid_today,
]
}
pub fn from_slice(v: &[f64]) -> Option<Self> {
if v.len() != STATE_WIDTH || v.iter().any(|x| x.is_nan()) {
return None;
}
Some(Self {
payout: v[0],
target_yield: v[1],
price_ema: v[2],
amount: v[3],
declared: v[4] != 0.0,
accrual: v[5],
paid_today: v[6],
})
}
}
pub fn phase_for(ticker: &str) -> i64 {
let mut h: u64 = 0xcbf2_9ce4_8422_2325;
for b in ticker.as_bytes() {
h ^= u64::from(*b);
h = h.wrapping_mul(0x0100_0000_01b3);
}
(h % DIVIDEND_PERIOD as u64) as i64
}
pub fn sessions_since_ex(ticker: &str, day: i64) -> i64 {
(day - phase_for(ticker)).rem_euclid(DIVIDEND_PERIOD)
}
pub fn payout_for(p: &ModelParams, company: &TickCompany) -> f64 {
if p.dividend_payout_share == 0.0 {
return 0.0;
}
if !matches!(company.eps, Some(e) if e > 0.0 && e.is_finite()) {
return 0.0;
}
if company.revenue_growth.unwrap_or(0.0) >= p.dividend_growth_cutoff {
return 0.0;
}
let sector = match crate::sectors::by_key(&company.sector) {
Some(s) => s.dividend_payout,
None => return 0.0,
};
mathx::min(1.0, p.dividend_payout_share * sector)
}
pub fn buyback_share(p: &ModelParams, company: &TickCompany) -> f64 {
if p.dividend_payout_share == 0.0 || p.dividend_buyback_substitution == 0.0 {
return p.buyback_payout_share;
}
let payout = match company.stock.dividend {
Some(d) => d.payout,
None => payout_for(p, company),
};
mathx::max(0.0, p.buyback_payout_share - payout)
}
pub fn with_accrual(fv: f64, company: &TickCompany) -> f64 {
match company.stock.dividend {
Some(d) if d.accrual != 0.0 => fv + d.accrual,
_ => fv,
}
}
pub fn accrual(company: &TickCompany) -> f64 {
company.stock.dividend.map(|d| d.accrual).unwrap_or(0.0)
}
pub fn quarterly_speed(p: &ModelParams) -> f64 {
1.0 - mathx::pow(1.0 - p.dividend_adjustment_speed, 0.25)
}
pub fn ema_weight() -> f64 {
1.0 - mathx::pow(2.0, -1.0 / PRICE_EMA_HALF_LIFE)
}
pub fn declare(p: &ModelParams, state: &DividendState, close: f64) -> f64 {
let target = state.target_yield * state.price_ema / 4.0;
let next = mathx::max(0.0, state.amount + quarterly_speed(p) * (target - state.amount));
let ceiling = p.dividend_yield_ceiling * state.target_yield * mathx::max(close, 0.0) / 4.0;
mathx::min(next, ceiling)
}
pub fn new_state(p: &ModelParams, company: &TickCompany, price: f64) -> DividendState {
let payout = payout_for(p, company);
let target_yield = if payout > 0.0 && price > 0.0 && price.is_finite() {
payout * company.eps.unwrap_or(0.0) / price
} else {
0.0
};
DividendState {
payout,
target_yield,
price_ema: price,
amount: target_yield * price / 4.0,
declared: false,
accrual: 0.0,
paid_today: 0.0,
}
}
pub fn accrual_for(p: &ModelParams, state: &DividendState, close: f64, k: i64) -> f64 {
if k == 0 {
return 0.0;
}
let d = if state.declared { state.amount } else { declare(p, state, close) };
d * k as f64 / DIVIDEND_PERIOD as f64
}
#[derive(Debug, Clone, Copy, PartialEq)]
#[non_exhaustive]
pub struct Upcoming {
pub ex_day: i64,
pub amount: f64,
pub declared: bool,
}
pub fn lookahead(
p: &ModelParams,
ticker: &str,
state: Option<&DividendState>,
day: i64,
close: f64,
through_day: i64,
) -> Vec<Upcoming> {
let state = match state {
Some(s) if s.target_yield > 0.0 => *s,
_ => return Vec::new(),
};
let mut out = Vec::new();
let mut ex_day = day + DIVIDEND_PERIOD - sessions_since_ex(ticker, day);
let mut declared = state.declared;
let mut amount = if declared { state.amount } else { declare(p, &state, close) };
while ex_day <= through_day {
out.push(Upcoming { ex_day, amount, declared });
let next = DividendState { amount, ..state };
amount = declare(p, &next, close);
declared = false;
ex_day += DIVIDEND_PERIOD;
}
out
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn the_lookahead_reads_the_declared_amount_then_projects() {
let mut p = ModelParams::pt_v1();
p.dividend_payout_share = 1.0;
let ticker = "ACME";
let ph = phase_for(ticker);
let s = DividendState {
payout: 0.5,
target_yield: 0.02,
price_ema: 100.0,
amount: 0.3,
declared: true,
accrual: 0.0,
paid_today: 0.0,
};
let day = ph + 63 * 4 - 10;
let ahead = lookahead(&p, ticker, Some(&s), day, 100.0, day + 140);
assert_eq!(ahead.len(), 3);
assert_eq!(ahead[0], Upcoming { ex_day: day + 10, amount: 0.3, declared: true });
let second = declare(&p, &DividendState { amount: 0.3, ..s }, 100.0);
assert_eq!(ahead[1], Upcoming { ex_day: day + 73, amount: second, declared: false });
assert!(ahead[1].amount > 0.3 && ahead[2].amount > ahead[1].amount && ahead[2].amount < 0.5);
let early = DividendState { declared: false, ..s };
let day = ph + 63 * 4 - 40;
let ahead = lookahead(&p, ticker, Some(&early), day, 100.0, day + 40);
assert_eq!(ahead.len(), 1);
assert_eq!(ahead[0].amount, declare(&p, &early, 100.0));
assert!(!ahead[0].declared);
let day = ph + 63 * 4;
let ahead = lookahead(&p, ticker, Some(&early), day, 100.0, day + 63);
assert_eq!(ahead.len(), 1);
assert_eq!(ahead[0].ex_day, day + 63);
assert!(lookahead(&p, ticker, Some(&early), day, 100.0, day + 62).is_empty());
let none = DividendState { target_yield: 0.0, ..s };
assert!(lookahead(&p, ticker, Some(&none), day, 100.0, day + 500).is_empty());
assert!(lookahead(&p, ticker, None, day, 100.0, day + 500).is_empty());
}
#[test]
fn the_phase_is_in_range_and_follows_the_ticker() {
for t in ["AAPL", "MSFT", "KAT0", "KAT11", ""] {
let ph = phase_for(t);
assert!((0..DIVIDEND_PERIOD).contains(&ph));
assert_eq!(ph, phase_for(t));
}
assert_eq!(sessions_since_ex("AAPL", phase_for("AAPL")), 0);
assert_eq!(sessions_since_ex("AAPL", phase_for("AAPL") + 62), 62);
assert_eq!(sessions_since_ex("AAPL", phase_for("AAPL") - 1), 62);
}
#[test]
fn the_declaration_adjusts_partially_and_is_capped() {
let mut p = ModelParams::pt_v1();
p.dividend_payout_share = 1.0;
let s = DividendState {
payout: 0.5,
target_yield: 0.02,
price_ema: 100.0,
amount: 0.0,
declared: false,
accrual: 0.0,
paid_today: 0.0,
};
let d = declare(&p, &s, 100.0);
assert!((d - 0.5 * quarterly_speed(&p)).abs() < 1e-12);
let high = DividendState { amount: 0.5, ..s };
let d = declare(&p, &high, 10.0);
assert!((d - 2.0 * 0.02 * 10.0 / 4.0).abs() < 1e-12);
}
}