thaler 0.1.0

The Thaler API: financial data from SEC filings, with the source filing for every value.
Documentation
//! The Screener's filters, written as clauses.
//!
//! A clause is `column:op:value` on the wire, where `op` is `gte`, `lte`,
//! `gt` or `lt` and `value` is a plain decimal, never in scientific
//! notation. [`Clause`] writes one from a column, an operator and a number:
//!
//! ```
//! use thaler::{Clause, Op, ScreenColumn};
//!
//! assert_eq!(Clause::new(ScreenColumn::Revenue, Op::Gte, 1_000_000_000).to_string(), "revenue:gte:1000000000");
//! assert_eq!(Clause::new(ScreenColumn::NetMargin, Op::Gt, 0.2).to_string(), "net_margin:gt:0.2");
//! ```
//!
//! [`ScreenRequest::filter`](crate::ScreenRequest::filter) takes a clause,
//! and [`ScreenRequest::where_`](crate::ScreenRequest::where_) one written
//! by hand.

use std::fmt;

use crate::decimal::Decimal;
use crate::types::ScreenColumn;

/// How a clause compares a column to its value.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Op {
    /// At least.
    Gte,
    /// At most.
    Lte,
    /// More than.
    Gt,
    /// Less than.
    Lt,
}

impl Op {
    /// The operator as the API spells it.
    pub fn as_str(self) -> &'static str {
        match self {
            Op::Gte => "gte",
            Op::Lte => "lte",
            Op::Gt => "gt",
            Op::Lt => "lt",
        }
    }
}

/// A number as the API takes it in a clause: digits, a sign and a
/// fraction, never an exponent.
pub trait ClauseValue {
    /// The number as a plain decimal.
    fn plain_decimal(&self) -> String;
}

macro_rules! whole {
    ($($t:ty),*) => { $(impl ClauseValue for $t { fn plain_decimal(&self) -> String { self.to_string() } })* };
}
whole!(
    i8, i16, i32, i64, i128, isize, u8, u16, u32, u64, u128, usize
);

impl ClauseValue for f64 {
    fn plain_decimal(&self) -> String {
        // Rust never writes an f64 with an exponent; it writes the shortest
        // digits that read back as the same number.
        format!("{self}")
    }
}

impl ClauseValue for f32 {
    fn plain_decimal(&self) -> String {
        format!("{self}")
    }
}

impl ClauseValue for Decimal {
    fn plain_decimal(&self) -> String {
        self.as_str().to_string()
    }
}

impl ClauseValue for &str {
    fn plain_decimal(&self) -> String {
        self.trim().to_string()
    }
}

impl ClauseValue for String {
    fn plain_decimal(&self) -> String {
        self.trim().to_string()
    }
}

#[cfg(feature = "rust_decimal")]
impl ClauseValue for rust_decimal::Decimal {
    fn plain_decimal(&self) -> String {
        self.normalize().to_string()
    }
}

/// A filter clause for the Screener: a column, an operator, a value.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Clause {
    column: ScreenColumn,
    op: Op,
    value: String,
}

impl Clause {
    /// A clause from a column, an operator and a number.
    pub fn new(column: ScreenColumn, op: Op, value: impl ClauseValue) -> Self {
        Clause {
            column,
            op,
            value: value.plain_decimal(),
        }
    }
}

impl fmt::Display for Clause {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "{}:{}:{}",
            self.column.as_str(),
            self.op.as_str(),
            self.value
        )
    }
}

impl From<Clause> for String {
    fn from(clause: Clause) -> Self {
        clause.to_string()
    }
}

