(df: &DataFrame, interval_seconds: i64)
| 197 | } |
| 198 | |
| 199 | pub fn align_calendar_df(df: &DataFrame, interval_seconds: i64) -> Result<DataFrame, String> { |
| 200 | if interval_seconds <= 0 { |
| 201 | return Err("interval_seconds must be > 0".to_string()); |
| 202 | } |
| 203 | |
| 204 | let (cleaned, _) = clean_ohlcv_df(df, true)?; |
| 205 | if cleaned.height() == 0 { |
| 206 | let mut out = cleaned.clone(); |
| 207 | out.with_column(Series::new("is_missing_bar".into(), Vec::<bool>::new())) |
| 208 | .map_err(|e| format!("failed to add is_missing_bar: {e}"))?; |
| 209 | return Ok(out); |
| 210 | } |
| 211 | |
| 212 | let symbols = cleaned |
| 213 | .column("symbol") |
| 214 | .map_err(|e| format!("symbol column error: {e}"))? |
| 215 | .str() |
| 216 | .map_err(|e| format!("symbol dtype error: {e}"))?; |
| 217 | let ts = cleaned |
| 218 | .column("ts_us") |
| 219 | .map_err(|e| format!("ts_us column error: {e}"))? |
| 220 | .i64() |
| 221 | .map_err(|e| format!("ts_us dtype error: {e}"))?; |
| 222 | |
| 223 | let step_us = interval_seconds * 1_000_000; |
| 224 | |
| 225 | let mut cal_symbols: Vec<String> = Vec::new(); |
| 226 | let mut cal_ts: Vec<i64> = Vec::new(); |
| 227 | |
| 228 | let mut i = 0usize; |
| 229 | while i < cleaned.height() { |
| 230 | let symbol = symbols.get(i).ok_or_else(|| format!("null symbol at row {i}"))?; |
| 231 | let start = ts.get(i).ok_or_else(|| format!("null ts_us at row {i}"))?; |
| 232 | |
| 233 | let mut j = i + 1; |
| 234 | while j < cleaned.height() && symbols.get(j) == Some(symbol) { |
| 235 | j += 1; |
| 236 | } |
| 237 | |
| 238 | let end = ts.get(j - 1).ok_or_else(|| format!("null ts_us at row {}", j - 1))?; |
| 239 | |
| 240 | let mut cur = start; |
| 241 | while cur <= end { |
| 242 | cal_symbols.push(symbol.to_string()); |
| 243 | cal_ts.push(cur); |
| 244 | cur += step_us; |
| 245 | } |
| 246 | |
| 247 | i = j; |
| 248 | } |
| 249 | |
| 250 | let calendar = df!("symbol" => cal_symbols, "ts_us" => cal_ts) |
| 251 | .map_err(|e| format!("calendar df build failed: {e}"))?; |
| 252 | |
| 253 | let mut out = calendar |
| 254 | .left_join(&cleaned, ["symbol", "ts_us"], ["symbol", "ts_us"]) |
| 255 | .map_err(|e| format!("calendar join failed: {e}"))?; |
| 256 |
no test coverage detected