use super::money;
use crate::{Context, Error, Outcome, Plugin, number, re};
use chrono::Datelike;
pub struct Finance;
fn words(s: &str) -> String {
let mut s = s.to_lowercase();
for (w, n) in [
("one", "1"),
("two", "2"),
("three", "3"),
("four", "4"),
("five", "5"),
("six", "6"),
("seven", "7"),
("eight", "8"),
("nine", "9"),
("ten", "10"),
] {
s = s
.split_whitespace()
.map(|t| if t == w { n } else { t })
.collect::<Vec<_>>()
.join(" ");
}
s
}
pub(super) fn currency(s: &str) -> Option<&'static str> {
match s.trim().to_lowercase().as_str() {
"aud" | "australian dollars" | "dollars" | "dollar" | "$" | "dollars aud" => Some("AUD"),
"usd" | "us dollars" | "us$" => Some("USD"),
"eur" | "euro" | "euros" | "€" => Some("EUR"),
"gbp" | "pounds" | "£" => Some("GBP"),
"jpy" | "yen" | "¥" => Some("JPY"),
"btc" | "₿" => Some("BTC"),
_ => None,
}
}
pub(super) fn validate_supplied_rate(
currency_name: &str,
input: &str,
engine: &super::compositions::Compositions,
context: &Context,
) -> Result<(), Error> {
let code = currency(currency_name).ok_or_else(|| Error("incompatible_units".into()))?;
let value = engine.quantity_value(input, "1", context)?;
let expected = context
.rates
.get(code)
.filter(|rate| rate.is_finite() && **rate > 0.0)
.ok_or_else(|| Error("invalid_financial_rate".into()))?;
if value <= 0.0
|| engine.quantity_order(input, &expected.to_string(), context)?
!= std::cmp::Ordering::Equal
{
return Err(Error("invalid_financial_rate".into()));
}
Ok(())
}
pub(crate) fn amount(s: &str) -> Option<(f64, &'static str)> {
let s = s.trim();
if let Some(code) = currency(s) {
return Some((1.0, code));
}
let c = re!(r"(?i)^([^\d+-.]*)([+-]?(?:\d[\d,]*(?:\.\d+)?|\.\d+)(?:e[+-]?\d+)?)(.*)$")
.captures(s)?;
let n = c[2].replace(',', "").parse::<f64>().ok()?;
let before = c[1].trim();
let after = c[3].trim();
if !before.is_empty() && currency(before).is_none() {
return None;
}
let code = if !after.is_empty() {
currency(after)?
} else if !before.is_empty() {
currency(before)?
} else {
""
};
Some((n, code))
}
fn years(n: f64, unit: &str) -> Option<f64> {
Some(match unit {
"year" | "years" => n,
"month" | "months" => n / 12.0,
"week" | "weeks" => n / 52.1775,
"day" | "days" => n / 365.2425,
"hour" | "hours" => n / 8765.82,
_ => return None,
})
}
pub(crate) fn compound_balance(
principal: f64,
annual_rate: f64,
years: f64,
frequency: f64,
) -> f64 {
principal * (1.0 + annual_rate / frequency).powf(years * frequency)
}
pub(crate) fn render(n: f64, code: &str) -> Outcome {
if !n.is_finite() {
None
} else {
Some(Ok(if code.is_empty() {
number(n)
} else {
money(n, code)
}))
}
}
impl Plugin for Finance {
fn evaluate(&self, input: &str, ctx: &Context) -> Outcome {
let s = words(input).replace("percent", "%");
if s.contains(" into ")
&& !s.starts_with("convert ")
&& re!(r"US\$|[$€£¥₿]|\b(?:aud|usd|eur|gbp|jpy|btc|dollars?|euros?|yen)\b").is_match(&s)
{
return Some(Err(Error("invalid_expression".into())));
}
if let Some((source, target)) = super::syntax::split_last(&s, super::syntax::CONVERSIONS)
&& currency(target).is_none()
&& super::units::Units::default().unit(target).is_some()
&& expression(source, ctx, 0).is_some_and(|(_, code)| !code.is_empty())
&& !super::units::Units::default().expression(source, 0).is_ok_and(|q| {
q.unit.dimension != [0; 8]
&& super::units::Units::default().unit(target)
.is_some_and(|unit| unit.dimension == q.unit.dimension)
})
{
return Some(Err(Error("internal_error".into())));
}
if let Some(lowered) = super::compositions::standard_grouped_comments(&s) {
if let Some(result) = super::calendar::Calendar.evaluate(&s, ctx) {
return Some(result);
}
return match lowered {
Ok(lowered) => self
.evaluate(&lowered, ctx)
.or_else(|| super::arithmetic::eval(&lowered).map(|value| Ok(number(value)))),
Err(error) => Some(Err(error)),
};
}
if let Some(c) = re!(r"^(.+) per (\w+) for (.+) in (.+)$").captures(&s) {
let (n, code) = amount(&c[1])?;
let target = currency(&c[4])?;
let units = super::units::Units::default();
let duration = units.quantity(&c[3])?;
let period = units.unit(&c[2])?;
if duration.unit.dimension != [0, 0, 1, 0, 0, 0, 0, 0]
|| period.dimension != duration.unit.dimension
|| code != target
{
return None;
}
return render(n * duration.base / period.scale, code);
}
if let Some(c) =
re!(r"^(.+) per (\w+) (?:as|in) (.+?) per (\w+)(?: at ([\d.]+) hours per (\w+))?$")
.captures(&s)
{
let (n, code) = amount(&c[1])?;
let target = currency(&c[3])?;
if code != target {
return None;
}
let units = super::units::Units::default();
let from = units.unit(&c[2])?;
let to = units.unit(&c[4])?;
if from.dimension != [0, 0, 1, 0, 0, 0, 0, 0] || to.dimension != from.dimension {
return None;
}
let n = n * to.scale / from.scale;
let (n, label) = if let Some(hours) = c.get(5) {
(n * hours.as_str().parse::<f64>().ok()?, c[6].to_string())
} else {
(n, c[4].to_string())
};
return Some(Ok(format!("{}/{}", money(n, code), label)));
}
if let Some(c) = re!(
r"^present value of (.+) (?:after|over) ([\d.]+) (years?|months?) at ([+-]?[\d.]+)%$"
)
.captures(&s)
{
let (p, code) = amount(&c[1])?;
return render(
p / (1.0 + c[4].parse::<f64>().ok()? / 100.0)
.powf(years(c[2].parse().ok()?, &c[3])?),
code,
);
}
if let Some(c)=re!(r"^(?:annual return on )?(.+) invested (.+) returned(?: (?:after|over) ([\d.]+) (years?|months?))?$").captures(&s){let(a,_)=amount(&c[1])?;let(b,_)=amount(&c[2])?;return if let Some(t)=c.get(3){Some(Ok(format!("{}%",number(((b/a).powf(1.0/years(t.as_str().parse().ok()?,&c[4])?)-1.0)*100.0))))}else{Some(Ok(format!("{}x",number(b/a-1.0))))};}
if let Some(c) =
re!(r"^investment required for (.+) per (month|year) at ([+-]?[\d.]+)%$").captures(&s)
{
let (value, code) = amount(&c[1])?;
if c[3].parse::<f64>().ok()? == 0.0 {
return Some(Ok("Error: ∞".into()));
}
return render(
value / years(1.0, &c[2])? / (c[3].parse::<f64>().ok()? / 100.0),
code,
);
}
if let Some(c) = re!(r"^(.+) per (.+) is what per (.+)$").captures(&s) {
let (value, code) = amount(&c[1])?;
if code.is_empty() {
return None;
}
let units = super::units::Units::default();
let a = units.unit(&c[2])?;
let b = units.unit(&c[3])?;
if a.dimension != b.dimension {
return None;
}
return Some(Ok(format!(
"{}/{}",
money(value * b.scale / a.scale, code),
b.symbol
)));
}
let loan = re!(
r"^(total|monthly|weekly|annual|quarterly) (interest (?:repayment )?|repayment )on (.+)$"
);
if let Some(c) = loan.captures(&s) {
let raw = &c[3];
let is_interest = c[2].starts_with("interest");
let compound = is_interest
&& !c[2].contains("repayment")
&& &c[1] != "total"
&& (raw.contains("compounding") || raw.find(" at ") < raw.find(" for "));
if !compound {
let parameters=re!(r"^(?:(.+) (?:for|over) ([\d.]+) (years?|months?) at ([+-]?[\d.]+)%|(.+) at ([+-]?[\d.]+)% (?:for|over) ([\d.]+) (years?|months?))$").captures(raw)?;
let (p, code, t, r) = if parameters.get(1).is_some() {
let (p, code) = amount(¶meters[1])?;
(
p,
code,
years(parameters[2].parse().ok()?, ¶meters[3])?,
parameters[4].parse::<f64>().ok()? / 1200.0,
)
} else {
let (p, code) = amount(¶meters[5])?;
(
p,
code,
years(parameters[7].parse().ok()?, ¶meters[8])?,
parameters[6].parse::<f64>().ok()? / 1200.0,
)
};
if r == 0.0 || t == 0.0 {
return Some(Err(Error("internal_error".into())));
}
let months = t * 12.0;
let payment = if r == 0.0 {
p / months
} else {
p * r / (1.0 - (1.0 + r).powf(-months))
};
let total = payment * months - if is_interest { p } else { 0.0 };
let frequency = match &c[1] {
"monthly" => 12.0,
"weekly" => 52.1775,
"quarterly" => 4.0,
_ => 1.0,
};
return render(
if &c[1] == "total" {
total
} else {
total / t / frequency
},
code,
);
}
}
if let Some(c)=re!(r"^(?:value of |purchasing power of |what will )(.+?)(?: be worth)? in (\d{4}) (?:assuming|at|with|given) ([+-]?[\d.]+)% inflation$").captures(&s){if c[3].starts_with("-0."){return None;}let(p,code)=amount(&c[1])?;let years=c[2].parse::<i32>().ok()?-ctx.now.with_timezone(&ctx.timezone).year();return render(p/(1.0+c[3].parse::<f64>().ok()?/100.0).powi(years),code);}
let pattern = re!(
r"^monthly repayment on (.+) (?:over|for) ([\d.]+) (years?|months?) at ([+-]?[\d.]+)\s*%$"
);
if let Some(c) = pattern.captures(&s) {
let (principal, code) = amount(&c[1])?;
let periods = years(c[2].parse().ok()?, &c[3])? * 12.0;
let rate = c[4].parse::<f64>().ok()? / 1200.0;
return render(principal * rate / (1.0 - (1.0 + rate).powf(-periods)), code);
}
let interest =
re!(r"^(?:(monthly|quarterly|annual|weekly) )?interest on (.+)$").captures(&s);
let comp_input = interest
.as_ref()
.map(|c| c.get(2).unwrap().as_str())
.unwrap_or(&s);
if let Some((mut result, code, principal)) = standard_compound(comp_input) {
if let Some(interest) = interest {
result -= principal;
result /= match interest.get(1).map(|m| m.as_str()) {
Some("monthly") => 12.0,
Some("quarterly") => 4.0,
Some("weekly") => 52.1775,
_ => 1.0,
};
}
return render(result, code);
}
let pattern = re!(
r"^([+-]?[\d.]+) hours? at (.+?)(?:/hour| per hour)(?: for ([+-]?[\d.]+) weeks?)?(?: in (.+))?$"
);
if let Some(c) = pattern.captures(&s) {
let hours = c[1].parse::<f64>().ok()?;
let (rate, code) = amount(&c[2])?;
let mut value = hours
* rate
* c.get(3)
.map(|m| m.as_str().parse::<f64>().ok())
.unwrap_or(Some(1.0))?;
let mut target = code;
if let Some(to) = c.get(4) {
target = currency(to.as_str())?;
value *= ctx.rates.get(target)? / ctx.rates.get(code)?;
}
return render(value, target);
}
if amount(&s).is_none()
&& let Some((value, code)) = expression(&s, ctx, 0)
&& (!code.is_empty()
|| re!(r"(?i)US\$|[$€£¥₿]|\b(?:AUD|USD|EUR|GBP|JPY|BTC|dollars?|euros?|yen)\b")
.is_match(&s))
{
return if value.is_finite() {
render(value, code)
} else {
Some(Err(Error("internal_error".into())))
};
}
let s = if let Some(rest) = s.strip_prefix("convert ") {
if !rest.contains(" into ") {
return None;
}
rest
} else {
s.as_str()
};
let parts: Vec<_> = re!(r" (?:to|in|into|as) ").split(s).collect();
if parts.len() < 2 {
return None;
}
if let Some(c) = re!(r"^([+-]?[\d.]+)% ([a-z]+)$").captures(parts[0]) {
currency(&c[2])?;
currency(parts[1])?;
return Some(Ok(format!("{}%", number(c[1].parse().ok()?))));
}
let (mut value, mut code) = amount(parts[0])?;
for target in &parts[1..] {
if let Some((n, to)) = amount(target).filter(|(_, c)| !c.is_empty())
&& currency(target).is_none()
{
value = n - value * ctx.rates.get(to)? / ctx.rates.get(code)?;
code = to;
continue;
}
let target = currency(target)?;
if code.is_empty() {
code = target;
} else if code != target {
value *= ctx.rates.get(target)? / ctx.rates.get(code)?;
code = target;
}
}
render(value, code)
}
}
pub(crate) fn expression(input: &str, ctx: &Context, depth: usize) -> Option<(f64, &'static str)> {
if depth > 64 {
return None;
}
let normalized = input
.replace(" plus ", " + ")
.replace(" minus ", " - ")
.replace(" divided by ", " / ")
.replace(" multiplied by ", " * ");
let s = normalized.trim();
let operators = super::arithmetic::operators(s)?;
if let Some((left, right)) = s.rsplit_once(" times ") {
return Some((
expression(left, ctx, depth + 1)?.0 * expression(right, ctx, depth + 1)?.0,
"",
));
}
let convert = |n: f64, from: &str, to: &str| -> Option<f64> {
if from.is_empty() || from == to {
Some(n)
} else {
Some(n / ctx.rates.get(from)? * ctx.rates.get(to)?)
}
};
for separator in [" to ", " in ", " into ", " as "] {
if let Some((left, right)) = s.rsplit_once(separator)
&& let Some(target) = currency(right)
{
let (n, code) = expression(left, ctx, depth + 1)?;
return Some((convert(n, code, target)?, target));
}
}
for level in ["+-", "*/"] {
if let Some(&(i, op)) = operators.iter().rev().find(|(_, op)| level.contains(*op)) {
let (a, ac) = expression(&s[..i], ctx, depth + 1)?;
let (b, bc) = expression(&s[i + 1..], ctx, depth + 1)?;
if matches!(op, '+' | '-') && s[i + 1..].trim().ends_with('%') {
return Some((a * (1.0 + if op == '+' { b } else { -b }), ac));
}
let code = if (op == '-' && !ac.is_empty()) || bc.is_empty() {
ac
} else {
bc
};
return Some(match op {
'+' => (convert(a, ac, code)? + convert(b, bc, code)?, code),
'-' => (convert(a, ac, code)? - convert(b, bc, code)?, code),
'*' => (a * b, code),
'/' if !ac.is_empty() && !bc.is_empty() => (convert(a, ac, bc)? / b, ""),
'/' => (a / b, code),
_ => unreachable!(),
});
}
}
if let Some(inner) = s.strip_prefix('(').and_then(|s| s.strip_suffix(')')) {
return expression(inner, ctx, depth + 1);
}
if let Some(rest) = s.strip_prefix('-') {
let (n, code) = expression(rest, ctx, depth + 1)?;
return Some((-n, code));
}
if let Some(c) = re!(r"^([+-]?[\d.]+)% (of|on|off) (.+)$").captures(s) {
let p = c[1].parse::<f64>().ok()?;
let (n, code) = expression(&c[3], ctx, depth + 1)?;
return Some((percentage_amount(n, p, &c[2]), code));
}
amount(s)
.or_else(|| Some((s.strip_suffix('%')?.trim().parse::<f64>().ok()? / 100.0, "")))
.or_else(|| super::arithmetic::eval(s).map(|n| (n, "")))
}
fn percentage_amount(amount: f64, percentage: f64, operation: &str) -> f64 {
let p = percentage / 100.0;
amount
* match operation {
"on" => 1.0 + p,
"off" => 1.0 - p,
_ => p,
}
}
pub(crate) fn standard_percentage_span(input: &str) -> Option<(f64, &'static str)> {
let c = re!(r"(?i)([+-]?[\d.]+)%\s+(of|on|off)\s+((?:us\$|[$€£¥₿])\s*[+-]?[\d,]+(?:\.\d+)?|[+-]?[\d,]+(?:\.\d+)?\s+(?:aud|usd|eur|gbp|jpy|btc|dollars?|euros?|pounds?|yen))").captures(input)?;
if c.get(0)?.as_str() == input.trim() {
return None;
}
let (amount, code) = amount(&c[3])?;
Some((
percentage_amount(amount, c[1].parse().ok()?, &c[2].to_lowercase()),
code,
))
}
pub(crate) fn standard_compound(input: &str) -> Option<(f64, &'static str, f64)> {
let comp = re!(
r"^(?:([\w$€£¥₿.,+\- ]+) at ([+-]?[\d.]+)\s*% (?:for|over) ([+-]?[\d.]+) (years?|months?|weeks?|days?|hours?)|([\w$€£¥₿.,+\- ]+) (?:over|for|after) ([+-]?[\d.]+) (years?|months?|weeks?|days?|hours?) at ([+-]?[\d.]+)\s*%)(?: compound(?:ed|ing) (yearly|monthly|quarterly|weekly|daily|hourly))?$"
);
let c = comp.captures(input)?;
let (a, rate, n, unit) = if c.get(1).is_some() {
(&c[1], &c[2], &c[3], &c[4])
} else {
(&c[5], &c[8], &c[6], &c[7])
};
let (principal, code) = amount(a)?;
let r = rate.parse::<f64>().ok()? / 100.0;
let t = years(n.parse().ok()?, unit)?;
let frequency = match c.get(9).map(|m| m.as_str()) {
Some("monthly") => 12.0,
Some("quarterly") => 4.0,
Some("weekly") => 52.1775,
Some("daily") => 365.2425,
Some("hourly") => 8765.82,
_ => 1.0,
};
let result = compound_balance(principal, r, t, frequency);
Some((result, code, principal))
}
pub(crate) fn standard_compound_span(input: &str) -> Option<(f64, &'static str)> {
let span = re!(r"(?i)(?:(?:us\$|[$€£¥₿])\s*[+-]?[\d,]+(?:\.\d+)?|[+-]?[\d,]+(?:\.\d+)?\s+(?:aud|usd|eur|gbp|jpy|btc|dollars?|euros?|pounds?|yen))\s+(?:at\s+[+-]?[\d.]+\s*%\s+(?:for|over)\s+[+-]?[\d.]+\s+(?:years?|months?|weeks?|days?|hours?)|(?:after|over|for)\s+[+-]?[\d.]+\s+(?:years?|months?|weeks?|days?|hours?)\s+at\s+[+-]?[\d.]+\s*%)(?:\s+compound(?:ed|ing)\s+(?:yearly|monthly|quarterly|weekly|daily|hourly))?").find(input)?;
standard_compound(span.as_str()).map(|(value, code, _)| (value, code))
}