Skip to main content

nfl_data/scoring/
mod.rs

1mod service;
2
3use crate::{PlayerWeekStats as NflPlayerWeekStats, TeamAbbr, TeamWeekStats as NflTeamWeekStats};
4use nfl_model::NflPlayerId;
5use std::collections::HashMap;
6
7pub use service::{SeasonAverages, season_averages, week_stats};
8
9#[derive(Debug, Clone, PartialEq)]
10pub struct ScoreLine {
11    pub stat: &'static str,
12    /// `None` for a threshold bonus, whose name already states the quantity.
13    pub quantity: Option<f64>,
14    pub points: f64,
15}
16
17impl ScoreLine {
18    /// `"2 RuTD"`, or just the stat name for a threshold bonus (`"100+ RuY Gm"`).
19    pub fn label(&self) -> String {
20        match self.quantity {
21            Some(q) => format!("{} {}", q as i64, self.stat),
22            None => self.stat.to_string(),
23        }
24    }
25    /// This line's points as `"12.00"`.
26    pub fn points_str(&self) -> String {
27        format_points(self.points)
28    }
29}
30
31#[derive(Debug, Clone, PartialEq, Default)]
32pub struct Score {
33    pub total: f64,
34    pub lines: Vec<ScoreLine>,
35}
36
37impl Score {
38    /// `"247 PaY, 2 PaTD, 300+ PaY Gm"` — one clause per scoring line, in
39    /// scoring order.
40    pub fn stat_line(&self) -> String {
41        self.lines
42            .iter()
43            .map(ScoreLine::label)
44            .collect::<Vec<_>>()
45            .join(", ")
46    }
47}
48
49/// Season-to-date FPPG
50#[derive(Debug, Clone, Copy, PartialEq, Default)]
51pub struct PointsPerGame {
52    pub avg_points: f64,
53    pub games_played: u8,
54}
55
56fn line(stat: &'static str, quantity: f64, points: f64) -> ScoreLine {
57    ScoreLine {
58        stat,
59        quantity: Some(quantity),
60        points,
61    }
62}
63
64fn threshold(stat: &'static str, points: f64) -> ScoreLine {
65    ScoreLine {
66        stat,
67        quantity: None,
68        points,
69    }
70}
71
72/// FanDuel points for one player's week (offense). Rules transcribed from
73/// fanduel-scraper/RECON.md.
74pub fn score_player(s: &NflPlayerWeekStats) -> Score {
75    let mut lines = Vec::new();
76    let mut push = |stat, qty: f64, per: f64| {
77        if qty != 0.0 {
78            lines.push(line(stat, qty, qty * per));
79        }
80    };
81    push("PaY", s.passing_yards as f64, 0.04);
82    push("PaTD", s.passing_tds as f64, 4.0);
83    push("I", s.passing_interceptions as f64, -1.0);
84    push("RuY", s.rushing_yards as f64, 0.1);
85    push("RuTD", s.rushing_tds as f64, 6.0);
86    push("Re", s.receptions as f64, 0.5);
87    push("ReY", s.receiving_yards as f64, 0.1);
88    push("ReTD", s.receiving_tds as f64, 6.0);
89    push("FU/L", s.fumbles_lost as f64, -2.0);
90    push("2PC", s.two_point_conversions as f64, 2.0);
91    push("KR/PR TD", s.special_teams_tds as f64, 6.0);
92    push("FU/TD", s.fumble_recovery_tds as f64, 6.0);
93    if s.passing_yards >= 300 {
94        lines.push(threshold("300+ PaY Gm", 3.0));
95    }
96    if s.rushing_yards >= 100 {
97        lines.push(threshold("100+ RuY Gm", 3.0));
98    }
99    if s.receiving_yards >= 100 {
100        lines.push(threshold("100+ ReY Gm", 3.0));
101    }
102    let total = lines.iter().map(|l| l.points).sum();
103    Score { total, lines }
104}
105
106/// FanDuel points-allowed tier from the defense's points-allowed count.
107/// Uses nfl-data's points_allowed (excludes non-defensive scoring).
108fn points_allowed_points(pa: i32) -> f64 {
109    match pa {
110        0 => 10.0,
111        1..=6 => 7.0,
112        7..=13 => 4.0,
113        14..=20 => 1.0,
114        21..=27 => 0.0,
115        28..=34 => -1.0,
116        _ => -4.0,
117    }
118}
119
120struct DefenseCounts {
121    sacks: u32,
122    interceptions: u32,
123    fumble_recoveries: u32,
124    touchdowns: u32,
125    safeties: u32,
126    blocked_kicks: u32,
127    conversion_returns: u32,
128}
129
130/// FanDuel points for one team defense's week. All inputs are pbp-derived, so
131/// every FanDuel DST category is covered.
132pub fn score_defense(t: &NflTeamWeekStats) -> Score {
133    defense_score(
134        DefenseCounts {
135            sacks: t.sacks,
136            interceptions: t.interceptions,
137            fumble_recoveries: t.fumble_recoveries,
138            touchdowns: t.touchdowns,
139            safeties: t.safeties,
140            blocked_kicks: t.blocked_kicks,
141            conversion_returns: t.conversion_returns,
142        },
143        Some(t.points_allowed),
144    )
145}
146
147/// Score observed live DST events without awarding a tier for unknown points allowed.
148pub fn score_live_defense(t: &nfl_model::live::LiveTeamStats) -> Score {
149    defense_score(
150        DefenseCounts {
151            sacks: t.sacks,
152            interceptions: t.interceptions,
153            fumble_recoveries: t.fumble_recoveries,
154            touchdowns: t.touchdowns,
155            safeties: t.safeties,
156            blocked_kicks: t.blocked_kicks,
157            conversion_returns: t.conversion_returns,
158        },
159        t.points_allowed,
160    )
161}
162
163fn defense_score(counts: DefenseCounts, points_allowed: Option<i32>) -> Score {
164    let mut lines = Vec::new();
165    let mut push = |stat, qty: f64, per: f64| {
166        if qty != 0.0 {
167            lines.push(line(stat, qty, qty * per));
168        }
169    };
170    push("S", counts.sacks as f64, 1.0);
171    push("I", counts.interceptions as f64, 2.0);
172    push("FR", counts.fumble_recoveries as f64, 2.0);
173    push("TD", counts.touchdowns as f64, 6.0);
174    push("DE/SF", counts.safeties as f64, 2.0);
175    push("DE/B", counts.blocked_kicks as f64, 2.0);
176    push("DE/XPR", counts.conversion_returns as f64, 2.0);
177    if let Some(pa) = points_allowed {
178        let pts = points_allowed_points(pa);
179        if pts != 0.0 {
180            lines.push(line("DE/PA", pa as f64, pts));
181        }
182    }
183    let total = lines.iter().map(|l| l.points).sum();
184    Score { total, lines }
185}
186
187/// One NFL week's stat lookups, typed. A `WeekStats` is week-scoped, so
188/// scoring needs no week parameter. The default is empty: nothing scores.
189#[derive(Default, Clone, Debug)]
190pub struct WeekStats {
191    pub players: HashMap<NflPlayerId, NflPlayerWeekStats>,
192    pub defenses: HashMap<TeamAbbr, NflTeamWeekStats>,
193}
194
195/// A score in whole hundredths — the precision at which the league reads a
196/// score, and so the precision at which two scores are the same score.
197fn hundredths(points: f64) -> i64 {
198    (points * 100.0).round() as i64
199}
200
201/// A score as the reader sees it: `1247.5` -> `"1,247.50"`.
202///
203/// Rounds to whole hundredths first, rather than `trunc`/`fract`, so `9.999`
204/// carries into the whole part instead of giving `"9.100"`, and a negative
205/// score keeps its sign.
206fn format_points(points: f64) -> String {
207    let hundredths = hundredths(points);
208    let sign = if hundredths < 0 { "-" } else { "" };
209    let hundredths = hundredths.unsigned_abs();
210    let whole = group_digits(&(hundredths / 100).to_string());
211    let frac = hundredths % 100;
212    format!("{sign}{whole}.{frac:02}")
213}
214
215/// `"1234567"` -> `"1,234,567"`.
216fn group_digits(digits: &str) -> String {
217    let mut out = String::new();
218    for (i, ch) in digits.char_indices() {
219        if i > 0 && (digits.len() - i).is_multiple_of(3) {
220            out.push(',');
221        }
222        out.push(ch);
223    }
224    out
225}
226
227#[cfg(test)]
228mod tests {
229    use super::*;
230    use crate::{Season, SeasonWeek, Week};
231    fn zero_player() -> NflPlayerWeekStats {
232        NflPlayerWeekStats {
233            season_week: SeasonWeek::new(Season(2025), Week(5)).expect("valid fixture"),
234            gsis_id: "00-1".into(),
235            team: TeamAbbr::SF,
236            opponent: None,
237            completions: 0,
238            attempts: 0,
239            passing_yards: 0,
240            passing_tds: 0,
241            passing_interceptions: 0,
242            rushing_attempts: 0,
243            rushing_yards: 0,
244            rushing_tds: 0,
245            targets: 0,
246            receptions: 0,
247            receiving_yards: 0,
248            receiving_tds: 0,
249            fumbles_lost: 0,
250            two_point_conversions: 0,
251            special_teams_tds: 0,
252            fumble_recovery_tds: 0,
253        }
254    }
255
256    #[test]
257    fn stat_line_renders_counted_stats_and_threshold_bonuses() {
258        let mut s = zero_player();
259        s.passing_yards = 325;
260        assert_eq!(score_player(&s).stat_line(), "325 PaY, 300+ PaY Gm");
261        let mut d = zero_defense();
262        d.points_allowed = 3;
263        assert_eq!(score_defense(&d).stat_line(), "3 DE/PA");
264    }
265
266    #[test]
267    fn qb_with_interception_and_bonus() {
268        let mut s = zero_player();
269        s.passing_yards = 325; // 13.0 + 3.0 bonus
270        s.passing_tds = 3; // 12.0
271        s.passing_interceptions = 1; // -1.0
272        let score = score_player(&s);
273        assert!((score.total - (13.0 + 3.0 + 12.0 - 1.0)).abs() < 1e-9);
274    }
275
276    #[test]
277    fn fumble_recovery_td_scores_six() {
278        // A skill player who recovers a fumble and scores (FanDuel FU/TD),
279        // like Woody Marks week 15: 30 rush yds, 1 rec / 8 yds, and the FU/TD.
280        let mut s = zero_player();
281        s.rushing_yards = 30; // 3.0
282        s.receptions = 1; // 0.5
283        s.receiving_yards = 8; // 0.8
284        s.fumble_recovery_tds = 1; // 6.0
285        let score = score_player(&s);
286        assert!((score.total - (3.0 + 0.5 + 0.8 + 6.0)).abs() < 1e-9);
287    }
288
289    #[test]
290    fn half_ppr_receptions() {
291        let mut s = zero_player();
292        s.receptions = 10; // 5.0
293        s.receiving_yards = 100; // 10.0 + 3.0 bonus
294        s.receiving_tds = 1; // 6.0
295        let score = score_player(&s);
296        assert!((score.total - (5.0 + 10.0 + 3.0 + 6.0)).abs() < 1e-9);
297    }
298
299    fn zero_defense() -> NflTeamWeekStats {
300        NflTeamWeekStats {
301            season_week: SeasonWeek::new(Season(2025), Week(5)).expect("valid fixture"),
302            team: TeamAbbr::SF,
303            opponent: TeamAbbr::LA,
304            game_id: "2025_05_SF_LA".into(),
305            sacks: 0,
306            interceptions: 0,
307            fumble_recoveries: 0,
308            safeties: 0,
309            touchdowns: 0,
310            blocked_kicks: 0,
311            conversion_returns: 0,
312            points_allowed: 10,
313        }
314    }
315    #[test]
316    fn defense_tier_boundaries() {
317        let mut t = zero_defense();
318        t.points_allowed = 6;
319        assert!((score_defense(&t).total - 7.0).abs() < 1e-9);
320        t.points_allowed = 7;
321        assert!((score_defense(&t).total - 4.0).abs() < 1e-9);
322        t.points_allowed = 0;
323        assert!((score_defense(&t).total - 10.0).abs() < 1e-9);
324    }
325
326    #[test]
327    fn defense_counts_every_category() {
328        let mut t = zero_defense();
329        t.points_allowed = 24; // 0 tier
330        t.sacks = 3; // 3
331        t.interceptions = 2; // 4
332        t.fumble_recoveries = 1; // 2
333        t.touchdowns = 1; // 6
334        t.safeties = 1; // 2
335        t.blocked_kicks = 1; // 2
336        t.conversion_returns = 1; // 2
337        assert!((score_defense(&t).total - 21.0).abs() < 1e-9);
338    }
339}