Skip to main content

ferric_alpha/report/
summary.rs

1use std::collections::HashSet;
2
3use polars::prelude::DataFrame;
4use serde::de;
5use serde::ser::SerializeStruct;
6use serde::{Deserialize, Deserializer, Serialize, Serializer};
7
8use crate::calendar::Period;
9use crate::report::{
10    InformationReportData, InformationTearSheetOptions, ReportKind, ReportMetadata, ReportTable,
11    ReturnsReportData, ReturnsTearSheetOptions, TurnoverReportData, TurnoverTearSheetOptions,
12    create_information_tear_sheet_data, create_returns_tear_sheet_data,
13    create_turnover_tear_sheet_data, factor_quantile_statistics,
14};
15use crate::{FerricAlphaError, Result};
16
17#[derive(Debug, Clone, PartialEq, Eq)]
18pub struct SummaryTearSheetOptions {
19    pub long_short: bool,
20    pub group_neutral: bool,
21    pub turnover_periods: Option<Vec<Period>>,
22}
23
24#[derive(Debug, Clone, PartialEq, Eq)]
25pub struct FullTearSheetOptions {
26    pub long_short: bool,
27    pub group_neutral: bool,
28    pub by_group: bool,
29    pub turnover_periods: Option<Vec<Period>>,
30    pub ic_rolling_window: u32,
31}
32
33#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
34pub struct SummaryReportData {
35    pub quantile_statistics: ReportTable,
36    pub returns_summary: ReportTable,
37    pub returns_mean_by_quantile: ReportTable,
38    pub information_summary: ReportTable,
39    pub turnover_mean_by_quantile: ReportTable,
40    pub turnover_mean_rank_autocorrelation: ReportTable,
41}
42
43#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
44pub struct SummaryTearSheetData {
45    pub metadata: ReportMetadata,
46    pub options: SummaryTearSheetOptions,
47    pub data: SummaryReportData,
48}
49
50#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
51pub struct FullReportData {
52    pub quantile_statistics: ReportTable,
53    pub returns: ReturnsReportData,
54    pub information: InformationReportData,
55    pub turnover: TurnoverReportData,
56}
57
58#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
59pub struct FullTearSheetData {
60    pub metadata: ReportMetadata,
61    pub options: FullTearSheetOptions,
62    pub data: FullReportData,
63}
64
65impl Default for FullTearSheetOptions {
66    fn default() -> Self {
67        Self {
68            long_short: true,
69            group_neutral: false,
70            by_group: false,
71            turnover_periods: None,
72            ic_rolling_window: 22,
73        }
74    }
75}
76
77impl Default for SummaryTearSheetOptions {
78    fn default() -> Self {
79        Self {
80            long_short: true,
81            group_neutral: false,
82            turnover_periods: None,
83        }
84    }
85}
86
87pub fn create_summary_tear_sheet_data(
88    factor_data: &DataFrame,
89    options: SummaryTearSheetOptions,
90) -> Result<SummaryTearSheetData> {
91    let metadata = ReportMetadata::from_factor_data(factor_data, ReportKind::Summary)?;
92    let quantile_statistics = factor_quantile_statistics(factor_data)?;
93    let returns = create_returns_tear_sheet_data(factor_data, options.returns_options())?;
94    let information =
95        create_information_tear_sheet_data(factor_data, options.information_options())?;
96    let turnover = create_turnover_tear_sheet_data(factor_data, options.turnover_options())?;
97
98    Ok(SummaryTearSheetData {
99        metadata,
100        options,
101        data: SummaryReportData {
102            quantile_statistics,
103            returns_summary: returns.data.summary,
104            returns_mean_by_quantile: returns.data.mean_by_quantile,
105            information_summary: information.data.summary,
106            turnover_mean_by_quantile: turnover.data.mean_by_quantile,
107            turnover_mean_rank_autocorrelation: turnover.data.mean_rank_autocorrelation,
108        },
109    })
110}
111
112pub fn create_full_tear_sheet_data(
113    factor_data: &DataFrame,
114    options: FullTearSheetOptions,
115) -> Result<FullTearSheetData> {
116    let metadata = ReportMetadata::from_factor_data(factor_data, ReportKind::Full)?;
117    let quantile_statistics = factor_quantile_statistics(factor_data)?;
118    let returns = create_returns_tear_sheet_data(factor_data, options.returns_options())?;
119    let information =
120        create_information_tear_sheet_data(factor_data, options.information_options())?;
121    let turnover = create_turnover_tear_sheet_data(factor_data, options.turnover_options())?;
122    validate_unique_full_ids(
123        &quantile_statistics,
124        &returns.data,
125        &information.data,
126        &turnover.data,
127    )?;
128
129    Ok(FullTearSheetData {
130        metadata,
131        options,
132        data: FullReportData {
133            quantile_statistics,
134            returns: returns.data,
135            information: information.data,
136            turnover: turnover.data,
137        },
138    })
139}
140
141impl SummaryTearSheetOptions {
142    fn returns_options(&self) -> ReturnsTearSheetOptions {
143        ReturnsTearSheetOptions {
144            long_short: self.long_short,
145            group_neutral: self.group_neutral,
146            by_group: false,
147        }
148    }
149
150    fn information_options(&self) -> InformationTearSheetOptions {
151        InformationTearSheetOptions {
152            group_neutral: self.group_neutral,
153            by_group: false,
154            rolling_window: InformationTearSheetOptions::default().rolling_window,
155        }
156    }
157
158    fn turnover_options(&self) -> TurnoverTearSheetOptions {
159        TurnoverTearSheetOptions {
160            periods: self.turnover_periods.clone(),
161        }
162    }
163}
164
165impl FullTearSheetOptions {
166    fn returns_options(&self) -> ReturnsTearSheetOptions {
167        ReturnsTearSheetOptions {
168            long_short: self.long_short,
169            group_neutral: self.group_neutral,
170            by_group: self.by_group,
171        }
172    }
173
174    fn information_options(&self) -> InformationTearSheetOptions {
175        InformationTearSheetOptions {
176            group_neutral: self.group_neutral,
177            by_group: self.by_group,
178            rolling_window: self.ic_rolling_window,
179        }
180    }
181
182    fn turnover_options(&self) -> TurnoverTearSheetOptions {
183        TurnoverTearSheetOptions {
184            periods: self.turnover_periods.clone(),
185        }
186    }
187}
188
189fn validate_unique_full_ids(
190    quantile_statistics: &ReportTable,
191    returns: &ReturnsReportData,
192    information: &InformationReportData,
193    turnover: &TurnoverReportData,
194) -> Result<()> {
195    let mut seen = HashSet::new();
196    for table in full_table_refs(quantile_statistics, returns, information, turnover) {
197        if !seen.insert(table.id()) {
198            return Err(FerricAlphaError::InvalidReport {
199                operation: "create_full_tear_sheet_data",
200                reason: "duplicate table id",
201            });
202        }
203    }
204    Ok(())
205}
206
207fn full_table_refs<'a>(
208    quantile_statistics: &'a ReportTable,
209    returns: &'a ReturnsReportData,
210    information: &'a InformationReportData,
211    turnover: &'a TurnoverReportData,
212) -> Vec<&'a ReportTable> {
213    let mut tables = vec![
214        quantile_statistics,
215        &returns.summary,
216        &returns.mean_by_quantile,
217        &returns.daily_by_quantile,
218        &returns.daily_spread,
219        &returns.factor_returns,
220        &information.summary,
221        &information.ic_by_date,
222        &information.ic_rolling,
223        &information.ic_monthly,
224        &information.qq_normal,
225        &turnover.mean_by_quantile,
226        &turnover.mean_rank_autocorrelation,
227        &turnover.quantile_series,
228        &turnover.rank_autocorrelation_series,
229    ];
230    if let Some(table) = &returns.group_mean_by_quantile {
231        tables.push(table);
232    }
233    if let Some(table) = &returns.factor_cumulative_1d {
234        tables.push(table);
235    }
236    if let Some(table) = &returns.quantile_cumulative_1d {
237        tables.push(table);
238    }
239    if let Some(table) = &information.ic_by_group {
240        tables.push(table);
241    }
242    tables
243}
244
245impl Serialize for SummaryTearSheetOptions {
246    fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
247    where
248        S: Serializer,
249    {
250        let mut state = serializer.serialize_struct("SummaryTearSheetOptions", 3)?;
251        state.serialize_field("long_short", &self.long_short)?;
252        state.serialize_field("group_neutral", &self.group_neutral)?;
253        state.serialize_field(
254            "turnover_periods",
255            &serialize_periods(&self.turnover_periods),
256        )?;
257        state.end()
258    }
259}
260
261impl<'de> Deserialize<'de> for SummaryTearSheetOptions {
262    fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
263    where
264        D: Deserializer<'de>,
265    {
266        #[derive(Deserialize)]
267        struct RawOptions {
268            long_short: bool,
269            group_neutral: bool,
270            turnover_periods: Option<Vec<String>>,
271        }
272
273        let raw = RawOptions::deserialize(deserializer)?;
274        Ok(Self {
275            long_short: raw.long_short,
276            group_neutral: raw.group_neutral,
277            turnover_periods: parse_optional_periods(raw.turnover_periods)
278                .map_err(de::Error::custom)?,
279        })
280    }
281}
282
283impl Serialize for FullTearSheetOptions {
284    fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
285    where
286        S: Serializer,
287    {
288        let mut state = serializer.serialize_struct("FullTearSheetOptions", 5)?;
289        state.serialize_field("long_short", &self.long_short)?;
290        state.serialize_field("group_neutral", &self.group_neutral)?;
291        state.serialize_field("by_group", &self.by_group)?;
292        state.serialize_field(
293            "turnover_periods",
294            &serialize_periods(&self.turnover_periods),
295        )?;
296        state.serialize_field("ic_rolling_window", &self.ic_rolling_window)?;
297        state.end()
298    }
299}
300
301impl<'de> Deserialize<'de> for FullTearSheetOptions {
302    fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
303    where
304        D: Deserializer<'de>,
305    {
306        #[derive(Deserialize)]
307        struct RawOptions {
308            long_short: bool,
309            group_neutral: bool,
310            by_group: bool,
311            turnover_periods: Option<Vec<String>>,
312            ic_rolling_window: u32,
313        }
314
315        let raw = RawOptions::deserialize(deserializer)?;
316        Ok(Self {
317            long_short: raw.long_short,
318            group_neutral: raw.group_neutral,
319            by_group: raw.by_group,
320            turnover_periods: parse_optional_periods(raw.turnover_periods)
321                .map_err(de::Error::custom)?,
322            ic_rolling_window: raw.ic_rolling_window,
323        })
324    }
325}
326
327fn serialize_periods(periods: &Option<Vec<Period>>) -> Option<Vec<String>> {
328    periods
329        .as_ref()
330        .map(|periods| periods.iter().map(|period| period.label()).collect())
331}
332
333fn parse_optional_periods(
334    labels: Option<Vec<String>>,
335) -> std::result::Result<Option<Vec<Period>>, String> {
336    labels
337        .map(|labels| {
338            labels
339                .into_iter()
340                .map(|label| parse_period_label(&label))
341                .collect::<std::result::Result<Vec<_>, _>>()
342        })
343        .transpose()
344}
345
346fn parse_period_label(label: &str) -> std::result::Result<Period, String> {
347    let Some(count) = label.strip_suffix('D') else {
348        return Err("period must end with D".to_string());
349    };
350    if count.is_empty() || count.starts_with('0') {
351        return Err("period must be a positive daily count".to_string());
352    }
353    let count = count
354        .parse::<u32>()
355        .map_err(|_| "period must be numeric".to_string())?;
356    Period::new(count).map_err(|error| error.to_string())
357}