use crate::{Context, Error, Outcome, Plugin, re};
use num_bigint::BigInt;
use num_rational::BigRational;
use num_traits::{One, Signed, ToPrimitive, Zero};
use std::cmp::Ordering;
pub(super) struct Definition {
basis: Option<f64>,
value: BigRational,
}
pub(super) struct ReportGoal {
pub balance: bool,
pub interest: bool,
pub loss: bool,
}
fn financial_coordinate(
input: &str,
ordinal: bool,
engine: &super::super::compositions::Compositions,
context: &Context,
) -> Result<super::super::model_coordinates::Coordinate, Error> {
let input = input.trim().to_ascii_lowercase();
let cardinal = if ordinal {
match input.as_str() {
"first" => "one",
"second" => "two",
"third" => "three",
"fourth" => "four",
"fifth" => "five",
"sixth" => "six",
"seventh" => "seven",
"eighth" => "eight",
"ninth" => "nine",
"tenth" => "ten",
_ => re!(r"^([0-9]+)(?:st|nd|rd|th)$")
.captures(&input)
.map(|c| c.get(1).unwrap().as_str())
.unwrap_or(&input),
}
} else {
&input
};
let normalized = super::super::language::Language::default()
.rewrite(cardinal, context)
.transpose()?
.unwrap_or_else(|| cardinal.into());
let period = super::super::model_coordinates::read(&normalized, "1", engine, context)?;
if period.value.is_negative() || ordinal && !period.value.is_integer() {
return Err(Error("invalid_duration".into()));
}
Ok(period)
}
fn financial_period(
input: &str,
ordinal: bool,
engine: &super::super::compositions::Compositions,
context: &Context,
) -> Result<BigRational, Error> {
financial_coordinate(input, ordinal, engine, context).map(|coordinate| coordinate.value)
}
fn finite_coordinate(value: &BigRational) -> Result<f64, Error> {
let coordinate = value
.to_f64()
.filter(|value| value.is_finite())
.ok_or_else(|| Error("numeric_overflow".into()))?;
if coordinate == 0.0 && !value.is_zero() {
return Err(Error("numeric_underflow".into()));
}
Ok(coordinate)
}
fn exact_monthly_balance(
opening: &BigRational,
fee: &BigRational,
factor: &BigRational,
months: &BigInt,
) -> Result<BigRational, Error> {
let bounded = super::super::model_coordinates::bounded;
if months.is_zero() {
return Ok(opening.clone());
}
if factor.is_zero() {
return Ok(BigRational::zero());
}
if factor.is_one() {
return bounded(opening - BigRational::from_integer(months.clone()) * fee);
}
let stationary = bounded(factor * fee / (factor - BigRational::one()))?;
let departure = bounded(opening - &stationary)?;
if departure.is_zero() {
return Ok(stationary);
}
let mut exponent = months.clone();
let mut power = factor.clone();
let mut product = BigRational::one();
while !exponent.is_zero() {
if (&exponent & BigInt::one()) == BigInt::one() {
product = bounded(product * &power)?;
}
exponent >>= 1;
if !exponent.is_zero() {
power = bounded(&power * &power)?;
}
}
bounded(stationary + bounded(departure * product)?)
}
fn periodic_log_factor(
percent: &str,
engine: &super::super::compositions::Compositions,
context: &Context,
) -> Result<f64, Error> {
let rate = super::super::model_coordinates::read(percent, "1", engine, context)?.value
/ BigRational::from_integer(100.into());
if rate <= -BigRational::one() {
return Err(Error("invalid_financial_rate".into()));
}
let factor = super::super::model_coordinates::bounded(BigRational::one() + &rate)?;
let factor = finite_coordinate(&factor)?;
Ok(if factor == 1.0 {
finite_coordinate(&rate)?.ln_1p()
} else {
factor.ln()
})
}
fn financial_list(input: &str) -> Result<Vec<String>, Error> {
let input = re!(r"(?i),?\s+and\s+").replace_all(input, ", ");
let mut rest = input.as_ref();
let mut fields = Vec::new();
while let Some((left, right)) = super::super::syntax::split_last(rest, &[","]) {
fields.push(right.trim().to_string());
if fields.len() >= 256 {
return Err(Error("expression_too_complex".into()));
}
rest = left;
}
fields.push(rest.trim().to_string());
if fields.iter().any(String::is_empty) {
return Err(Error("invalid_financial_argument".into()));
}
fields.reverse();
Ok(fields)
}
pub(super) fn annual_returns(input: &str, context: &Context) -> Outcome {
let input = input.trim().trim_end_matches(['.', '?']).replace('−', "-");
let c = re!(r"(?i)^a (?:fund|investment|account) starts (?:at|with) (.+?) and has annual returns (.+?)(?: in that order)?; report (.+?) over (.+?) years?$")
.captures(&input)?;
Some((|| {
if input.len() > 4096 {
return Err(Error("expression_too_complex".into()));
}
let engine = super::super::compositions::Compositions::default();
let (principal_exact, code) = super::nonnegative_money_coordinate(&c[1], &engine, context)?;
let rates = financial_list(&c[2])?;
let count = financial_period(&c[4], false, &engine, context)?;
if !count.is_integer()
|| count.is_zero()
|| count != BigRational::from_integer(rates.len().into())
{
return Err(Error("invalid_duration".into()));
}
let goals = financial_list(&c[3])?;
if goals.len() != 2 {
return Err(Error("invalid_financial_argument".into()));
}
let mut seen = Vec::new();
for goal in &goals {
let goal = goal.to_ascii_lowercase();
if !matches!(
goal.as_str(),
"ending value" | "geometric mean annual return"
) || seen.contains(&goal)
{
return Err(Error("invalid_financial_argument".into()));
}
seen.push(goal);
}
let bounded = super::super::model_coordinates::bounded;
let mut factors = Vec::new();
let mut authored = principal_exact.authored;
let mut positive_rates = Vec::new();
for rate in rates {
let c = re!(r"(?i)^(.+?)(?:%| percent)$")
.captures(&rate)
.ok_or_else(|| Error("invalid_financial_rate".into()))?;
let rate = super::super::model_coordinates::read(&c[1], "1", &engine, context)?;
authored &= rate.authored;
let factor =
bounded(BigRational::one() + rate.value / BigRational::from_integer(100.into()))?;
if factor.is_negative() {
return Err(Error("invalid_financial_rate".into()));
}
if !factor.is_zero() {
positive_rates.push(c[1].to_owned());
}
factors.push(factor);
}
let zero = factors.iter().any(Zero::is_zero);
let gross = if zero {
BigRational::zero()
} else {
factors
.into_iter()
.try_fold(BigRational::one(), |product, factor| {
bounded(product * factor)
})?
};
let ending = bounded(principal_exact.value * gross)?;
let ending = if authored {
format!("(rational({},{}) {code})", ending.numer(), ending.denom())
} else {
format!("(real({:e}) {code})", finite_coordinate(&ending)?)
};
let mean = if zero {
-1.0
} else {
let mut log_sum = BigRational::zero();
for rate in positive_rates {
let log = periodic_log_factor(&rate, &engine, context)?;
log_sum = bounded(
log_sum
+ BigRational::from_float(log)
.ok_or_else(|| Error("numeric_overflow".into()))?,
)?;
}
super::Growth {
principal: 1.0,
code,
annual_rate: 0.0,
years: 1.0,
frequency: 1.0,
goal: super::Goal::Interest,
}
.value_for_log_periods(finite_coordinate(&(log_sum / count))?, 1.0)?
};
engine.evaluate_money(&ending, context)?;
let fields = seen
.into_iter()
.map(|goal| match goal.as_str() {
"ending value" => format!("{goal}|{ending}"),
_ => format!("{goal}|real({mean:e})"),
})
.collect::<Vec<_>>();
let report = format!("finance_annual_report({})", fields.join(";"));
if report.len() > 4096 {
return Err(Error("expression_too_complex".into()));
}
Ok(report)
})())
}
fn discounted_receipts(
receipts: &[(super::Growth, BigRational)],
log_factor: f64,
) -> Result<BigRational, Error> {
let mut present_value = BigRational::zero();
for (receipt, authored) in receipts {
let value = if log_factor == 0.0 {
authored.clone()
} else {
let value =
BigRational::from_float(receipt.value_for_log_periods(log_factor, receipt.years)?)
.ok_or_else(|| Error("numeric_overflow".into()))?;
if authored.is_negative() {
-value
} else {
value
}
};
present_value = super::super::model_coordinates::bounded(present_value + value)?;
}
Ok(present_value)
}
fn cashflow_sign(
cost: &BigRational,
receipts: &[(super::Growth, BigRational)],
rate: f64,
) -> Result<Ordering, Error> {
Ok(discounted_receipts(receipts, rate.ln_1p())?.cmp(cost))
}
pub(super) fn cashflow_npv(input: &str, context: &Context) -> Outcome {
let input = input.trim().trim_end_matches(['.', '?']);
let c = re!(r"(?i)^for the (.+?) cash flows (.+?), (?:compute|calculate|find) NPV at an effective annual discount rate of (.+?)(?:%| percent) and report the sign$")
.captures(input)?;
Some((|| {
if input.len() > 4096 {
return Err(Error("expression_too_complex".into()));
}
let engine = super::super::compositions::Compositions::default();
let count = financial_period(&c[1], false, &engine, context)?;
let count = count
.to_integer()
.to_usize()
.filter(|_| count.is_integer())
.filter(|n| (1..=256).contains(n))
.ok_or_else(|| Error("invalid_financial_argument".into()))?;
let clauses = financial_list(&c[2])?;
if clauses.len() != count {
return Err(Error("invalid_financial_argument".into()));
}
let rate = super::super::model_coordinates::read(&c[3], "1", &engine, context)?;
let rate_value = &rate.value / BigRational::from_integer(100.into());
let factor = super::super::model_coordinates::bounded(BigRational::one() + &rate_value)?;
if factor <= BigRational::zero() {
return Err(Error("invalid_financial_rate".into()));
}
let mut authored = rate.authored;
let mut receipts = Vec::with_capacity(count);
let mut years = Vec::with_capacity(count);
let mut initial_count = 0;
for clause in clauses {
let c = re!(r"(?i)^(.+?) at (?:time (.+?)|(?:the )?end of year (.+?))$")
.captures(&clause)
.ok_or_else(|| Error("invalid_financial_argument".into()))?;
let amount = super::super::model_coordinates::read(&c[1], "1", &engine, context)?;
let year = financial_coordinate(
c.get(2).or_else(|| c.get(3)).unwrap().as_str(),
false,
&engine,
context,
)?;
if !year.value.is_integer()
|| c.get(2).is_some() && !year.value.is_zero()
|| c.get(3).is_some() && year.value.is_zero()
{
return Err(Error("invalid_duration".into()));
}
initial_count += usize::from(c.get(2).is_some());
authored &= amount.authored && year.authored;
let receipt = super::Growth {
principal: finite_coordinate(&amount.value.abs())?,
code: "",
annual_rate: 0.0,
years: finite_coordinate(&year.value)?,
frequency: 1.0,
goal: super::Goal::Principal,
};
receipt.validate()?;
receipts.push((receipt, amount.value));
years.push(year.value);
}
if initial_count != 1 {
return Err(Error("invalid_financial_argument".into()));
}
let value = if authored {
let mut sum = BigRational::zero();
for ((_, amount), year) in receipts.iter().zip(years) {
let value = if amount.is_zero() || factor.is_one() || year.is_zero() {
amount.clone()
} else {
let power = year
.to_integer()
.to_i32()
.ok_or_else(|| Error("integer_limit".into()))?;
let bits = factor.numer().bits().max(factor.denom().bits());
if bits * power as u64 > 65_536 {
return Err(Error("integer_limit".into()));
}
super::super::model_coordinates::bounded(amount / factor.pow(power))?
};
sum = super::super::model_coordinates::bounded(sum + value)?;
}
format!("rational({},{})", sum.numer(), sum.denom())
} else {
let sum =
discounted_receipts(&receipts, periodic_log_factor(&c[3], &engine, context)?)?;
format!("real({:e})", finite_coordinate(&sum)?)
};
let result = format!("finance_npv_report({value})");
if result.len() > 4096 {
return Err(Error("expression_too_complex".into()));
}
Ok(result)
})())
}
pub(super) fn cashflow_irr(input: &str, context: &Context) -> Outcome {
let input = input.trim().trim_end_matches(['.', '?']);
let c = re!(r"(?i)^a project costs (.+?) now and pays (.+?) at the ends of years (.+?); find the annual effective rate making net present value zero between (.+?) and (.+?) percent$")
.captures(input)?;
Some((|| {
if input.len() > 4096 {
return Err(Error("expression_too_complex".into()));
}
let engine = super::super::compositions::Compositions::default();
engine.evaluate_money(&c[1], context)?;
let (_, code) = super::signed_amount(&c[1])
.filter(|(value, code)| *value > 0.0 && !code.is_empty())
.ok_or_else(|| Error("invalid_financial_argument".into()))?;
let number = re!(r"(?i)[+-]?(?:\d[\d,]*(?:\.\d+)?|\.\d+)(?:e[+-]?\d+)?")
.find(&c[1])
.ok_or_else(|| Error("invalid_financial_argument".into()))?;
let cost =
super::super::model_coordinates::read(number.as_str(), "1", &engine, context)?.value;
let (values, receipt_code) = c[2]
.char_indices()
.filter_map(|(at, ch)| {
if !ch.is_whitespace() {
return None;
}
super::super::finance::currency(c[2][at..].trim())
.map(|code| (c[2][..at].trim(), code))
})
.next()
.ok_or_else(|| Error("invalid_financial_argument".into()))?;
if receipt_code != code {
return Err(Error("incompatible_units".into()));
}
let values = financial_list(values)?;
let years = financial_list(&c[3])?;
if values.len() != years.len() {
return Err(Error("invalid_financial_argument".into()));
}
let mut receipts = Vec::with_capacity(values.len());
for (amount, year) in values.iter().zip(years) {
let amount =
super::super::model_coordinates::read(amount, "1", &engine, context)?.value;
if amount.is_negative() {
return Err(Error("invalid_financial_argument".into()));
}
let year = financial_period(&year, false, &engine, context)?;
if year.is_zero() || !year.is_integer() {
return Err(Error("invalid_duration".into()));
}
let receipt = super::Growth {
principal: finite_coordinate(&amount)?,
code,
annual_rate: 0.0,
years: finite_coordinate(&year)?,
frequency: 1.0,
goal: super::Goal::Principal,
};
receipt.validate()?;
receipts.push((receipt, amount));
}
if receipts.iter().all(|(_, amount)| amount.is_zero()) {
return Err(Error("invalid_financial_argument".into()));
}
let hundred = BigRational::from_integer(100.into());
let left =
super::super::model_coordinates::read(&c[4], "1", &engine, context)?.value / &hundred;
let right =
super::super::model_coordinates::read(&c[5], "1", &engine, context)?.value / hundred;
if left.is_negative() || right <= left {
return Err(Error("invalid_financial_rate".into()));
}
let (mut left, mut right) = (finite_coordinate(&left)?, finite_coordinate(&right)?);
if right <= left {
return Err(Error("invalid_financial_rate".into()));
}
let lower = cashflow_sign(&cost, &receipts, left)?;
let upper = cashflow_sign(&cost, &receipts, right)?;
let rate = if lower == Ordering::Equal {
left
} else if upper == Ordering::Equal {
right
} else {
if lower != Ordering::Greater || upper != Ordering::Less {
return Err(Error("no_financial_solution".into()));
}
for _ in 0..2176 {
let middle = left + (right - left) * 0.5;
if middle == left || middle == right {
break;
}
match cashflow_sign(&cost, &receipts, middle)? {
Ordering::Greater => left = middle,
Ordering::Less => right = middle,
Ordering::Equal => {
left = middle;
right = middle;
break;
}
}
}
left + (right - left) * 0.5
};
Ok(format!("real({rate:e}) as percent"))
})())
}
pub(super) fn monthly_loan(input: &str, context: &Context) -> Outcome {
let input = input.trim().trim_end_matches(['.', '?']);
let c = re!(r"(?i)^a (.+?) loan is repaid by (.+?) equal end-of-month payments at (.+?)% monthly interest, first payment one month after origination; report the payment to the nearest cent$")
.captures(input)?;
Some((|| {
if input.len() > 4096 {
return Err(Error("expression_too_complex".into()));
}
let engine = super::super::compositions::Compositions::default();
let count = financial_period(&c[2], false, &engine, context)?;
if count.is_zero() || !count.is_integer() {
return Err(Error("invalid_duration".into()));
}
let periods = finite_coordinate(&count)?;
let log_factor = periodic_log_factor(&c[3], &engine, context)?;
engine.evaluate_money(&c[1], context)?;
let (principal, code) = super::signed_amount(&c[1])
.filter(|(_, code)| !code.is_empty())
.ok_or_else(|| Error("invalid_financial_argument".into()))?;
let growth = super::Growth {
principal,
code,
annual_rate: 0.0,
years: periods,
frequency: 1.0,
goal: super::Goal::Principal,
};
growth.validate()?;
let unit_present_value = super::Growth {
principal: 1.0,
..growth
}
.recurring_present_value(periods, log_factor)?;
let payment = principal / unit_present_value;
if !payment.is_finite() {
return Err(Error("numeric_overflow".into()));
}
if payment == 0.0 && principal != 0.0 {
return Err(Error("numeric_underflow".into()));
}
let expression = format!("({payment} {code})");
engine.evaluate_money(&expression, context)?;
Ok(expression)
})())
}
pub(super) fn coupon_bond(input: &str, context: &Context) -> Outcome {
let input = input.trim().trim_end_matches(['.', '?']);
let c = re!(r"(?i)^a bond pays (?:a )?(.+?) coupon every (.+?) months? for (.+?) years? and repays (.+?) with the final coupon; discount all cash flows at an effective (.+?)% per (.+?)[- ]month period to find price$")
.captures(input)?;
Some((|| {
if input.len() > 4096 {
return Err(Error("expression_too_complex".into()));
}
let engine = super::super::compositions::Compositions::default();
let interval = financial_period(&c[2], false, &engine, context)?;
let years = financial_period(&c[3], false, &engine, context)?;
let rate_interval = financial_period(&c[6], false, &engine, context)?;
if interval.is_zero() || years.is_zero() {
return Err(Error("invalid_duration".into()));
}
if rate_interval != interval {
return Err(Error("invalid_financial_rate".into()));
}
let count = super::super::model_coordinates::bounded(
years * BigRational::from_integer(12.into()) / interval,
)?;
if !count.is_integer() {
return Err(Error("invalid_duration".into()));
}
let periods = finite_coordinate(&count)?;
let log_factor = periodic_log_factor(&c[5], &engine, context)?;
let cashflow = |input: &str| -> Result<super::Growth, Error> {
let amount = if let Some((number, currency)) = input.rsplit_once('-')
&& super::super::finance::currency(currency).is_some()
&& super::super::integer_queries::ratio_value(number).is_ok()
{
format!("{number} {currency}")
} else {
input.to_string()
};
engine.evaluate_money(&amount, context)?;
let (principal, code) = super::signed_amount(&amount)
.filter(|(_, code)| !code.is_empty())
.ok_or_else(|| Error("invalid_financial_argument".into()))?;
let growth = super::Growth {
principal,
code,
annual_rate: 0.0,
years: periods,
frequency: 1.0,
goal: super::Goal::Principal,
};
growth.validate()?;
Ok(growth)
};
let coupon = cashflow(&c[1])?;
let redemption = cashflow(&c[4])?;
let expression = format!(
"(({} {}) + ({} {}))",
coupon.recurring_present_value(periods, log_factor)?,
coupon.code,
redemption.value_for_log_periods(log_factor, periods)?,
redemption.code,
);
engine.evaluate_money(&expression, context)?;
Ok(expression)
})())
}
pub(super) fn timed_deposits(input: &str, context: &Context) -> Outcome {
let input = input.trim().trim_end_matches(['.', '?']);
let c = re!(r"(?i)^if i (?:invest|deposit) (.+?) now and another (.+?) exactly (.+?) years? later, at (.+?)% annual compounding, what is the value immediately after the (.+?) year[’']s interest is applied$")
.captures(input)?;
Some((|| {
if input.len() > 4096 {
return Err(Error("expression_too_complex".into()));
}
let engine = super::super::compositions::Compositions::default();
let delay = financial_period(&c[3], false, &engine, context)?;
let horizon = financial_period(&c[5], true, &engine, context)?;
if delay > horizon {
return Err(Error("invalid_duration".into()));
}
let remaining = super::super::model_coordinates::bounded(&horizon - delay)?;
let annual = super::super::model_coordinates::read(&c[4], "1", &engine, context)?.value
/ BigRational::from_integer(100.into());
let annual_rate = finite_coordinate(&annual)?;
let balance = |amount: &str, years: &BigRational| -> Result<String, Error> {
engine.evaluate_money(amount, context)?;
let (principal, code) = super::signed_amount(amount)
.filter(|(_, code)| !code.is_empty())
.ok_or_else(|| Error("invalid_financial_argument".into()))?;
super::Growth {
principal,
code,
annual_rate,
years: finite_coordinate(years)?,
frequency: 1.0,
goal: super::Goal::Balance,
}
.literal()
};
let expression = format!(
"({} + {})",
balance(&c[1], &horizon)?,
balance(&c[2], &remaining)?
);
engine.evaluate_money(&expression, context)?;
Ok(expression)
})())
}
pub(super) fn monthly_account(input: &str, context: &Context) -> Outcome {
let input = input.trim().trim_end_matches(['.', '?']);
let c = re!(r"(?i)^an? account charges (?:a )?(.+?) monthly fee and earns (.+?)% monthly; starting with (.+?) and making (.+?) deposits at each month-end for (.+?) months?, (?:calculate|find) the closing balance after the last fee and deposit, with interest applied before fee and deposit each month$")
.captures(input)?;
Some((|| {
if input.len() > 4096 {
return Err(Error("expression_too_complex".into()));
}
let engine = super::super::compositions::Compositions::default();
let count = financial_period(&c[5], false, &engine, context)?;
if !count.is_integer() {
return Err(Error("invalid_duration".into()));
}
let periods = finite_coordinate(&count)?;
let rate = super::super::model_coordinates::read(&c[2], "1", &engine, context)?.value
/ BigRational::from_integer(100.into());
let monthly_rate = finite_coordinate(&rate)?;
let growth = |input: &str| -> Result<super::Growth, Error> {
engine.evaluate_money(input, context)?;
let (principal, code) = super::signed_amount(input)
.filter(|(_, code)| !code.is_empty())
.ok_or_else(|| Error("invalid_financial_argument".into()))?;
let growth = super::Growth {
principal,
code,
annual_rate: monthly_rate,
years: periods,
frequency: 1.0,
goal: super::Goal::Interest,
};
growth.validate()?;
Ok(growth)
};
let opening = growth(&c[3])?;
let fee = growth(&c[1])?;
let deposit = growth(&c[4])?;
let opening = super::Growth {
goal: super::Goal::Balance,
..opening
}
.literal()?;
let expression = format!(
"({opening} + ({} {}) - ({} {}))",
deposit.recurring_deposit_value(periods)?,
deposit.code,
fee.recurring_deposit_value(periods)?,
fee.code,
);
engine.evaluate_money(&expression, context)?;
Ok(expression)
})())
}
pub(super) fn one_month_interest_then_fee(input: &str, context: &Context) -> Outcome {
let input = input.trim().trim_end_matches(['.', '?']);
let c = re!(r"(?is)^compute the one-month ending amount from (.+?) at (.+?)% monthly interest when a (.+?) fee is deducted only after interest has been applied to the opening balance$")
.captures(input)?;
Some((|| {
if input.len() > 4096 {
return Err(Error("expression_too_complex".into()));
}
let engine = super::super::compositions::Compositions::default();
let (opening, code) = super::nonnegative_money_coordinate(&c[1], &engine, context)?;
let (fee, fee_code) = super::nonnegative_money_coordinate(&c[3], &engine, context)?;
let normalized_fee = super::normalize_grouped_money(&c[3])
.ok_or_else(|| Error("invalid_financial_argument".into()))?;
engine.quantity_value(&normalized_fee, code, context)?;
let fee = super::money_in_currency(fee.value, fee_code, code, context)?;
let rate = super::super::model_coordinates::read(&c[2], "1", &engine, context)?.value
/ BigRational::from_integer(100.into());
let gross = super::super::model_coordinates::bounded(BigRational::one() + rate)?;
if gross.is_negative() {
return Err(Error("invalid_financial_rate".into()));
}
let post_interest = super::super::model_coordinates::bounded(opening.value * gross)?;
if fee > post_interest {
return Err(Error("invalid_financial_argument".into()));
}
let ending = super::super::model_coordinates::bounded(post_interest - fee)?;
let expression = format!("(rational({},{}) {code})", ending.numer(), ending.denom());
engine.evaluate_money(&expression, context)?;
Ok(expression)
})())
}
pub(super) fn monthly_fee_before_interest(input: &str, context: &Context) -> Outcome {
let input = input.trim().trim_end_matches(['.', '?']);
let c = re!(r"(?is)^an? account charges (?:a )?(.+?) monthly fee and earns (.+?)% interest monthly on the balance after the fee\. starting at (.+?), what is the balance after (.+?) months?$")
.captures(input)?;
Some((|| {
if input.len() > 4096 {
return Err(Error("expression_too_complex".into()));
}
let engine = super::super::compositions::Compositions::default();
let count = financial_period(&c[4], false, &engine, context)?;
if !count.is_integer() {
return Err(Error("invalid_duration".into()));
}
let periods = finite_coordinate(&count)?;
if BigRational::from_float(periods).as_ref() != Some(&count) {
return Err(Error("integer_limit".into()));
}
let (opening_exact, code) = super::nonnegative_money_coordinate(&c[3], &engine, context)?;
let (fee_exact, fee_code) = super::nonnegative_money_coordinate(&c[1], &engine, context)?;
let normalized_fee = super::normalize_grouped_money(&c[1])
.ok_or_else(|| Error("invalid_financial_argument".into()))?;
engine.quantity_value(&normalized_fee, code, context)?;
let fee = super::money_in_currency(fee_exact.value, fee_code, code, context)?;
let rate = super::super::model_coordinates::read(&c[2], "1", &engine, context)?.value
/ BigRational::from_integer(100.into());
let gross = super::super::model_coordinates::bounded(BigRational::one() + &rate)?;
if gross.is_negative() {
return Err(Error("invalid_financial_rate".into()));
}
let months = count.to_integer();
if !months.is_zero() && opening_exact.value < fee {
return Err(Error("invalid_financial_argument".into()));
}
if months > BigInt::one()
&& exact_monthly_balance(
&opening_exact.value,
&fee,
&gross,
&(&months - BigInt::one()),
)? < fee
{
return Err(Error("invalid_financial_argument".into()));
}
let ending = exact_monthly_balance(&opening_exact.value, &fee, &gross, &months)?;
let expression = format!("(rational({},{}) {code})", ending.numer(), ending.denom());
engine.evaluate_money(&expression, context)?;
Ok(expression)
})())
}
pub(super) fn monthly_deposits(input: &str, context: &Context) -> Outcome {
let input = input.trim().trim_end_matches(['.', '?']);
let c = re!(r"(?i)^a (?:customer|person|saver) deposits (.+?) at the end of each month for (.+?) months? into an account earning (.+?)% nominal annual interest compounded monthly; (?:what is|find|calculate) (?:the )?accumulated value immediately after the last deposit$")
.captures(input)?;
Some((|| {
if input.len() > 4096 {
return Err(Error("expression_too_complex".into()));
}
let engine = super::super::compositions::Compositions::default();
engine.evaluate_money(&c[1], context)?;
let (principal, code) = super::signed_amount(&c[1])
.filter(|(_, code)| !code.is_empty())
.ok_or_else(|| Error("invalid_financial_argument".into()))?;
let periods = super::super::integer_queries::value(&c[2])?;
if periods <= BigInt::zero() {
return Err(Error("invalid_duration".into()));
}
let periods = periods
.to_f64()
.filter(|value| value.is_finite())
.ok_or_else(|| Error("numeric_overflow".into()))?;
let rate = super::super::model_coordinates::read(&c[3], "1", &engine, context)?;
let annual = rate.value / BigRational::from_integer(100.into());
let annual_rate = annual
.to_f64()
.filter(|value| value.is_finite())
.ok_or_else(|| Error("numeric_overflow".into()))?;
if annual_rate == 0.0 && !annual.is_zero() {
return Err(Error("numeric_underflow".into()));
}
let growth = super::Growth {
principal,
code,
annual_rate,
years: periods / 12.0,
frequency: 12.0,
goal: super::Goal::Interest,
};
let value = growth.recurring_deposit_value(periods)?;
Ok(format!("({value} {code})"))
})())
}
pub(super) fn simple_interest(input: &str, context: &Context) -> Outcome {
let input = input.trim().trim_end_matches(['.', '?']);
let c = re!(r"(?i)^a (.+?) (?:balance|principal|investment|account) earns (.+?)% simple annual interest for (.+?) (years?|months?); how much interest (?:accrues|is accrued|is earned)$")
.captures(input)?;
Some((|| {
if input.len() > 4096 {
return Err(Error("expression_too_complex".into()));
}
let engine = super::super::compositions::Compositions::default();
engine.evaluate_money(&c[1], context)?;
if engine.quantity_order(&c[1], &format!("0 * ({})", &c[1]), context)?
== std::cmp::Ordering::Less
{
return Err(Error("invalid_financial_argument".into()));
}
let rate = super::super::model_coordinates::read(&c[2], "1", &engine, context)?;
let duration = super::super::model_coordinates::read(&c[3], "1", &engine, context)?;
if rate.value.is_negative() {
return Err(Error("invalid_financial_rate".into()));
}
if duration.value.is_negative() {
return Err(Error("invalid_duration".into()));
}
let periods = if c[4].to_ascii_lowercase().starts_with("month") {
12
} else {
1
};
let factor = super::super::model_coordinates::bounded(
rate.value * duration.value / BigRational::from_integer((100 * periods).into()),
)?;
let factor = format!("rational({},{})", factor.numer(), factor.denom());
let factor = if rate.authored && duration.authored {
factor
} else {
format!("real({factor})")
};
let expression = format!("(({}) * {factor})", &c[1]);
if expression.len() > 4096 {
return Err(Error("expression_too_complex".into()));
}
engine.evaluate_money(&expression, context)?;
Ok(expression)
})())
}
struct SuppliedDayInterestRoles {
opening: String,
fees: Vec<(String, bool)>,
rate: String,
elapsed_days: String,
basis_days: String,
allow_negative: bool,
}
fn supplied_role_source(input: &str, mut spans: Vec<(usize, usize, &str)>) -> Option<String> {
if input.contains('\0') {
return None;
}
spans.sort_by_key(|span| span.0);
if spans.windows(2).any(|pair| pair[0].1 > pair[1].0) {
return None;
}
let mut source = input.to_owned();
for (start, end, role) in spans.into_iter().rev() {
source.replace_range(start..end, &format!(" \0{role}\0 "));
}
let source = re!(r"[,;.]").replace_all(&source, " ");
Some(
re!(r"\s+")
.replace_all(source.trim(), " ")
.to_ascii_lowercase(),
)
}
fn closed_supplied_day_shape(input: &str, spans: Vec<(usize, usize, &str)>) -> bool {
let Some(source) = supplied_role_source(input, spans) else {
return false;
};
let Some((prefix, after_rate)) = source.split_once(" \0r\0 ") else {
return false;
};
if !re!(r"^((?:calculate|compute) simple interest (?:on|for) \x00p\x00 at|find (?:the )?simple interest (?:on|earned by) \x00p\x00 at|a principal of \x00p\x00 earns simple annual interest at|a \x00p\x00 principal (?:earns|accrues) simple interest at|for (?:a )?\x00p\x00(?: principal)? at|on principal \x00p\x00 calculate simple interest at)$")
.is_match(prefix)
{
return false;
}
let Some(time) = re!(r"^(?:simple annual interest )?(?:(?:per year|per annum|yearly|annually) )?(?:\x00n\x00 )?(?:(?:use|using|under) (?:a |the )?\x00b\x00 (?:and|with|of) (?:exactly )?\x00d\x00|(?:over|for) \x00d\x00 (?:on|using) (?:a |the )?\x00b\x00) (.+)$")
.captures(after_rate)
else {
return false;
};
let Some(after_fee) = re!(r"^(?:(?:(?:then|afterward) )?(?:apply|deduct|charge|subtract) (?:a |an )?(?:\x00f\x00(?: after-interest)? fee|after-interest fee of \x00f\x00|\x00f\x00)(?: after (?:interest|accrual)| afterward)?|a \x00f\x00 fee is charged after accrual) (.+)$")
.captures(&time[1])
else {
return false;
};
let Some(permission) = after_fee[1].strip_suffix(" \0goals\0") else {
return false;
};
re!(r"^(?:and )?(?:(?:allow|permit|allowing) (?:a |the resulting )?(?:negative (?:post-fee |ending )?(?:balance|balances|result|remainder)|balance to be below zero)|with negative post-fee balances allowed|negative post-fee balances are (?:explicitly )?(?:allowed|permitted)|do not allow a negative post-fee balance)(?: and)?$")
.is_match(permission)
}
fn supplied_day_interest_roles(
input: &str,
context: &Context,
) -> Option<Result<SuppliedDayInterestRoles, Error>> {
if !re!(r"(?i)\bsimple\s+(?:annual\s+)?interest\b").is_match(input)
|| !re!(r"(?i)\bfee\b|\bcharge\b").is_match(input)
|| !input.contains('%')
|| !re!(r"(?i)\bdays?\b").is_match(input)
{
return None;
}
Some((|| {
let invalid = || Error("unsupported_financial_parameters".into());
let money = super::money_records().find_iter(input).collect::<Vec<_>>();
if money.len() != 2 {
return Err(invalid());
}
let rates = re!(r"(?i)([0-9][0-9,]*(?:\.[0-9]+)?(?:e[+-]?[0-9]+)?)%")
.captures_iter(input)
.collect::<Vec<_>>();
if rates.len() != 1
|| money[0].start() >= rates[0].get(0).unwrap().start()
|| money[1].start() <= rates[0].get(0).unwrap().end()
{
return Err(invalid());
}
let basis = re!(r"(?i)([0-9][0-9,]*(?:\.[0-9]+)?)\s*-\s*day\s+(?:basis|convention|year)\b|([0-9][0-9,]*(?:\.[0-9]+)?)\s+days\s+per\s+year\b")
.captures_iter(input)
.collect::<Vec<_>>();
if basis.len() != 1 {
return Err(invalid());
}
let basis_span = basis[0].get(0).unwrap();
let basis = basis[0]
.get(1)
.or_else(|| basis[0].get(2))
.unwrap()
.as_str();
let days = re!(r"(?i)([0-9][0-9,]*(?:\.[0-9]+)?)\s+(?:(?:elapsed|total)\s+)?days\b")
.captures_iter(input)
.filter(|c| {
let suffix = &input[c.get(0).unwrap().end()..];
!re!(r"(?i)^\s+per\s+year\b").is_match(suffix)
})
.collect::<Vec<_>>();
if days.len() != 1 {
return Err(invalid());
}
let nominal = re!(r"(?i)\b(?:for|over)\s+([0-9][0-9,]*(?:\.[0-9]+)?)\s+(months?|years?)\b")
.captures_iter(input)
.collect::<Vec<_>>();
if nominal.len() > 1 {
return Err(invalid());
}
if let Some(nominal) = nominal.first() {
let engine = super::super::compositions::Compositions::default();
let nominal = financial_period(&nominal[1], false, &engine, context)?;
let elapsed = financial_period(&days[0][1].replace(',', ""), false, &engine, context)?;
if nominal.is_zero() != elapsed.is_zero() {
return Err(Error("invalid_duration".into()));
}
}
let fee_after = re!(r"(?i)\b(?:after\s+(?:interest|accrual)|afterward|after-interest|then\s+(?:subtract|deduct))\b")
.is_match(input);
if !fee_after || re!(r"(?i)\b(?:before\s+interest|fee\s+first)\b").is_match(input) {
return Err(invalid());
}
let goal = re!(r"(?i)\b(?:return|report|provide|give|output|state)\b")
.find_iter(input)
.last()
.ok_or_else(invalid)?;
let goal_start = goal.start();
let goal = &input[goal.end()..];
if !re!(r"(?i)^\s*(?:the\s+)?interest\s*,?\s*(?:then|followed\s+by|and)\s+(?:(?:the|final|ending|remaining|post-fee)\s+)*(?:balance|amount|remainder)(?:\s+after\s+fee)?\s*$")
.is_match(goal)
{
return Err(invalid());
}
let denied = re!(r"(?i)\b(?:do\s+not|don't|never|not)\s+(?:allow|permit)\b|\bnegative\b[^.;]*\bnot\s+(?:allowed|permitted)\b")
.is_match(input);
let signed = !denied
&& re!(r"(?i)\b(?:allow|allowed|allowing|permit|permitted)\b").is_match(input)
&& re!(r"(?i)\bnegative\b|\bbelow\s+zero\b").is_match(input);
let mut spans = vec![
(money[0].start(), money[0].end(), "p"),
(money[1].start(), money[1].end(), "f"),
(
rates[0].get(0).unwrap().start(),
rates[0].get(0).unwrap().end(),
"r",
),
(basis_span.start(), basis_span.end(), "b"),
(
days[0].get(0).unwrap().start(),
days[0].get(0).unwrap().end(),
"d",
),
(goal_start, input.len(), "goals"),
];
if let Some(nominal) = nominal.first() {
let span = nominal.get(0).unwrap();
spans.push((span.start(), span.end(), "n"));
}
if !closed_supplied_day_shape(input, spans) {
return Err(invalid());
}
Ok(SuppliedDayInterestRoles {
opening: money[0].as_str().to_owned(),
fees: vec![(money[1].as_str().to_owned(), false)],
rate: rates[0][1].to_owned(),
elapsed_days: days[0][1].to_owned(),
basis_days: basis.to_owned(),
allow_negative: signed,
})
})())
}
fn supplied_two_fee_roles(input: &str) -> Option<Result<SuppliedDayInterestRoles, Error>> {
if !re!(r"(?i)\bsimple\s+(?:annual\s+)?interest\b").is_match(input)
|| !re!(r"(?i)\bbefore\s+(?:accrual|interest)\b").is_match(input)
|| !re!(r"(?i)\bafter\s+(?:accrual|interest)\b").is_match(input)
{
return None;
}
Some((|| {
let invalid = || Error("unsupported_financial_parameters".into());
let money = super::money_records().find_iter(input).collect::<Vec<_>>();
let rates = re!(r"(?i)([0-9][0-9,]*(?:\.[0-9]+)?(?:e[+-]?[0-9]+)?)%")
.captures_iter(input)
.collect::<Vec<_>>();
let days = re!(r"(?i)([0-9][0-9,]*(?:\.[0-9]+)?)\s+(?:(?:elapsed|total)\s+)?days\b")
.captures_iter(input)
.collect::<Vec<_>>();
let basis = re!(r"(?i)([0-9][0-9,]*(?:\.[0-9]+)?)\s*-\s*day\s+(?:basis|convention|year)\b|([0-9][0-9,]*(?:\.[0-9]+)?)\s+days\s+per\s+year\b")
.captures_iter(input)
.collect::<Vec<_>>();
let goal = re!(r"(?i)\b(?:give|report|return|provide|output|state)\b")
.find_iter(input)
.last()
.ok_or_else(invalid)?;
if money.len() != 3 || rates.len() != 1 || days.len() != 1 || basis.len() != 1 {
return Err(invalid());
}
let request = &input[goal.start()..];
if !re!(r"(?i)^(?:give|report|return|provide|output|state)\s+(?:the\s+)?interest\s+(?:and|then)\s+(?:the\s+)?(?:signed\s+)?(?:final|ending)\s+balance$")
.is_match(request)
{
return Err(invalid());
}
let rate = rates[0].get(0).unwrap();
let day = days[0].get(0).unwrap();
let basis_span = basis[0].get(0).unwrap();
let spans = vec![
(money[0].start(), money[0].end(), "p"),
(rate.start(), rate.end(), "r"),
(day.start(), day.end(), "d"),
(basis_span.start(), basis_span.end(), "b"),
(money[1].start(), money[1].end(), "f1"),
(money[2].start(), money[2].end(), "f2"),
(goal.start(), input.len(), "goals"),
];
let source = supplied_role_source(input, spans).ok_or_else(invalid)?;
if !re!(r"^for \x00p\x00 at \x00r\x00 simple annual interest (?:over|for) \x00d\x00 (?:on|using) (?:a |the )?\x00b\x00 (?:charge|subtract|deduct) \x00f1\x00 before (?:accrual|interest) and (?:another |then )?\x00f2\x00 after (?:accrual|interest) interest applies to the post-first-fee principal and \x00goals\x00$")
.is_match(&source)
{
return Err(invalid());
}
Ok(SuppliedDayInterestRoles {
opening: money[0].as_str().to_owned(),
fees: vec![
(money[1].as_str().to_owned(), true),
(money[2].as_str().to_owned(), false),
],
rate: rates[0][1].to_owned(),
elapsed_days: days[0][1].to_owned(),
basis_days: basis[0]
.get(1)
.or_else(|| basis[0].get(2))
.unwrap()
.as_str()
.to_owned(),
allow_negative: re!(r"(?i)\bsigned\s+(?:final|ending)\s+balance\b").is_match(request),
})
})())
}
pub(super) fn simple_interest_fee_report(input: &str, context: &Context) -> Outcome {
let input = input.trim().trim_end_matches(['.', '?']);
let fee_first = re!(r"(?i)^beginning with (.+?), subtract a (.+?) fee and then calculate (.+?)% simple interest for (.+?) days on the post-fee amount using a (.+?)-day year; report interest and closing balance to cents, half up$")
.captures(input)
.map(|c| (c[1].to_owned(), c[2].to_owned(), c[3].to_owned(), c[4].to_owned(), c[5].to_owned(), true, false, "days"));
let signed = re!(r"(?i)^for a (.+?) principal with a (.+?) fee charged first, then (.+?)% simple annual interest for (.+?) days on the resulting balance using a (.+?)-day year, give interest and ending amount rounded half up to cents, including any negative amount$")
.captures(input)
.map(|c| (c[1].to_owned(), c[2].to_owned(), c[3].to_owned(), c[4].to_owned(), c[5].to_owned(), true, true, "days"));
let interest_first = re!(r"(?i)^for a (.+?) balance, add (.+?)% simple interest for (.+?) days using a (.+?)-day year, then deduct a (.+?) fee; report the interest and final balance to cents with half-up rounding$")
.captures(input)
.map(|c| (c[1].to_owned(), c[5].to_owned(), c[2].to_owned(), c[3].to_owned(), c[4].to_owned(), false, false, "days"));
let monthly_interest_first = re!(r"(?i)^a (.+?) balance earns (.+?)% simple annual interest for (.+?) months; first compute and add interest, then subtract a (.+?) fee\. give interest and ending balance to the nearest cent, rounding half up$")
.captures(input)
.map(|c| (c[1].to_owned(), c[4].to_owned(), c[2].to_owned(), c[3].to_owned(), "12".to_owned(), false, false, "months"));
let roles = fee_first
.or(signed)
.or(interest_first)
.or(monthly_interest_first);
let (opening, fees, rate, days, year_days, allow_negative, period_unit) = match roles {
Some((opening, fee, rate, days, year_days, fee_before, allow_negative, unit)) => (
opening,
vec![(fee, fee_before)],
rate,
days,
year_days,
allow_negative,
unit,
),
None => match supplied_two_fee_roles(input)
.or_else(|| supplied_day_interest_roles(input, context))?
{
Ok(roles) => (
roles.opening,
roles.fees,
roles.rate,
roles.elapsed_days,
roles.basis_days,
roles.allow_negative,
"days",
),
Err(error) => return Some(Err(error)),
},
};
Some((|| {
if input.len() > 4096 {
return Err(Error("expression_too_complex".into()));
}
let bounded = super::super::model_coordinates::bounded;
let engine = super::super::compositions::Compositions::default();
let (opening, code) = super::nonnegative_money_coordinate(&opening, &engine, context)?;
let mut before = BigRational::zero();
let mut after = BigRational::zero();
for (fee_input, fee_before) in fees {
let (fee, fee_code) =
super::nonnegative_money_coordinate(&fee_input, &engine, context)?;
let normalized_fee = super::normalize_grouped_money(&fee_input)
.ok_or_else(|| Error("invalid_financial_argument".into()))?;
engine.quantity_value(&normalized_fee, code, context)?;
let fee = super::money_in_currency(fee.value, fee_code, code, context)?;
if fee_before {
before = bounded(before + fee)?;
} else {
after = bounded(after + fee)?;
}
}
let rate = super::super::model_coordinates::read(&rate, "1", &engine, context)?.value;
let days = super::super::model_coordinates::read(
&format!("{days} {period_unit}"),
period_unit,
&engine,
context,
)?
.value;
let year_days = super::super::model_coordinates::read(
&format!("{year_days} {period_unit}"),
period_unit,
&engine,
context,
)?
.value;
if rate.is_negative() {
return Err(Error("invalid_financial_rate".into()));
}
if days.is_negative() || !year_days.is_positive() {
return Err(Error("invalid_duration".into()));
}
let principal = bounded(&opening.value - before)?;
if principal.is_negative() && !allow_negative {
return Err(Error("invalid_financial_argument".into()));
}
let interest = bounded(
&principal * rate * days / bounded(BigRational::from_integer(100.into()) * year_days)?,
)?;
let ending = bounded(principal + &interest - after)?;
if ending.is_negative() && !allow_negative {
return Err(Error("invalid_financial_argument".into()));
}
let interest = super::round_money_to_cents(&interest)?;
let ending = super::round_money_to_cents(&ending)?;
let money = |amount: &BigRational| {
format!("(rational({},{}) {code})", amount.numer(), amount.denom())
};
let interest = money(&interest);
let ending = money(&ending);
engine.evaluate_money(&interest, context)?;
engine.evaluate_money(&ending, context)?;
Ok(format!(
"finance_annual_report(interest earned|{interest};ending balance|{ending})"
))
})())
}
fn balance_targets() -> &'static regex::Regex {
re!(
r"(?i)\b((?:resulting|ending|final) balance) (?:in|to|into) ([^,;.?]+?)(\s+and\s+|\s+using\s+|[,;.?]|$)"
)
}
pub(super) fn balance_interest_goals(input: &str) -> Result<Option<[super::Goal; 2]>, Error> {
let input = input.trim().trim_end_matches(['.', '?']);
if report_goal(input)?.is_some() {
return Ok(None);
}
let Some((_, request)) = super::super::syntax::split_last(input, &[";", ". "]) else {
return Ok(None);
};
let request = re!(r"(?i)^assume no (?:other )?transactions and ")
.replace(request.trim_start(), "")
.into_owned();
let request = balance_targets().replace_all(&request, "$1$3");
let request = if let Some(c) =
re!(r"(?i)^using nominal annual rate divided by (.+?), (.+), to cents$")
.captures(request.trim())
{
let (n, d) = super::super::integer_queries::ratio_value(&c[1])?;
let divisor = BigRational::new(n, d);
let frequencies = re!(
r"(?i)\bcompound(?:ed|ing|s)? (annually|yearly|monthly|quarterly|semiannually|weekly)\b"
)
.captures_iter(input)
.collect::<Vec<_>>();
if frequencies.len() != 1
|| divisor
!= BigRational::from_integer(BigInt::from(
super::frequency(&frequencies[0][1].to_ascii_lowercase()).unwrap() as u64,
))
{
return Err(Error("invalid_financial_rate".into()));
}
c[2].to_string()
} else {
request.into_owned()
};
if !re!(r"(?i)^\s*(?:calculate|compute|give|return|find|report|what (?:are|is))\b")
.is_match(&request)
|| !re!(r"(?i)\b(?:ending|final|resulting) balance\b").is_match(&request)
|| !re!(r"(?i)\b(?:interest (?:earned|accrued)|total interest)\b").is_match(&request)
{
return Ok(None);
}
let c = re!(r"(?i)^\s*(?:calculate|compute|give|return|find|report|what (?:are|is)) (?:the )?((?:ending|final|resulting) balance|interest (?:earned|accrued)|total interest(?: (?:earned|accrued))?)(?: to cents)? and (?:the )?((?:ending|final|resulting) balance|interest (?:earned|accrued)|total interest(?: (?:earned|accrued))?)(?: to cents)?\s*$")
.captures(&request)
.ok_or_else(|| Error("unsupported_financial_parameters".into()))?;
let goal = |role: &str| {
if role.to_ascii_lowercase().contains("interest") {
super::Goal::Interest
} else {
super::Goal::Balance
}
};
let first = goal(&c[1]);
let second = goal(&c[2]);
Ok(matches!(
(first, second),
(super::Goal::Balance, super::Goal::Interest)
| (super::Goal::Interest, super::Goal::Balance)
)
.then_some([first, second]))
}
pub(super) fn report_goal(input: &str) -> Result<Option<ReportGoal>, Error> {
let without_target = balance_targets().replace_all(input, "$1$3");
let goals = re!(
r"(?i)\b(?:calculate|compute|give|return|find|report|what (?:are|is))\s+((?:(?:the|its|percentage|cumulative|effective|period|total|ending|final|and|balance|yield|loss|interest|earned|accrued)\b\s*)+)"
);
let mut balance = balance_targets().is_match(input);
let mut interest = false;
let mut loss = false;
let mut yield_requested = false;
let mut incomplete_role = false;
for c in goals.captures_iter(&without_target) {
let goal = c[1].to_ascii_lowercase();
incomplete_role |= goal.trim_end().ends_with("and");
balance |= goal.contains("balance");
interest |= goal.contains("interest");
loss |= goal.contains("loss");
yield_requested |= re!(r"\b(?:yield|loss)\b").is_match(&goal);
}
if yield_requested && incomplete_role {
return Err(Error("unsupported_financial_parameters".into()));
}
Ok(yield_requested.then_some(ReportGoal {
balance,
interest,
loss,
}))
}
fn target_currency(input: &str, paired_goals: bool) -> Result<Option<&'static str>, Error> {
let mut target = None;
let goal_start = if paired_goals {
super::super::syntax::split_last(input, &[";", ". "])
.map(|(_, request)| input.len() - request.len())
} else {
None
};
for c in balance_targets().captures_iter(input) {
if goal_start.is_some_and(|start| c.get(0).unwrap().start() >= start)
&& c[2].trim().eq_ignore_ascii_case("cents")
{
continue;
}
let currency = super::super::finance::currency(c[2].trim())
.ok_or_else(|| Error("incompatible_units".into()))?;
if target.is_some_and(|old| old != currency) {
return Err(Error("unsupported_financial_parameters".into()));
}
target = Some(currency);
}
Ok(target)
}
pub(super) fn paired_report_target(input: &str) -> Result<Option<&'static str>, Error> {
target_currency(input, true)
}
pub(super) fn report_target(input: &str) -> Result<Option<&'static str>, Error> {
target_currency(input, false)
}
pub(super) fn validate_currency_records(input: &str, context: &Context) -> Result<(), Error> {
let records =
re!(r"(?i)\busing ([a-z]{3})\s*=\s*(.+?) and ([a-z]{3})\s*=\s*(.+?) per common base\b");
let engine = super::super::compositions::Compositions::default();
for c in records.captures_iter(input) {
for (code, value) in [(&c[1], &c[2]), (&c[3], &c[4])] {
super::super::finance::validate_supplied_rate(code, value, &engine, context)?;
}
}
if re!(r"(?i)\b(?:using\b.*)?[a-z]{3}\s*=").is_match(&records.replace_all(input, "")) {
return Err(Error("invalid_financial_rate".into()));
}
Ok(())
}
pub(super) fn has_definitions(input: &str) -> bool {
re!(r"(?i)\b(?:monthly|quarterly|semiannual(?:ly)?|weekly|annual|periodic)\s+(?:interest\s+)?(?:rate|factor)\s*(?:is|of|=)|\buse\s+(?:a\s+)?factor\b").is_match(input)
}
pub(super) fn prepare(input: &str) -> Result<(String, Vec<Definition>), Error> {
let input =
re!(r"(?i)\buse factor ([0-9eE.()+*/^ \t-]*[0-9)]) (monthly|quarterly|weekly|annually)\b")
.replace_all(input, "$2 factor = $1");
let calls = re!(
r"(?i)\b(?:use\s+(?:a\s+)?)?(monthly|quarterly|semiannual(?:ly)?|weekly|annual|periodic)\s+(?:interest\s+)?(rate|factor)\s*(?:is|of|=)\s*([0-9eE.()+*/^ \t-]*[0-9)])\s*(%)?"
);
let mut definitions = Vec::new();
let mut output = String::new();
let mut start = 0;
let primary_percentage = input.find('%');
for c in calls.captures_iter(&input) {
let span = c.get(0).unwrap();
let after = input[span.end()..].trim_start();
if after.starts_with(['+', '-', '*', '/', '^', ')']) {
return Err(Error("invalid_financial_rate".into()));
}
if !after.is_empty() && !after.starts_with(['.', ',', ';', '?', '!']) {
let word = after
.split_whitespace()
.next()
.unwrap()
.to_ascii_lowercase();
if !matches!(
word.as_str(),
"compound"
| "compounds"
| "compounded"
| "compounding"
| "per"
| "a"
| "every"
| "each"
| "monthly"
| "quarterly"
| "weekly"
| "annual"
| "annually"
| "yearly"
| "nominal"
| "effective"
| "interest"
| "for"
| "after"
| "over"
| "on"
| "and"
| "with"
| "give"
| "find"
| "calculate"
| "compute"
| "return"
| "what"
) {
return Err(Error("invalid_financial_rate".into()));
}
}
if c.get(4)
.is_some_and(|percent| Some(percent.start()) == primary_percentage)
{
continue;
}
let (n, d) = super::super::integer_queries::ratio_value(c[3].trim())?;
if n.bits().max(d.bits()) > 4096 || definitions.len() >= 8 {
return Err(Error("integer_limit".into()));
}
let mut value = BigRational::new(n, d);
if c.get(4).is_some() {
value /= BigInt::from(100);
}
if c[2].eq_ignore_ascii_case("factor") {
if c.get(4).is_some() {
return Err(Error("invalid_financial_rate".into()));
}
value -= BigRational::one();
}
let basis = if c[1].eq_ignore_ascii_case("periodic") {
None
} else {
super::frequency(&c[1].to_ascii_lowercase())
};
definitions.push(Definition { basis, value });
output.push_str(&input[start..span.start()]);
start = span.end();
}
output.push_str(&input[start..]);
if has_definitions(&calls.replace_all(&input, "")) {
return Err(Error("invalid_financial_rate".into()));
}
Ok((output, definitions))
}
pub(super) fn validate(
primary: &str,
rate_basis: f64,
frequency: f64,
effective: bool,
negative: bool,
definitions: &[Definition],
) -> Result<(), Error> {
if definitions.is_empty() {
return Ok(());
}
let (n, d) = super::super::integer_queries::ratio_value(primary)?;
let mut annual = BigRational::new(n, d * 100);
if negative {
annual = -annual.abs();
}
annual *= BigInt::from(rate_basis as i32);
for definition in definitions {
let basis = definition.basis.unwrap_or(frequency) as i32;
if effective {
let factor = BigRational::one() + &definition.value;
if factor < BigRational::zero()
|| factor.numer().bits().max(factor.denom().bits()) * basis as u64 > 65_536
{
return Err(Error("invalid_financial_rate".into()));
}
if factor.pow(basis) != BigRational::one() + &annual {
return Err(Error("invalid_financial_rate".into()));
}
} else if &definition.value * BigInt::from(basis) != annual {
return Err(Error("invalid_financial_rate".into()));
}
}
Ok(())
}
pub(super) fn primary_basis(prefix: &str, tail: &str) -> Option<f64> {
let noun = re!(
r"(?i)^\s*(?:interest\s+)?(?:per|a|every|each)\s+(month|quarter|week|half[ -]year|year)\b"
);
if let Some(c) = noun.captures(tail) {
return Some(match &c[1].to_ascii_lowercase()[..] {
"month" => 12.0,
"quarter" => 4.0,
"week" => 52.0,
"half year" | "half-year" => 2.0,
_ => 1.0,
});
}
let before = re!(
r"(?i)\b(monthly|quarterly|weekly|semiannual(?:ly)?|annual|annually|yearly)(?:\s+(?:interest|growth))?\s+rate\s*(?:of|at|is|=)?\s*$"
);
let after = re!(
r"(?i)^\s*(?:interest\s+)?(?:(?:nominal|effective)\s+)?(monthly|quarterly|weekly|semiannual(?:ly)?|annual|annually|yearly)\b"
);
before
.captures(prefix)
.or_else(|| after.captures(tail))
.and_then(|c| super::frequency(&c[1].to_ascii_lowercase()))
.or_else(|| {
re!(r"(?i)\bapy\s*(?:of|at|is|=)?\s*$")
.is_match(prefix)
.then_some(1.0)
})
}