use super::finance::amount;
use crate::{Context, Error, ModelPosition, Outcome, Plugin, re};
use num_bigint::BigInt;
use num_integer::Integer;
use num_rational::BigRational;
use num_traits::Signed;
mod wording;
pub struct FinanceQueries;
#[derive(Clone, Copy)]
enum Goal {
Balance,
Interest,
Principal,
}
#[derive(Clone, Copy)]
struct Growth {
principal: f64,
code: &'static str,
annual_rate: f64,
years: f64,
frequency: f64,
goal: Goal,
}
impl Growth {
fn validate(&self) -> Result<(), Error> {
if !self.principal.is_finite() || self.principal < 0.0 {
return Err(Error("invalid_financial_argument".into()));
}
if !self.years.is_finite() || self.years < 0.0 {
return Err(Error("invalid_duration".into()));
}
if !self.frequency.is_finite() || self.frequency <= 0.0 || !self.annual_rate.is_finite() {
return Err(Error("invalid_financial_rate".into()));
}
let factor = 1.0 + self.annual_rate / self.frequency;
if factor < 0.0
|| (factor == 0.0 && matches!(self.goal, Goal::Principal) && self.years > 0.0)
{
return Err(Error("invalid_financial_rate".into()));
}
Ok(())
}
fn value(&self) -> Result<f64, Error> {
self.validate()?;
if self.principal == 0.0 {
return Ok(0.0);
}
if self.years == 0.0 || self.annual_rate == 0.0 {
return Ok(if matches!(self.goal, Goal::Interest) {
0.0
} else {
self.principal
});
}
let rate = self.annual_rate / self.frequency;
let exponent = if rate == 0.0 {
self.annual_rate * self.years
} else if rate.is_infinite() {
(self.annual_rate.ln() - self.frequency.ln()) * self.frequency * self.years
} else {
self.annual_rate * (rate.ln_1p() / rate) * self.years
};
let ordinary = rate.abs() >= 1e-6 && rate > -1.0 && rate.is_finite();
self.value_for_exponent(exponent, ordinary)
}
fn value_for_log_periods(&self, log_factor: f64, periods: f64) -> Result<f64, Error> {
self.validate()?;
if !log_factor.is_finite() {
return Err(Error("invalid_financial_rate".into()));
}
if !periods.is_finite() || periods < 0.0 {
return Err(Error("invalid_duration".into()));
}
if self.principal == 0.0 {
return Ok(0.0);
}
if periods == 0.0 || log_factor == 0.0 {
return Ok(if matches!(self.goal, Goal::Interest) {
0.0
} else {
self.principal
});
}
self.value_for_exponent(log_factor * periods, false)
}
fn value_for_exponent(&self, exponent: f64, ordinary: bool) -> Result<f64, Error> {
let logarithmic = |sign: f64| (self.principal.ln() + sign * exponent).exp();
let value = match self.goal {
Goal::Interest => {
let interest = self.principal * exponent.exp_m1();
if interest.is_finite() {
interest
} else {
logarithmic(1.0) - self.principal
}
}
Goal::Balance => {
let balance = if ordinary {
super::finance::compound_balance(
self.principal,
self.annual_rate,
self.years,
self.frequency,
)
} else {
self.principal * exponent.exp()
};
if balance.is_finite() && balance != 0.0 {
balance
} else {
logarithmic(1.0)
}
}
Goal::Principal => {
let factor = if ordinary {
super::finance::compound_balance(
1.0,
self.annual_rate,
self.years,
self.frequency,
)
} else {
exponent.exp()
};
if factor.is_finite() && factor > 0.0 {
self.principal / factor
} else {
logarithmic(-1.0)
}
}
};
if !value.is_finite() {
return Err(Error("numeric_overflow".into()));
}
Ok(value)
}
fn literal(&self) -> Result<String, Error> {
self.value().map(|value| format!("({value} {})", self.code))
}
fn recurring_deposit_value(&self, periods: f64) -> Result<f64, Error> {
self.recurring_value(periods, None)
}
fn recurring_value(&self, periods: f64, log_factor: Option<f64>) -> Result<f64, Error> {
self.validate()?;
if log_factor.is_some_and(|factor| !factor.is_finite()) {
return Err(Error("invalid_financial_rate".into()));
}
if periods == 0.0 {
return Ok(0.0);
}
let rate = log_factor.map_or_else(|| self.annual_rate / self.frequency, f64::exp_m1);
let value = if self.principal == 0.0 {
0.0
} else if rate == 0.0 || periods == 1.0 {
self.principal * periods
} else {
let (largest, sum_rate) = if let Some(log_factor) = log_factor {
if log_factor > 0.0 {
(
Growth {
goal: Goal::Balance,
..*self
}
.value_for_log_periods(log_factor, periods - 1.0)?,
(-log_factor).exp_m1(),
)
} else {
(self.principal, log_factor.exp_m1())
}
} else if rate > 0.0 {
(
Growth {
years: (periods - 1.0) / self.frequency,
goal: Goal::Balance,
..*self
}
.value()?,
-rate / (1.0 + rate),
)
} else {
(self.principal, rate)
};
let unit = Growth {
principal: 1.0,
annual_rate: sum_rate * self.frequency,
goal: Goal::Interest,
..*self
};
let increment = if let Some(log_factor) = log_factor {
let log_factor = if log_factor > 0.0 {
-log_factor
} else {
log_factor
};
Growth {
annual_rate: 0.0,
..unit
}
.value_for_log_periods(log_factor, periods)?
} else {
unit.value()?
};
largest * (increment / sum_rate)
};
if !value.is_finite() {
return Err(Error("numeric_overflow".into()));
}
if value == 0.0 && self.principal != 0.0 {
return Err(Error("numeric_underflow".into()));
}
Ok(value)
}
fn recurring_present_value(&self, periods: f64, log_factor: f64) -> Result<f64, Error> {
let first = Growth {
goal: Goal::Balance,
..*self
}
.value_for_log_periods(-log_factor, 1.0)?;
Growth {
principal: first,
goal: Goal::Interest,
..*self
}
.recurring_value(periods, Some(-log_factor))
}
}
fn frequency(word: &str) -> Option<f64> {
match word {
"annually" | "annual" | "yearly" => Some(1.0),
"quarterly" => Some(4.0),
"monthly" => Some(12.0),
"semiannual" | "semiannually" => Some(2.0),
"weekly" => Some(52.0),
_ => None,
}
}
fn normalize_grouped_money(input: &str) -> Option<String> {
let mut valid = true;
let input =
re!(r"[0-9]+(?:\s*,\s*[0-9]+)+").replace_all(input, |capture: ®ex::Captures<'_>| {
let number = &capture[0];
if !number.contains(char::is_whitespace) {
return number.to_string();
}
let compact = number.split_whitespace().collect::<String>();
valid &= re!(r"^[0-9]{1,3}(?:,[0-9]{3})+$").is_match(&compact);
compact
});
valid.then(|| input.into_owned())
}
fn signed_amount(input: &str) -> Option<(f64, &'static str)> {
let input = normalize_grouped_money(input)?;
let input = input.trim();
if let Some(rest) = input.strip_prefix('-') {
amount(rest).map(|(value, code)| (-value, code))
} else {
amount(input.strip_prefix('+').unwrap_or(input))
}
}
pub(super) fn nonnegative_money_coordinate(
input: &str,
engine: &super::compositions::Compositions,
context: &Context,
) -> Result<(super::model_coordinates::Coordinate, &'static str), Error> {
let normalized =
normalize_grouped_money(input).ok_or_else(|| Error("invalid_financial_argument".into()))?;
engine.evaluate_money(&normalized, context)?;
let (_, code) = signed_amount(&normalized)
.filter(|(amount, code)| amount.is_finite() && *amount >= 0.0 && !code.is_empty())
.ok_or_else(|| Error("invalid_financial_argument".into()))?;
let number = re!(r"[+-]?(?:\d[\d,]*(?:\.\d+)?|\.\d+)(?:[eE][+-]?\d+)?")
.find(&normalized)
.ok_or_else(|| Error("invalid_financial_argument".into()))?;
let coordinate =
super::model_coordinates::read(&number.as_str().replace(',', ""), "1", engine, context)?;
if coordinate.value.is_negative() {
return Err(Error("invalid_financial_argument".into()));
}
Ok((coordinate, code))
}
pub(super) fn money_in_currency(
amount: BigRational,
source: &str,
target: &str,
context: &Context,
) -> Result<BigRational, Error> {
if source == target {
return Ok(amount);
}
let quote = |code: &str| -> Result<BigRational, Error> {
let rate = context
.rates
.get(code)
.copied()
.filter(|rate| rate.is_finite() && *rate > 0.0)
.ok_or_else(|| Error("incompatible_units".into()))?;
BigRational::from_float(rate).ok_or_else(|| Error("incompatible_units".into()))
};
super::model_coordinates::bounded(amount * quote(target)? / quote(source)?)
}
pub(super) fn round_money_to_cents(value: &BigRational) -> Result<BigRational, Error> {
let hundred = BigRational::from_integer(BigInt::from(100));
let cents = super::model_coordinates::bounded(value.abs() * &hundred)?;
let (mut whole, remainder) = cents.numer().div_rem(cents.denom());
if remainder * 2u8 >= cents.denom().clone() {
whole += 1u8;
}
if value.is_negative() {
whole = -whole;
}
super::model_coordinates::bounded(BigRational::new(whole, BigInt::from(100)))
}
pub(super) fn money_records() -> &'static regex::Regex {
re!(
r"(?i)[+-]?\s*(?:us\$|[$€£¥₿])\s*[+-]?(?:\d(?:\s*,\s*|\d)*(?:\.\d+)?|\.\d+)(?:e[+-]?\d+)?(?:\s+(?:aud|usd|eur|gbp|jpy|btc)\b)?|[+-]?(?:\d(?:\s*,\s*|\d)*(?:\.\d+)?|\.\d+)\s+(?:aud|usd|eur|gbp|jpy|btc|dollars?|euros?|yen)\b"
)
}
fn story(input: &str, require_basis: bool) -> Option<Result<Growth, Error>> {
let s = input
.to_lowercase()
.replace('−', "-")
.replace("percent", "%");
if !re!(r"\b(?:compound(?:ed|ing|s)?|compounding|balance|principal|investment|account)\b")
.is_match(&s)
{
return None;
}
if re!(r"(?:monthly payments|monthly instalments|end-of-month payments|equal .*payments)")
.is_match(&s)
{
return None;
}
let (s, definitions) = match wording::prepare(&s) {
Ok(prepared) => prepared,
Err(error) => return Some(Err(error)),
};
let supported = s
.replace("no payments", "")
.replace("no repayments", "")
.replace("no other transactions", "")
.replace("no transactions", "");
if re!(r"\b(?:deposits?|contributions?|withdrawals?|fees?|tax|payments?|repayments?|transactions?)\b")
.is_match(&supported)
{
return Some(Err(Error("unsupported_financial_parameters".into())));
}
let money = money_records().find_iter(&s).collect::<Vec<_>>();
if money.len() != 1 {
return None;
}
let tail = s[money[0].end()..].trim_start();
if tail.starts_with(|ch: char| ch.is_ascii_digit())
&& !re!(r"(?i)^(?:\d+(?:\.\d+)?|\.\d+)(?:e[+-]?\d+)?\s*(?:%|(?:years?|months?|weeks?|quarters?|periods?)\b)")
.is_match(tail)
{
return Some(Err(Error("invalid_financial_argument".into())));
}
let (principal, code) = signed_amount(money[0].as_str())?;
let rates = re!(r"([+-]?(?:\d+(?:\.\d+)?|\.\d+)(?:e[+-]?\d+)?)\s*%")
.captures_iter(&s)
.collect::<Vec<_>>();
if rates.len() != 1 {
return None;
}
let mut annual_rate = rates[0][1].parse::<f64>().ok()? / 100.0;
let negative = re!(r"\b(?:loses|depreciates|declines)\b").is_match(&s);
if negative {
annual_rate = -annual_rate.abs();
}
let times = re!(r"(?:for|after|over)\s+(?:exactly\s+)?([+-]?(?:\d+(?:\.\d+)?|\.\d+)\s+(?:years?|months?|weeks?|quarters?|periods?)\b(?:\s*(?:and|,)\s*[+-]?(?:\d+(?:\.\d+)?|\.\d+)\s+(?:years?|months?|weeks?|quarters?|periods?)\b)*)")
.captures_iter(&s)
.collect::<Vec<_>>();
if times.len() != 1 {
return None;
}
if re!(r"\bsimple(?:\s+(?:annual|yearly|monthly|quarterly|weekly))?\s+interest\b").is_match(&s)
{
return Some(Err(Error("invalid_financial_argument".into())));
}
for c in re!(r"\bcompound(?:ed|ing|s)?\s+([a-z]+)").captures_iter(&s) {
if !matches!(
&c[1],
"annually"
| "yearly"
| "annual"
| "monthly"
| "quarterly"
| "semiannually"
| "weekly"
| "at"
| "for"
| "over"
| "interest"
| "on"
) {
return Some(Err(Error("unsupported_financial_frequency".into())));
}
}
let rate_end = rates[0].get(0)?.end();
let rate_tail = &s[rate_end..];
let rate_prefix = &s[..rates[0].get(0)?.start()];
let basis = wording::primary_basis(rate_prefix, rate_tail);
if require_basis && basis.is_none() {
return Some(Err(Error("invalid_financial_rate".into())));
}
let rate_frequency = basis.unwrap_or(1.0);
annual_rate *= rate_frequency;
let mut declared = Vec::new();
for c in re!(r"compound(?:ed|ing|s)?\s+((?:annually|yearly|monthly|quarterly|semiannually|weekly)(?:\s*(?:and|or|,)\s*(?:annually|yearly|monthly|quarterly|semiannually|weekly))*)|\b((?:annual|monthly|quarterly|semiannual|weekly)(?:\s*(?:and|or|,)\s*(?:annual|monthly|quarterly|semiannual|weekly))*)\s+compounding\b").captures_iter(&s) {
for word in re!(r"[a-z]+").find_iter(c.get(1).or_else(|| c.get(2))?.as_str()) {
if let Some(value) = frequency(word.as_str()) && !declared.contains(&value) { declared.push(value); }
}
}
if declared.len() > 1 {
return Some(Err(Error("invalid_financial_rate".into())));
}
let frequency = declared.first().copied().unwrap_or(rate_frequency);
let effective =
re!(r"\b(?:effective annual|annual effective|annual percentage yield|apy)\b").is_match(&s);
if effective {
if rate_frequency != 1.0
|| s.contains("nominal")
|| re!(r"\b(?:monthly|quarterly) (?:interest )?rate\b").is_match(&s)
|| annual_rate < -1.0
{
return Some(Err(Error("invalid_financial_rate".into())));
}
annual_rate = (annual_rate.ln_1p() / frequency).exp_m1() * frequency;
}
if let Err(error) = wording::validate(
&rates[0][1],
rate_frequency,
frequency,
effective,
negative,
&definitions,
) {
return Some(Err(error));
}
let mut years = 0.0;
for duration in
re!(r"([+-]?(?:\d+(?:\.\d+)?|\.\d+))\s+(years?|months?|weeks?|quarters?|periods?)\b")
.captures_iter(×[0][1])
{
let n = duration[1].parse::<f64>().ok()?;
if n < 0.0 {
return Some(Err(Error("invalid_duration".into())));
}
years += if duration[2].starts_with("month") {
n / 12.0
} else if duration[2].starts_with("week") {
n / 52.0
} else if duration[2].starts_with("quarter") {
n / 4.0
} else if duration[2].starts_with("period") {
n / frequency
} else {
n
};
}
let goal = if re!(r"\b(?:what principal|find (?:the )?principal|present value|initial (?:principal|investment))\b")
.is_match(&s)
{
Goal::Principal
} else if re!(r"\b(?:how much interest|interest (?:is )?(?:earned|accrued|accumulated)|(?:earned|accrued|accumulated) interest|compound interest earned)\b")
.is_match(&s)
{
Goal::Interest
} else {
Goal::Balance
};
let growth = Growth {
principal,
code,
annual_rate,
years,
frequency,
goal,
};
Some(growth.validate().map(|()| growth))
}
fn operation(input: &str) -> Option<Result<Growth, Error>> {
let inner = input.strip_prefix("finance_growth(")?.strip_suffix(')')?;
let parts = inner.split(',').map(str::trim).collect::<Vec<_>>();
let invalid = || Error("invalid_financial_argument".into());
if parts.len() != 6 {
return Some(Err(invalid()));
}
let growth = (|| {
Some(Growth {
principal: parts[0].parse().ok()?,
code: super::finance::currency(parts[1])?,
annual_rate: parts[2].parse::<f64>().ok()? / 100.0,
years: parts[3].parse().ok()?,
frequency: parts[4].parse().ok()?,
goal: match parts[5] {
"balance" => Goal::Balance,
"interest" => Goal::Interest,
"principal" => Goal::Principal,
_ => return None,
},
})
})();
Some(growth.ok_or_else(invalid))
}
fn balance_interest_request(input: &str, context: &Context) -> Outcome {
let input = super::syntax::ungroup(input);
let goals = match wording::balance_interest_goals(input) {
Ok(Some(goals)) => goals,
Ok(None) => return None,
Err(error) => return Some(Err(error)),
};
Some((|| {
if input.len() > 4096 {
return Err(Error("expression_too_complex".into()));
}
let target = wording::paired_report_target(input)?;
wording::validate_currency_records(input, context)?;
let growth = story(input, true).ok_or_else(|| Error("invalid_expression".into()))??;
Ok(format!(
"finance_balance_interest_report({};{};{};{};{})",
Growth {
goal: Goal::Balance,
..growth
}
.value()?,
Growth {
goal: Goal::Interest,
..growth
}
.value()?,
growth.code,
target.unwrap_or(growth.code),
if matches!(goals[0], Goal::Balance) {
"balance"
} else {
"interest"
}
))
})())
}
fn report_money(
engine: &super::compositions::Compositions,
value: f64,
code: &str,
target: &str,
context: &Context,
) -> Result<String, Error> {
engine.evaluate_money(&format!("({value} {code}) in {target}"), context)
}
fn period_request(input: &str, context: &Context) -> Outcome {
let input = super::syntax::ungroup(input);
let goal = match wording::report_goal(input) {
Ok(Some(goal)) => goal,
Ok(None) => return None,
Err(error) => return Some(Err(error)),
};
Some((|| {
let target = wording::report_target(input)?;
wording::validate_currency_records(input, context)?;
let statement = if money_records().is_match(input) {
input.to_string()
} else if !goal.balance && !goal.interest {
format!("{input}; ending balance on 1 AUD")
} else {
return Err(Error("invalid_expression".into()));
};
let growth =
story(&statement, true).ok_or_else(|| Error("invalid_expression".into()))??;
let mut yield_value = Growth {
principal: 1.0,
goal: Goal::Interest,
..growth
}
.value()?;
if goal.loss {
if yield_value > 0.0 {
return Err(Error("invalid_financial_argument".into()));
}
yield_value = -yield_value;
}
if goal.balance || goal.interest {
Ok(format!(
"finance_period_report({yield_value:e};{};{};{};{};{};{})",
Growth {
goal: Goal::Balance,
..growth
}
.value()?,
growth.code,
if goal.loss {
"period loss"
} else {
"effective period yield"
},
target.unwrap_or(growth.code),
u8::from(goal.balance),
if goal.interest {
Growth {
goal: Goal::Interest,
..growth
}
.value()?
.to_string()
} else {
String::new()
}
))
} else {
Ok(format!("real({yield_value:e}) as percent"))
}
})())
}
fn lower(input: &str, depth: usize, context: &Context) -> Option<Result<String, Error>> {
if let Some(result) = wording::annual_returns(input, context) {
return Some(result);
}
if let Some(result) = wording::cashflow_npv(input, context) {
return Some(result);
}
if let Some(result) = wording::cashflow_irr(input, context) {
return Some(result);
}
let complete_clause = re!(r"(?i)\b(?:after|for|over)\b").is_match(input)
&& re!(r"(?i)%|\bpercent\b").is_match(input);
if !input.contains("finance_growth(")
&& !re!(r"(?i)\bcompound(?:ed|ing|s)?\b").is_match(input)
&& !complete_clause
{
return None;
}
if depth > 64 {
return Some(Err(Error("expression_too_complex".into())));
}
if let Some(result) = wording::monthly_loan(input, context) {
return Some(result);
}
if let Some(result) = wording::coupon_bond(input, context) {
return Some(result);
}
if let Some(result) = wording::monthly_account(input, context) {
return Some(result);
}
if let Some(result) = wording::one_month_interest_then_fee(input, context) {
return Some(result);
}
if let Some(result) = wording::simple_interest_fee_report(input, context) {
return Some(result);
}
if let Some(result) = wording::monthly_fee_before_interest(input, context) {
return Some(result);
}
if let Some(result) = wording::timed_deposits(input, context) {
return Some(result);
}
if let Some(result) = wording::monthly_deposits(input, context) {
return Some(result);
}
if let Some(result) = wording::simple_interest(input, context) {
return Some(result);
}
if let Some(result) = balance_interest_request(input, context) {
return Some(result);
}
if let Some(result) = period_request(input, context) {
return Some(result);
}
if wording::has_definitions(input) {
return Some(
story(input, false)
.ok_or_else(|| Error("invalid_expression".into()))
.and_then(|growth| growth)
.and_then(|growth| growth.literal()),
);
}
let normalized = input
.trim()
.to_lowercase()
.replace('−', "-")
.replace("percent", "%");
if let Some((value, code, _)) = super::finance::standard_compound(&normalized) {
return Some(if value.is_finite() {
Ok(format!("({value} {code})"))
} else {
Err(Error("numeric_overflow".into()))
});
}
let calls = re!(r"\bfinance_growth\([^()]*\)");
if calls.is_match(input) {
let mut output = String::new();
let mut start = 0;
for call in calls.find_iter(input) {
let result = operation(call.as_str())?.and_then(|growth| growth.literal());
let value = match result {
Ok(value) => value,
Err(error) => return Some(Err(error)),
};
output.push_str(&input[start..call.start()]);
output.push_str(&value);
start = call.end();
}
output.push_str(&input[start..]);
return Some(Ok(output));
}
if let Some((left, _right)) = super::syntax::split_last(input, super::syntax::CONVERSIONS)
&& let Some(result) = lower(left, depth + 1, context)
{
let suffix = &input[left.len()..];
return Some(result.map(|value| format!("{value}{suffix}")));
}
if let Some(operators) = super::arithmetic::operators(input) {
for &(i, _) in operators.iter().rev() {
let left = lower(&input[..i], depth + 1, context);
let right = lower(&input[i + 1..], depth + 1, context);
if left.is_some() || right.is_some() {
let a = left.unwrap_or_else(|| Ok(input[..i].to_owned()));
let b = right.unwrap_or_else(|| Ok(input[i + 1..].to_owned()));
return Some(a.and_then(|a| b.map(|b| format!("{a} {} {b}", &input[i..i + 1]))));
}
}
}
let inner = super::syntax::ungroup(input);
if inner != input
&& let Some(result) = lower(inner, depth + 1, context)
{
return Some(result.map(|value| format!("({value})")));
}
story(input, false).map(|growth| growth.and_then(|growth| growth.literal()))
}
impl Plugin for FinanceQueries {
fn rewrite_call(&self, name: &str, arguments: &str, _: &Context, _: ModelPosition) -> Outcome {
if !name.eq_ignore_ascii_case("finance_growth") {
return None;
}
operation(&format!("finance_growth({arguments})"))
.map(|result| result.and_then(|growth| growth.literal()))
}
fn rewrite_model(&self, input: &str, context: &Context, _: ModelPosition) -> Outcome {
if super::business_queries::simple_interest_fee_request(input).is_some()
|| super::business_queries::fee_priority_request(input)
|| super::business_queries::priority_ledger_request(input).is_some()
|| super::business_queries::included_installment_request(input)
|| super::business_queries::staged_coupon_gift_request(input)
{
return None;
}
wording::annual_returns(input, context)
.or_else(|| wording::cashflow_npv(input, context))
.or_else(|| wording::cashflow_irr(input, context))
.or_else(|| wording::monthly_loan(input, context))
.or_else(|| wording::coupon_bond(input, context))
.or_else(|| wording::monthly_account(input, context))
.or_else(|| wording::one_month_interest_then_fee(input, context))
.or_else(|| wording::simple_interest_fee_report(input, context))
.or_else(|| wording::monthly_fee_before_interest(input, context))
.or_else(|| wording::timed_deposits(input, context))
.or_else(|| wording::monthly_deposits(input, context))
.or_else(|| wording::simple_interest(input, context))
.or_else(|| balance_interest_request(input, context))
.or_else(|| period_request(input, context))
.or_else(|| {
story(input, false).map(|result| result.and_then(|growth| growth.literal()))
})
}
fn rewrite(&self, input: &str, context: &Context) -> Outcome {
if super::business_queries::simple_interest_fee_request(input).is_some()
|| super::business_queries::fee_priority_request(input)
|| super::business_queries::priority_ledger_request(input).is_some()
|| super::business_queries::included_installment_request(input)
|| super::business_queries::staged_coupon_gift_request(input)
{
return None;
}
super::syntax::rewrite_groups(input, |part| lower(part, 0, context))
}
fn evaluate(&self, input: &str, context: &Context) -> Outcome {
let input = super::syntax::ungroup(input);
if let Some(inner) = input
.strip_prefix("finance_annual_report(")
.and_then(|rest| rest.strip_suffix(')'))
{
return Some((|| {
if input.len() > 4096 {
return Err(Error("expression_too_complex".into()));
}
let fields = inner.split(';').collect::<Vec<_>>();
if fields.len() != 2 {
return Err(Error("invalid_financial_argument".into()));
}
let engine = super::compositions::Compositions::default();
let mut seen = Vec::new();
let mut output = Vec::new();
for field in fields {
let (label, value) = field
.split_once('|')
.ok_or_else(|| Error("invalid_financial_argument".into()))?;
if seen.contains(&label) {
return Err(Error("invalid_financial_argument".into()));
}
seen.push(label);
let display = match label {
"ending value" | "interest earned" | "ending balance" => {
engine.evaluate_money(value, context)?
}
"geometric mean annual return" => {
let mean = engine.quantity_value(value, "1", context)?;
let percent = mean * 100.0;
if mean < -1.0 || !percent.is_finite() {
return Err(Error("invalid_financial_rate".into()));
}
format!("{}%", crate::number(percent))
}
_ => return Err(Error("invalid_financial_argument".into())),
};
output.push(format!("{label}: {display}"));
}
Ok(output.join("; "))
})());
}
if let Some(value) = input
.strip_prefix("finance_npv_report(")
.and_then(|rest| rest.strip_suffix(')'))
{
return Some((|| {
if input.len() > 4096 {
return Err(Error("expression_too_complex".into()));
}
let engine = super::compositions::Compositions::default();
let coordinate = engine.quantity_value(value, "1", context)?;
let ordering =
if let Ok((numerator, _)) = super::integer_queries::ratio_value(value) {
numerator.cmp(&0.into())
} else {
coordinate
.partial_cmp(&0.0)
.ok_or_else(|| Error("numeric_overflow".into()))?
};
let sign = match ordering {
std::cmp::Ordering::Less => "negative",
std::cmp::Ordering::Equal => "zero",
std::cmp::Ordering::Greater => "positive",
};
let display = engine
.evaluate(value, context)
.ok_or_else(|| Error("invalid_expression".into()))??;
Ok(format!("NPV: {display}; sign: {sign}"))
})());
}
if let Some(inner) = input
.strip_prefix("finance_balance_interest_report(")
.and_then(|rest| rest.strip_suffix(')'))
{
return Some((|| {
let invalid = || Error("invalid_financial_argument".into());
let fields = inner.split(';').collect::<Vec<_>>();
if fields.len() != 5 {
return Err(invalid());
}
let balance = fields[0].parse::<f64>().map_err(|_| invalid())?;
let interest = fields[1].parse::<f64>().map_err(|_| invalid())?;
let code = super::finance::currency(fields[2]).ok_or_else(invalid)?;
if !balance.is_finite() || balance < 0.0 || !interest.is_finite() {
return Err(invalid());
}
let engine = super::compositions::Compositions::default();
let balance = format!(
"ending balance: {}",
report_money(&engine, balance, code, fields[3], context)?
);
let interest = format!(
"interest earned: {}",
report_money(&engine, interest, code, fields[3], context)?
);
match fields[4] {
"balance" => Ok(format!("{balance}; {interest}")),
"interest" => Ok(format!("{interest}; {balance}")),
_ => Err(invalid()),
}
})());
}
let inner = input
.strip_prefix("finance_period_report(")?
.strip_suffix(')')?;
Some((|| {
let fields = inner.split(';').collect::<Vec<_>>();
if !matches!(fields.len(), 3 | 4 | 5 | 7) {
return Err(Error("invalid_financial_argument".into()));
}
let yield_value = fields[0]
.parse::<f64>()
.map_err(|_| Error("invalid_financial_argument".into()))?;
let balance = fields[1]
.parse::<f64>()
.map_err(|_| Error("invalid_financial_argument".into()))?;
let code = super::finance::currency(fields[2])
.ok_or_else(|| Error("invalid_financial_argument".into()))?;
let label = fields.get(3).copied().unwrap_or("effective period yield");
if !matches!(label, "effective period yield" | "period loss") {
return Err(Error("invalid_financial_argument".into()));
}
let percent = yield_value * 100.0;
if !percent.is_finite() || yield_value < -1.0 || !balance.is_finite() || balance < 0.0 {
return Err(Error("invalid_financial_argument".into()));
}
let target = fields.get(4).copied().unwrap_or(code);
let engine = super::compositions::Compositions::default();
let money = |value| report_money(&engine, value, code, target, context);
let mut output = vec![format!("{label}: {}%", crate::number(percent))];
match fields.get(5).copied().unwrap_or("1") {
"1" => output.push(format!("ending balance: {}", money(balance)?)),
"0" => {}
_ => return Err(Error("invalid_financial_argument".into())),
}
if let Some(field) = fields.get(6).filter(|value| !value.is_empty()) {
let interest = field
.parse::<f64>()
.map_err(|_| Error("invalid_financial_argument".into()))?;
if !interest.is_finite() {
return Err(Error("invalid_financial_argument".into()));
}
output.push(format!("interest earned: {}", money(interest)?));
}
Ok(output.join("; "))
})())
}
}