Compare commits

..

8 Commits

Author SHA1 Message Date
Palash Tyagi
19e91cfe47 Merge branch 'main' into rawdf 2025-04-13 11:41:00 +01:00
Palash Tyagi
b4d42c1dda add BSeries struct and conversion implementations for FSeries and ISeries 2025-04-12 22:06:44 +01:00
Palash Tyagi
2b969f4eaf change example usage code blocks to ignore in JPMaQSDownload documentation 2025-04-12 11:04:28 +01:00
Palash Tyagi
1d301b45b7 uncomment README.md documentation line and add core module declaration 2025-04-12 11:04:24 +01:00
Palash Tyagi
4f60e31d55 add core module with df, xseries, and dateseries 2025-04-12 11:04:12 +01:00
Palash Tyagi
d938d9adc3 added placeholder df module 2025-04-11 23:55:42 +01:00
Palash Tyagi
5a5bd4777d add first draft for dateseries 2025-04-11 23:55:29 +01:00
Palash Tyagi
cf2779c5a1 adding first draft for xseries 2025-04-11 23:55:15 +01:00
6 changed files with 514 additions and 3 deletions

281
src/core/dateseries.rs Normal file
View File

@@ -0,0 +1,281 @@
//! # DateSeries and BDateSeries Implementations
//!
//! This module provides two date-handling types using the [`chrono`](https://docs.rs/chrono) crate:
//!
//! - [`DateSeries`]: Stores any set of calendar dates and allows adding/subtracting *calendar days*.
//! - [`BDateSeries`]: Stores only MondayFriday business days and interprets add/sub as *business day* shifts,
//! skipping weekends (e.g., adding 1 to Friday goes to Monday).
//!
//! Both types also provide a [`from_iso8601_range`](#method.from_iso8601_range) constructor
//! that builds a date series (or businessdate series) from a start/end string (YYYYMMDD).
use chrono::{Datelike, Duration, NaiveDate, ParseResult};
use std::ops::{Add, Sub};
/// Determines if the date is Saturday or Sunday.
fn is_weekend(date: NaiveDate) -> bool {
matches!(date.weekday(), chrono::Weekday::Sat | chrono::Weekday::Sun)
}
/// A `DateSeries` stores a list of [`NaiveDate`] values and shifts by **calendar days**.
///
/// ## Example Usage
///
/// ```
/// use chrono::NaiveDate;
/// use msyrs::core::dateseries::DateSeries;
///
/// // Create from explicit dates
/// let ds = DateSeries::new(vec![
/// NaiveDate::from_ymd_opt(2023, 7, 14).unwrap(), // a Friday
/// NaiveDate::from_ymd_opt(2023, 7, 15).unwrap(), // a Saturday
/// ]);
///
/// // Shift forward by 5 calendar days
/// let ds_plus = ds + 5;
/// // 2023-07-14 + 5 => 2023-07-19 (Wednesday)
/// // 2023-07-15 + 5 => 2023-07-20 (Thursday)
///
/// assert_eq!(ds_plus.data()[0], NaiveDate::from_ymd_opt(2023, 7, 19).unwrap());
/// assert_eq!(ds_plus.data()[1], NaiveDate::from_ymd_opt(2023, 7, 20).unwrap());
/// ```
///
#[derive(Debug, Clone)]
pub struct DateSeries {
data: Vec<NaiveDate>,
}
impl DateSeries {
/// Creates a new `DateSeries` from a vector of [`NaiveDate`] values.
///
/// # Panics
/// - Does not panic on invalid weekend or anything; this type accepts all valid dates.
pub fn new(data: Vec<NaiveDate>) -> Self {
Self { data }
}
/// Constructs a `DateSeries` by parsing an ISO8601 start/end string (YYYYMMDD)
/// and including **every calendar date** from start to end (inclusive).
///
/// # Errors
/// - Returns a [`chrono::ParseError`](chrono::ParseError) if parsing fails.
/// - Panics if `start` > `end` chronologically.
///
/// # Examples
///
/// ```
/// use msyrs::core::dateseries::DateSeries;
/// # fn main() -> Result<(), chrono::ParseError> {
/// let ds = DateSeries::from_iso8601_range("2023-07-14", "2023-07-16")?;
/// assert_eq!(ds.data().len(), 3);
/// # Ok(())
/// # }
/// ```
pub fn from_iso8601_range(start: &str, end: &str) -> ParseResult<Self> {
let start_date = NaiveDate::parse_from_str(start, "%Y-%m-%d")?;
let end_date = NaiveDate::parse_from_str(end, "%Y-%m-%d")?;
assert!(
start_date <= end_date,
"start date cannot be after end date"
);
let mut dates = Vec::new();
let mut current = start_date;
while current <= end_date {
dates.push(current);
current = current
.checked_add_signed(Duration::days(1))
.expect("Date overflow in from_iso8601_range");
}
Ok(Self::new(dates))
}
/// Returns a reference to the underlying slice of dates.
pub fn data(&self) -> &[NaiveDate] {
&self.data
}
/// Internal helper applying a function to each date.
fn apply<F>(&self, op: F) -> Self
where
F: Fn(NaiveDate) -> NaiveDate,
{
let new_data = self.data.iter().map(|&date| op(date)).collect();
Self { data: new_data }
}
}
/// Implements adding calendar days to each `NaiveDate`.
///
/// If the shifted date goes out of chrono's valid range, it panics.
impl Add<i64> for DateSeries {
type Output = Self;
fn add(self, rhs: i64) -> Self::Output {
self.apply(|date| {
date.checked_add_signed(Duration::days(rhs))
.expect("Overflow in date addition")
})
}
}
/// Implements subtracting calendar days from each `NaiveDate`.
///
/// If the shifted date goes out of chrono's valid range, it panics.
impl Sub<i64> for DateSeries {
type Output = Self;
fn sub(self, rhs: i64) -> Self::Output {
self.apply(|date| {
date.checked_sub_signed(Duration::days(rhs))
.expect("Overflow in date subtraction")
})
}
}
/// A “Business Date Series” for MondayFriday only.
///
/// 1. The constructor disallows weekend dates (panics if any date is Sat/Sun).
/// 2. Adding or subtracting an `i64` interprets that integer as *business days*, skipping weekends.
/// For example, adding 1 to a Friday yields the following Monday.
///
/// ## Example Usage
///
/// ```
/// use chrono::NaiveDate;
/// use msyrs::core::dateseries::BDateSeries;
///
/// // Friday
/// let friday = NaiveDate::from_ymd_opt(2023, 7, 14).unwrap();
/// let mut bds = BDateSeries::new(vec![friday]);
///
/// // Adding 1 “business day” => next Monday, 2023-07-17
/// bds = bds + 1;
/// assert_eq!(bds.data()[0], NaiveDate::from_ymd_opt(2023, 7, 17).unwrap());
/// ```
#[derive(Debug, Clone)]
pub struct BDateSeries {
data: Vec<NaiveDate>,
}
impl BDateSeries {
/// Creates a new `BDateSeries`, panicking if any of the supplied dates is on Saturday/Sunday.
pub fn new(data: Vec<NaiveDate>) -> Self {
for &d in &data {
if is_weekend(d) {
panic!("BDateSeries cannot contain weekend dates: {}", d);
}
}
Self { data }
}
/// Constructs a `BDateSeries` by parsing an ISO8601 start/end string (YYYYMMDD).
///
/// Only MondayFriday dates within `[start, end]` are included in the series.
///
/// # Errors
/// - Returns a [`chrono::ParseError`](chrono::ParseError) if parsing fails.
/// - Panics if `start` > `end` chronologically.
///
/// # Examples
///
/// ```
/// use msyrs::core::dateseries::BDateSeries;
/// # fn main() -> Result<(), chrono::ParseError> {
/// let bds = BDateSeries::from_iso8601_range("2023-07-14", "2023-07-18")?;
/// // 2023-07-14 (Friday), 2023-07-15 (Saturday) => skipped,
/// // 2023-07-16 (Sunday) => skipped,
/// // 2023-07-17 (Monday), 2023-07-18 (Tuesday)
/// // so total 3 valid business days
/// assert_eq!(bds.data().len(), 3);
/// # Ok(())
/// # }
/// ```
pub fn from_iso8601_range(start: &str, end: &str) -> ParseResult<Self> {
let start_date = NaiveDate::parse_from_str(start, "%Y-%m-%d")?;
let end_date = NaiveDate::parse_from_str(end, "%Y-%m-%d")?;
assert!(
start_date <= end_date,
"start date cannot be after end date"
);
let mut dates = Vec::new();
let mut current = start_date;
while current <= end_date {
if !is_weekend(current) {
dates.push(current);
}
current = current
.checked_add_signed(Duration::days(1))
.expect("Date overflow in from_iso8601_range");
}
Ok(Self::new(dates))
}
/// Returns a reference to the underlying slice of dates.
pub fn data(&self) -> &[NaiveDate] {
&self.data
}
/// Internal helper that tries to shift a date forward or backward by one day at a time,
/// skipping weekends, for a total of `delta` business days.
fn shift_business_days(date: NaiveDate, delta: i64) -> NaiveDate {
if delta == 0 {
return date;
}
let step = if delta > 0 { 1 } else { -1 };
let abs_delta = delta.abs();
let mut new_date = date;
for _ in 0..abs_delta {
// Move by 1 day in the correct direction
new_date = new_date
.checked_add_signed(Duration::days(step))
.expect("Overflow in BDateSeries add/sub");
// If we land on weekend, keep moving until Monday..Friday
while is_weekend(new_date) {
new_date = new_date
.checked_add_signed(Duration::days(step))
.expect("Overflow in BDateSeries skipping weekend");
}
}
new_date
}
/// Internal helper to apply a shift of `delta` business days to each date.
fn apply(&self, delta: i64) -> Self {
let new_data = self
.data
.iter()
.map(|&date| Self::shift_business_days(date, delta))
.collect();
Self { data: new_data }
}
}
/// Implement *business day* addition for `BDateSeries`.
///
/// # Panics
/// - If the resulting date(s) overflow `NaiveDate` range.
/// - `BDateSeries` is guaranteed to remain Monday..Friday after the shift.
impl Add<i64> for BDateSeries {
type Output = Self;
fn add(self, rhs: i64) -> Self::Output {
self.apply(rhs)
}
}
/// Implement *business day* subtraction for `BDateSeries`.
///
/// # Panics
/// - If the resulting date(s) overflow `NaiveDate`.
/// - `BDateSeries` is guaranteed to remain Monday..Friday after the shift.
impl Sub<i64> for BDateSeries {
type Output = Self;
fn sub(self, rhs: i64) -> Self::Output {
self.apply(-rhs)
}
}