/// Why the API would refuse a clause, or `None`: `column:op:value` with
/// `op` one of `gte`, `lte`, `gt`, `lt`, and `value` a plain decimal of at
/// most 32 characters, never with an exponent. It is what the API's own
/// parser checks, so a clause that passes is sent and one that fails is
/// not, which saves a counted request.
pub(crate) fn refused(clause: &str) -> Option<String> {
    let mut parts = clause.splitn(3, ':');
    let (Some(column), Some(op), Some(value)) = (parts.next(), parts.next(), parts.next()) else {
        return Some(format!(
            "the clause `{clause}` is not column:op:value, such as revenue:gte:1000000000"
        ));
    };
    if column.trim().is_empty() {
        return Some(format!("the clause `{clause}` names no column"));
    }
    if !matches!(op.trim(), "gte" | "lte" | "gt" | "lt") {
        return Some(format!(
            "the clause `{clause}` has the operator `{}`; it is gte, lte, gt or lt",
            op.trim()
        ));
    }
    let value = value.trim();
    if value.chars().count() > 32 {
        return Some(format!(
            "the clause `{clause}` has a value of more than 32 characters"
        ));
    }
    if !is_plain_decimal(value) {
        return Some(format!(
            "the clause `{clause}` has the value `{value}`; it is a plain decimal, never with an exponent"
        ));
    }
    None
}

/// Digits, a sign and a fraction, as the API's parser takes them: `5`,
/// `-5`, `+5`, `0.5`, `.5`, `5.`; never an exponent.
fn is_plain_decimal(value: &str) -> bool {
    let digits = value
        .strip_prefix('-')
        .or_else(|| value.strip_prefix('+'))
        .unwrap_or(value);
    let (whole, fraction) = match digits.split_once('.') {
        Some((whole, fraction)) => (whole, Some(fraction)),
        None => (digits, None),
    };
    let all_digits = |part: &str| part.bytes().all(|b| b.is_ascii_digit());
    let some_digit = !whole.is_empty() || fraction.is_some_and(|f| !f.is_empty());
    some_digit && all_digits(whole) && fraction.is_none_or(all_digits)
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn a_clause_the_api_would_refuse_is_named() {
        for clause in [
            "revenue:gte:1000000000",
            "net_margin:gt:0.2",
            "net_income:lt:-58000000",
            "fcf_margin:lte:.5",
            "fcf_margin:lte:+5",
            "fcf_margin:lte:5.",
            " revenue : gte : 1 ",
        ] {
            assert_eq!(refused(clause), None, "{clause}");
        }
        for clause in [
            "revenue",
            "revenue:gte",
            ":gte:1",
            "revenue:>=:1",
            "revenue:gte:1e9",
            "revenue:gte:5,000",
            "revenue:gte:",
            "revenue:gte:NaN",
            "revenue:gte:inf",
            "revenue:gte:123456789012345678901234567890123",
        ] {
            assert!(refused(clause).is_some(), "{clause}");
        }
        assert!(
            Clause::new(ScreenColumn::Revenue, Op::Gte, f64::NAN)
                .to_string()
                .contains("NaN")
        );
        assert!(
            refused(&Clause::new(ScreenColumn::Revenue, Op::Gte, f64::NAN).to_string()).is_some()
        );
    }

    #[test]
    fn clauses_are_written_as_the_api_takes_them() {
        assert_eq!(
            Clause::new(ScreenColumn::Revenue, Op::Gte, 1_000_000_000_i64).to_string(),
            "revenue:gte:1000000000"
        );
        assert_eq!(
            Clause::new(ScreenColumn::MarketCap, Op::Gte, 1e21).to_string(),
            "market_cap:gte:1000000000000000000000"
        );
        assert_eq!(
            Clause::new(ScreenColumn::FcfMargin, Op::Lte, 0.15).to_string(),
            "fcf_margin:lte:0.15"
        );
        assert_eq!(
            Clause::new(ScreenColumn::Pe, Op::Lt, 1e-7).to_string(),
            "pe:lt:0.0000001"
        );
        assert_eq!(
            Clause::new(
                ScreenColumn::NetIncome,
                Op::Gt,
                "-58000000".parse::<Decimal>().unwrap()
            )
            .to_string(),
            "net_income:gt:-58000000"
        );
        assert_eq!(
            Clause::new(ScreenColumn::Roe, Op::Gt, " 0.2 ").to_string(),
            "roe:gt:0.2"
        );
        let text: String = Clause::new(ScreenColumn::Ps, Op::Lte, 4_u8).into();
        assert_eq!(text, "ps:lte:4");
    }
}