0
src/core/df.rs Normal file
View File

3
src/core/mod.rs Normal file
View File

@@ -0,0 +1,3 @@
pub mod df;
pub mod xseries;
pub mod dateseries;

223
src/core/xseries.rs Normal file
View File

@@ -0,0 +1,223 @@
use std::ops::{Add, Div, Mul, Sub};
//
// 1) Define a float series: FSeries
//
#[derive(Debug, Clone)]
pub struct FSeries {
data: Vec<f64>,
}
impl FSeries {
/// Create a new FSeries from a vector of f64 values.
pub fn new(data: Vec<f64>) -> Self {
Self { data }
}
pub fn len(&self) -> usize {
self.data.len()
}
/// Elementwise helper applying an operation between two FSeries.
pub fn apply<F>(&self, other: &Self, op: F) -> Self
where
F: Fn(f64, f64) -> f64,
{
assert!(
self.len() == other.len(),
"FSeries must have the same length to apply operations."
);
let data = self
.data
.iter()
.zip(other.data.iter())
.map(|(&a, &b)| op(a, b))
.collect();
FSeries { data }
}
/// Access to the underlying data
pub fn data(&self) -> &[f64] {
&self.data
}
}
// Macros for float series arithmetic (elementwise)
macro_rules! impl_fseries_bin_op {
($trait:ident, $method:ident, $op:tt) => {
impl $trait for FSeries {
type Output = Self;
fn $method(self, rhs: Self) -> Self::Output {
self.apply(&rhs, |a, b| a $op b)
}
}
};
}
impl_fseries_bin_op!(Add, add, +);
impl_fseries_bin_op!(Sub, sub, -);
impl_fseries_bin_op!(Mul, mul, *);
impl_fseries_bin_op!(Div, div, /);
macro_rules! impl_fseries_scalar_op {
($trait:ident, $method:ident, $op:tt) => {
impl $trait<f64> for FSeries {
type Output = Self;
fn $method(mut self, scalar: f64) -> Self::Output {
for x in self.data.iter_mut() {
*x = *x $op scalar;
}
self
}
}
};
}
impl_fseries_scalar_op!(Add, add, +);
impl_fseries_scalar_op!(Sub, sub, -);
impl_fseries_scalar_op!(Mul, mul, *);
impl_fseries_scalar_op!(Div, div, /);
//
// 2) Define an integer series: ISeries
//
#[derive(Debug, Clone)]
pub struct ISeries {
data: Vec<i64>,
}
impl ISeries {
/// Create an ISeries from a vector of i64 values.
pub fn new(data: Vec<i64>) -> Self {
Self { data }
}
pub fn len(&self) -> usize {
self.data.len()
}
pub fn data(&self) -> &[i64] {
&self.data
}
/// Elementwise helper for integer series.
pub fn apply<F>(&self, other: &Self, op: F) -> Self
where
F: Fn(i64, i64) -> i64,
{
assert!(
self.len() == other.len(),
"ISeries must have the same length to apply operations."
);
let data = self
.data
.iter()
.zip(other.data.iter())
.map(|(&a, &b)| op(a, b))
.collect();
ISeries { data }
}
}
// Macros for integer series arithmetic (elementwise)
macro_rules! impl_iseries_bin_op {
($trait:ident, $method:ident, $op:tt) => {
impl $trait for ISeries {
type Output = Self;
fn $method(self, rhs: Self) -> Self::Output {
self.apply(&rhs, |a, b| a $op b)
}
}
};
}
impl_iseries_bin_op!(Add, add, +);
impl_iseries_bin_op!(Sub, sub, -);
impl_iseries_bin_op!(Mul, mul, *);
impl_iseries_bin_op!(Div, div, /); // integer division (floor trunc)
// Optional scalar operations (for i64)
macro_rules! impl_iseries_scalar_op {
($trait:ident, $method:ident, $op:tt) => {
impl $trait<i64> for ISeries {
type Output = Self;
fn $method(mut self, scalar: i64) -> Self::Output {
for x in self.data.iter_mut() {
*x = *x $op scalar;
}
self
}
}
};
}
impl_iseries_scalar_op!(Add, add, +);
impl_iseries_scalar_op!(Sub, sub, -);
impl_iseries_scalar_op!(Mul, mul, *);
impl_iseries_scalar_op!(Div, div, /); // floor/trunc division by scalar
/// A boolean series: BSeries
///
#[derive(Debug, Clone)]
pub struct BSeries {
data: Vec<bool>,
}
impl BSeries {
pub fn new(data: Vec<bool>) -> Self {
Self { data }
}
pub fn len(&self) -> usize {
self.data.len()
}
pub fn data(&self) -> &[bool] {
&self.data
}
}
/// Convert an FSeries to ISeries by truncation (floor cast).
impl From<FSeries> for ISeries {
fn from(fseries: FSeries) -> Self {
let data = fseries
.data
.into_iter()
.map(|val| val as i64) // trunc cast
.collect();
ISeries::new(data)
}
}
/// Implement conversion from ISeries to FSeries by casting to f64.
impl From<ISeries> for FSeries {
fn from(iseries: ISeries) -> Self {
let data = iseries.data.into_iter().map(|val| val as f64).collect();
FSeries::new(data)
}
}
/// Convert an ISeries to BSeries by checking if each value is non-zero.
impl From<ISeries> for BSeries {
fn from(iseries: ISeries) -> Self {
let data = iseries.data.into_iter().map(|val| val != 0).collect();
BSeries::new(data)
}
}
impl From<BSeries> for ISeries {
fn from(bseries: BSeries) -> Self {
let data = bseries
.data
.into_iter()
.map(|val| if val { 1 } else { 0 })
.collect();
ISeries::new(data)
}
}

View File

@@ -102,7 +102,7 @@ impl Default for JPMaQSDownloadGetIndicatorArgs {
/// Struct for downloading data from the JPMaQS data from JPMorgan DataQuery API.
///
/// ## Example Usage
/// ```rust
/// ```ignore
/// use msyrs::download::jpmaqsdownload::JPMaQSDownload;
/// use msyrs::download::jpmaqsdownload::JPMaQSDownloadGetIndicatorArgs;
/// use polars::prelude::*;
@@ -140,7 +140,7 @@ impl Default for JPMaQSDownloadGetIndicatorArgs {
/// Ok(_) => println!("Saved indicators to disk"),
/// Err(e) => println!("Error saving indicators: {:?}", e),
/// }
///
/// ```
#[derive(Debug, Clone)]
pub struct JPMaQSDownload {
requester: DQRequester,
@@ -277,7 +277,7 @@ impl JPMaQSDownload {
///
/// Usage:
///
/// ```rust
/// ```ignore
/// use msyrs::download::jpmaqsdownload::JPMaQSDownload;
/// use msyrs::download::jpmaqsdownload::JPMaQSDownloadGetIndicatorArgs;
/// let mut jpamqs_download = JPMaQSDownload::default();

View File

@@ -1,4 +1,5 @@
// #![doc = include_str!("../README.md")]
// uncomment the above line to include the README.md file in the documentation
//! # msyrs
//!
@@ -18,6 +19,9 @@
/// Documentation and type-stubs for the `msyrs` Python API.
pub mod _py;
/// Implementation for the `core` module.
pub mod core;
/// Implementation for the `download` module.
pub mod download;