optionstratlib 0.17.3

OptionStratLib is a comprehensive Rust library for options trading and strategy development across multiple asset classes.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
// Scoped allow: bulk migration of unchecked `[]` indexing to
// `.get().ok_or_else(..)` tracked as follow-ups to #341. The existing
// call sites are internal to this file and audited for invariant-bound
// indices (fixed-length buffers, just-pushed slices, etc.).
#![allow(clippy::indexing_slicing)]

use crate::error::OhlcvError;
use chrono::NaiveDate;
use rust_decimal::Decimal;
use rust_decimal::prelude::FromStr;
use serde::{Deserialize, Serialize};
use std::fs::File;
use std::io::{BufRead, BufReader};
use std::path::Path;
use zip::ZipArchive;

/// Represents an OHLC+V candlestick with timestamp
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct OhlcvCandle {
    /// Date of the candle
    pub date: NaiveDate,
    /// Time of the candle in HH:MM:SS format
    pub time: String,
    /// Opening price
    pub open: Decimal,
    /// Highest price during the period
    pub high: Decimal,
    /// Lowest price during the period
    pub low: Decimal,
    /// Closing price
    pub close: Decimal,
    /// Volume traded during the period
    pub volume: u64,
}

/// Reads OHLCV data from a zipped CSV file and filters it by date range
///
/// # Arguments
///
/// * `zip_path` - Path to the ZIP file containing the CSV
/// * `start_date` - Optional start date in DD/MM/YYYY format (inclusive)
/// * `end_date` - Optional end date in DD/MM/YYYY format (inclusive)
///
/// # Returns
///
/// A vector of OhlcvCandle structs containing the filtered data
///
/// # Errors
///
/// Returns an OhlcvError if:
/// - The ZIP file cannot be opened
/// - The CSV file within the ZIP cannot be read
/// - The date range is invalid
/// - Data parsing fails
pub fn read_ohlcv_from_zip(
    zip_path: &str,
    start_date: Option<&str>,
    end_date: Option<&str>,
) -> Result<Vec<OhlcvCandle>, OhlcvError> {
    // Parse date range if provided
    let start = if let Some(start_str) = start_date {
        Some(NaiveDate::parse_from_str(start_str, "%d/%m/%Y")?)
    } else {
        None
    };

    let end = if let Some(end_str) = end_date {
        Some(NaiveDate::parse_from_str(end_str, "%d/%m/%Y")?)
    } else {
        None
    };

    // Validate date range if both dates are provided
    if let (Some(start_date), Some(end_date)) = (&start, &end)
        && start_date > end_date
    {
        return Err(OhlcvError::InvalidParameter {
            reason: format!("Start date {start_date} is after end date {end_date}"),
        });
    }

    // Open the ZIP file
    let file = File::open(Path::new(zip_path))?;
    let mut archive = ZipArchive::new(file)?;

    // Find the first CSV file in the archive
    let mut csv_index = None;
    for i in 0..archive.len() {
        let file = archive.by_index(i)?;
        if file.name().ends_with(".csv") {
            csv_index = Some(i);
            break;
        }
    }

    let csv_index = csv_index.ok_or(OhlcvError::MissingZipEntry { extension: "csv" })?;
    let file = archive.by_index(csv_index)?;
    let reader = BufReader::new(file);

    let mut candles = Vec::new();

    for (line_num, line_result) in reader.lines().enumerate() {
        // Skip header if present (line 0)
        if line_num == 0
            && line_result
                .as_ref()
                .is_ok_and(|l| l.contains("date") || l.contains("Date"))
        {
            continue;
        }

        let line = line_result?;
        let parts: Vec<&str> = line.split(';').collect();

        // Ensure we have 7 parts: date, time, open, high, low, close, volume
        if parts.len() != 7 {
            return Err(OhlcvError::CsvError {
                reason: format!(
                    "Invalid CSV format at line {}: expected 7 fields, got {}",
                    line_num + 1,
                    parts.len()
                ),
            });
        }

        // Parse date
        let date = NaiveDate::parse_from_str(parts[0], "%d/%m/%Y")?;

        // Skip records outside our date range if dates are specified
        if start.is_some_and(|s| date < s) || end.is_some_and(|e| date > e) {
            continue;
        }

        // Parse other fields
        let candle = OhlcvCandle {
            date,
            time: parts[1].to_string(),
            open: Decimal::from_str(parts[2])?,
            high: Decimal::from_str(parts[3])?,
            low: Decimal::from_str(parts[4])?,
            close: Decimal::from_str(parts[5])?,
            volume: parts[6].parse::<u64>().map_err(|e| OhlcvError::CsvError {
                reason: format!("Invalid volume at line {}: {}", line_num + 1, e),
            })?,
        };

        candles.push(candle);
    }

    Ok(candles)
}

/// Reads OHLCV data from a zipped CSV file asynchronously and filters it by date range.
///
/// # Note
///
/// This method is only available with the `async` feature.
///
/// # Errors
///
/// Returns the same variants as [`read_ohlcv_from_zip`]
/// (I/O, ZIP, CSV and date/decimal parsing), plus
/// [`OhlcvError::AsyncTask`] when the `spawn_blocking` worker fails
/// (e.g. panics or cancellation).
#[cfg(feature = "async")]
pub async fn read_ohlcv_from_zip_async(
    zip_path: String,
    start_date: Option<String>,
    end_date: Option<String>,
) -> Result<Vec<OhlcvCandle>, OhlcvError> {
    tokio::task::spawn_blocking(move || {
        read_ohlcv_from_zip(&zip_path, start_date.as_deref(), end_date.as_deref())
    })
    .await
    .map_err(|e| OhlcvError::AsyncTask {
        reason: e.to_string(),
    })?
}

#[cfg(test)]
mod ohlcv_tests {
    use super::*;
    use chrono::NaiveDate;
    use mockall::predicate::*;
    use rust_decimal_macros::dec;
    use std::io::Write;
    use tempfile::NamedTempFile;
    use zip::{ZipWriter, write::FileOptions};

    // Helper function to create a temporary zip file with test data
    fn create_test_zip(data: &str) -> Result<(String, NamedTempFile), OhlcvError> {
        // Create a temp file to hold our zip
        let temp_file = NamedTempFile::new().map_err(|e| OhlcvError::IoError {
            reason: e.to_string(),
        })?;

        // Create a zip archive
        let mut zip = ZipWriter::new(File::create(temp_file.path())?);

        // Add a CSV file
        let options: FileOptions<'_, ()> =
            FileOptions::default().compression_method(zip::CompressionMethod::Stored);

        zip.start_file("test_data.csv", options)
            .map_err(|e| OhlcvError::ZipError {
                reason: e.to_string(),
            })?;

        // Write our test data
        zip.write_all(data.as_bytes())
            .map_err(|e| OhlcvError::IoError {
                reason: e.to_string(),
            })?;

        // Finish the zip
        zip.finish().map_err(|e| OhlcvError::ZipError {
            reason: e.to_string(),
        })?;

        Ok((temp_file.path().to_string_lossy().to_string(), temp_file))
    }

    #[test]
    fn test_read_ohlcv_valid_data() -> Result<(), OhlcvError> {
        // Create test data
        let csv_data = "date;time;open;high;low;close;volume\n\
                        01/01/2022;10:00:00;100.0;110.0;95.0;105.0;5000\n\
                        02/01/2022;10:00:00;105.0;112.0;104.0;110.0;6000\n\
                        03/01/2022;10:00:00;110.0;115.0;108.0;114.0;7000";

        let (zip_path, _temp_file) = create_test_zip(csv_data)?;

        // Call our function
        let candles = read_ohlcv_from_zip(&zip_path, Some("01/01/2022"), Some("02/01/2022"))?;

        // Verify results
        assert_eq!(candles.len(), 2, "Should return exactly 2 candles");

        // Verify first candle
        assert_eq!(
            candles[0].date,
            NaiveDate::from_ymd_opt(2022, 1, 1).unwrap()
        );
        assert_eq!(candles[0].time, "10:00:00");
        assert_eq!(candles[0].open, dec!(100.0));
        assert_eq!(candles[0].high, dec!(110.0));
        assert_eq!(candles[0].low, dec!(95.0));
        assert_eq!(candles[0].close, dec!(105.0));
        assert_eq!(candles[0].volume, 5000);

        // Verify second candle
        assert_eq!(
            candles[1].date,
            NaiveDate::from_ymd_opt(2022, 1, 2).unwrap()
        );
        assert_eq!(candles[1].time, "10:00:00");
        assert_eq!(candles[1].open, dec!(105.0));
        assert_eq!(candles[1].high, dec!(112.0));
        assert_eq!(candles[1].low, dec!(104.0));
        assert_eq!(candles[1].close, dec!(110.0));
        assert_eq!(candles[1].volume, 6000);

        Ok(())
    }

    #[test]
    fn test_read_ohlcv_without_header() -> Result<(), OhlcvError> {
        // Create test data without header
        let csv_data = "01/01/2022;10:00:00;100.0;110.0;95.0;105.0;5000\n\
                        02/01/2022;10:00:00;105.0;112.0;104.0;110.0;6000";

        let (zip_path, _temp_file) = create_test_zip(csv_data)?;

        // Call our function
        let candles = read_ohlcv_from_zip(&zip_path, Some("01/01/2022"), Some("02/01/2022"))?;

        // Verify results
        assert_eq!(
            candles.len(),
            2,
            "Should return exactly 2 candles even without header"
        );

        Ok(())
    }

    #[test]
    fn test_read_ohlcv_invalid_date_range() {
        // Create test data
        let csv_data = "date;time;open;high;low;close;volume\n\
                        01/01/2022;10:00:00;100.0;110.0;95.0;105.0;5000";

        let (zip_path, _temp_file) = create_test_zip(csv_data).unwrap();

        // Call our function with end date before start date
        let result = read_ohlcv_from_zip(&zip_path, Some("02/01/2022"), Some("01/01/2022"));

        // Verify results
        assert!(
            result.is_err(),
            "Should return an error for invalid date range"
        );
        if let Err(OhlcvError::InvalidParameter { reason }) = result {
            assert!(
                reason.contains("Start date"),
                "Error should mention start date being after end date"
            );
        } else {
            panic!("Expected InvalidParameter error");
        }
    }

    #[test]
    fn test_read_ohlcv_nonexistent_file() {
        // Call function with nonexistent file
        let result = read_ohlcv_from_zip(
            "nonexistent_file.zip",
            Some("01/01/2022"),
            Some("31/12/2022"),
        );

        // Verify results
        assert!(
            result.is_err(),
            "Should return an error for nonexistent file"
        );
        if let Err(OhlcvError::IoError { .. }) = result {
            // This is expected
        } else {
            panic!("Expected IoError");
        }
    }

    #[test]
    fn test_read_ohlcv_invalid_csv_format() -> Result<(), OhlcvError> {
        // Create test data with invalid format (missing a column)
        let csv_data = "date;time;open;high;low;close\n\
                        01/01/2022;10:00:00;100.0;110.0;95.0;105.0";

        let (zip_path, _temp_file) = create_test_zip(csv_data)?;

        // Call our function
        let result = read_ohlcv_from_zip(&zip_path, Some("01/01/2022"), Some("31/12/2022"));

        // Verify results
        assert!(
            result.is_err(),
            "Should return an error for invalid CSV format"
        );
        if let Err(OhlcvError::CsvError { reason }) = result {
            assert!(
                reason.contains("expected 7 fields"),
                "Error should mention expected field count"
            );
        } else {
            panic!("Expected CsvError");
        }

        Ok(())
    }

    #[test]
    fn test_read_ohlcv_invalid_decimal() -> Result<(), OhlcvError> {
        // Create test data with invalid decimal
        let csv_data = "date;time;open;high;low;close;volume\n\
                        01/01/2022;10:00:00;not_a_number;110.0;95.0;105.0;5000";

        let (zip_path, _temp_file) = create_test_zip(csv_data)?;

        // Call our function
        let result = read_ohlcv_from_zip(&zip_path, Some("01/01/2022"), Some("31/12/2022"));

        // Verify results
        assert!(
            result.is_err(),
            "Should return an error for invalid decimal"
        );
        if let Err(OhlcvError::DecimalParseError { .. }) = result {
            // This is expected
        } else {
            panic!("Expected DecimalParseError");
        }

        Ok(())
    }

    #[test]
    fn test_read_ohlcv_invalid_volume() -> Result<(), OhlcvError> {
        // Create test data with invalid volume
        let csv_data = "date;time;open;high;low;close;volume\n\
                        01/01/2022;10:00:00;100.0;110.0;95.0;105.0;not_a_number";

        let (zip_path, _temp_file) = create_test_zip(csv_data)?;

        // Call our function
        let result = read_ohlcv_from_zip(&zip_path, Some("01/01/2022"), Some("31/12/2022"));

        // Verify results
        assert!(result.is_err(), "Should return an error for invalid volume");
        if let Err(OhlcvError::CsvError { .. }) = result {
            // This is expected
        } else {
            panic!("Expected CsvError");
        }

        Ok(())
    }

    #[test]
    fn test_read_ohlcv_invalid_date_format() -> Result<(), OhlcvError> {
        // Create test data with invalid date format
        let csv_data = "date;time;open;high;low;close;volume\n\
                        2022-01-01;10:00:00;100.0;110.0;95.0;105.0;5000";

        let (zip_path, _temp_file) = create_test_zip(csv_data)?;

        // Call our function
        let result = read_ohlcv_from_zip(&zip_path, Some("01/01/2022"), Some("31/12/2022"));

        // Verify results
        assert!(
            result.is_err(),
            "Should return an error for invalid date format"
        );
        if let Err(OhlcvError::DateParseError { .. }) = result {
            // This is expected
        } else {
            panic!("Expected DateParseError");
        }

        Ok(())
    }

    #[test]
    fn test_read_ohlcv_empty_file() -> Result<(), OhlcvError> {
        // Create empty test file
        let csv_data = "";

        let (zip_path, _temp_file) = create_test_zip(csv_data)?;

        // Call our function
        let candles = read_ohlcv_from_zip(&zip_path, Some("01/01/2022"), Some("31/12/2022"))?;

        // Verify results
        assert_eq!(
            candles.len(),
            0,
            "Should return empty vector for empty file"
        );

        Ok(())
    }

    #[test]
    fn test_read_ohlcv_no_matching_dates() -> Result<(), OhlcvError> {
        // Create test data with dates outside requested range
        let csv_data = "date;time;open;high;low;close;volume\n\
                        01/01/2022;10:00:00;100.0;110.0;95.0;105.0;5000\n\
                        02/01/2022;10:00:00;105.0;112.0;104.0;110.0;6000";

        let (zip_path, _temp_file) = create_test_zip(csv_data)?;

        // Call our function with date range that doesn't match any data
        let candles = read_ohlcv_from_zip(&zip_path, Some("03/01/2022"), Some("04/01/2022"))?;

        // Verify results
        assert_eq!(
            candles.len(),
            0,
            "Should return empty vector when no dates match"
        );

        Ok(())
    }

    #[test]
    fn test_read_ohlcv_partial_matches() -> Result<(), OhlcvError> {
        // Create test data with some dates in range and some out of range
        let csv_data = "date;time;open;high;low;close;volume\n\
                        01/01/2022;10:00:00;100.0;110.0;95.0;105.0;5000\n\
                        02/01/2022;10:00:00;105.0;112.0;104.0;110.0;6000\n\
                        03/01/2022;10:00:00;110.0;115.0;108.0;114.0;7000";

        let (zip_path, _temp_file) = create_test_zip(csv_data)?;

        // Call our function with date range that only matches some data
        let candles = read_ohlcv_from_zip(&zip_path, Some("02/01/2022"), Some("03/01/2022"))?;

        // Verify results
        assert_eq!(candles.len(), 2, "Should return exactly 2 candles");
        assert_eq!(
            candles[0].date,
            NaiveDate::from_ymd_opt(2022, 1, 2).unwrap()
        );
        assert_eq!(
            candles[1].date,
            NaiveDate::from_ymd_opt(2022, 1, 3).unwrap()
        );

        Ok(())
    }

    #[test]
    fn test_ohlcv_error_display() {
        // Test IoError display
        let io_error = OhlcvError::IoError {
            reason: "test reason".to_string(),
        };
        assert_eq!(format!("{io_error}"), "IO error: test reason");

        // Test ZipError display
        let zip_error = OhlcvError::ZipError {
            reason: "test reason".to_string(),
        };
        assert_eq!(format!("{zip_error}"), "ZIP error: test reason");

        // Test CsvError display
        let csv_error = OhlcvError::CsvError {
            reason: "test reason".to_string(),
        };
        assert_eq!(format!("{csv_error}"), "CSV error: test reason");

        // Test DateParseError display
        let date_error = OhlcvError::DateParseError {
            reason: "test reason".to_string(),
        };
        assert_eq!(format!("{date_error}"), "Date parse error: test reason");

        // Test DecimalParseError display
        let decimal_error = OhlcvError::DecimalParseError {
            reason: "test reason".to_string(),
        };
        assert_eq!(
            format!("{decimal_error}"),
            "Decimal parse error: test reason"
        );

        // Test InvalidParameter display
        let param_error = OhlcvError::InvalidParameter {
            reason: "test reason".to_string(),
        };
        assert_eq!(format!("{param_error}"), "Invalid parameter: test reason");

        // Test MissingColumn display
        let missing_column = OhlcvError::MissingColumn { column: "csv" };
        assert_eq!(
            format!("{missing_column}"),
            "required column `csv` is missing"
        );

        // Test RowParsing display
        let row_parsing = OhlcvError::RowParsing {
            reason: "test reason".to_string(),
        };
        assert_eq!(format!("{row_parsing}"), "failed to parse row: test reason");
    }

    #[test]
    fn test_read_ohlcv_error_conversions() {
        // Test std::io::Error conversion
        let io_error = std::io::Error::new(std::io::ErrorKind::NotFound, "file not found");
        let ohlcv_error = OhlcvError::from(io_error);
        assert!(matches!(ohlcv_error, OhlcvError::IoError { .. }));

        // Test zip::result::ZipError conversion
        let zip_error = zip::result::ZipError::FileNotFound;
        let ohlcv_error = OhlcvError::from(zip_error);
        assert!(matches!(ohlcv_error, OhlcvError::ZipError { .. }));

        // Test chrono::ParseError conversion
        let date_str = "invalid date";
        let parse_result = NaiveDate::parse_from_str(date_str, "%d/%m/%Y");
        assert!(parse_result.is_err());
        let ohlcv_error = OhlcvError::from(parse_result.err().unwrap());
        assert!(matches!(ohlcv_error, OhlcvError::DateParseError { .. }));

        // Test rust_decimal::Error conversion
        let decimal_str = "not a number";
        let decimal_result = Decimal::from_str(decimal_str);
        assert!(decimal_result.is_err());
        let ohlcv_error = OhlcvError::from(decimal_result.err().unwrap());
        assert!(matches!(ohlcv_error, OhlcvError::DecimalParseError { .. }));
    }

    #[test]
    fn test_ohlcv_struct_serialization() {
        // Create a sample candle
        let candle = OhlcvCandle {
            date: NaiveDate::from_ymd_opt(2022, 1, 1).unwrap(),
            time: "10:00:00".to_string(),
            open: dec!(100.0),
            high: dec!(110.0),
            low: dec!(95.0),
            close: dec!(105.0),
            volume: 5000,
        };

        // Serialize to JSON
        let json = serde_json::to_string(&candle).unwrap();

        // Deserialize from JSON
        let deserialized: OhlcvCandle = serde_json::from_str(&json).unwrap();

        // Verify equality
        assert_eq!(candle.date, deserialized.date);
        assert_eq!(candle.time, deserialized.time);
        assert_eq!(candle.open, deserialized.open);
        assert_eq!(candle.high, deserialized.high);
        assert_eq!(candle.low, deserialized.low);
        assert_eq!(candle.close, deserialized.close);
        assert_eq!(candle.volume, deserialized.volume);
    }

    #[test]
    fn test_read_ohlcv_all_data_no_dates() -> Result<(), OhlcvError> {
        // Create test data
        let csv_data = "date;time;open;high;low;close;volume\n\
                    01/01/2022;10:00:00;100.0;110.0;95.0;105.0;5000\n\
                    02/01/2022;10:00:00;105.0;112.0;104.0;110.0;6000\n\
                    03/01/2022;10:00:00;110.0;115.0;108.0;114.0;7000";

        let (zip_path, _temp_file) = create_test_zip(csv_data)?;

        // Call our function without specifying any dates
        let candles = read_ohlcv_from_zip(&zip_path, None, None)?;

        // Verify results - should include all 3 candles
        assert_eq!(
            candles.len(),
            3,
            "Should return all 3 candles when no dates specified"
        );

        // Verify all candles are included
        assert_eq!(
            candles[0].date,
            NaiveDate::from_ymd_opt(2022, 1, 1).unwrap()
        );
        assert_eq!(
            candles[1].date,
            NaiveDate::from_ymd_opt(2022, 1, 2).unwrap()
        );
        assert_eq!(
            candles[2].date,
            NaiveDate::from_ymd_opt(2022, 1, 3).unwrap()
        );

        Ok(())
    }

    #[test]
    fn test_read_ohlcv_only_start_date() -> Result<(), OhlcvError> {
        // Create test data
        let csv_data = "date;time;open;high;low;close;volume\n\
                    01/01/2022;10:00:00;100.0;110.0;95.0;105.0;5000\n\
                    02/01/2022;10:00:00;105.0;112.0;104.0;110.0;6000\n\
                    03/01/2022;10:00:00;110.0;115.0;108.0;114.0;7000";

        let (zip_path, _temp_file) = create_test_zip(csv_data)?;

        // Call our function with only start date specified
        let candles = read_ohlcv_from_zip(&zip_path, Some("02/01/2022"), None)?;

        // Verify results - should include candles from 02/01/2022 onwards
        assert_eq!(
            candles.len(),
            2,
            "Should return 2 candles from start date onwards"
        );

        // Verify correct candles are included
        assert_eq!(
            candles[0].date,
            NaiveDate::from_ymd_opt(2022, 1, 2).unwrap()
        );
        assert_eq!(
            candles[1].date,
            NaiveDate::from_ymd_opt(2022, 1, 3).unwrap()
        );

        Ok(())
    }

    #[test]
    fn test_read_ohlcv_only_end_date() -> Result<(), OhlcvError> {
        // Create test data
        let csv_data = "date;time;open;high;low;close;volume\n\
                    01/01/2022;10:00:00;100.0;110.0;95.0;105.0;5000\n\
                    02/01/2022;10:00:00;105.0;112.0;104.0;110.0;6000\n\
                    03/01/2022;10:00:00;110.0;115.0;108.0;114.0;7000";

        let (zip_path, _temp_file) = create_test_zip(csv_data)?;

        // Call our function with only end date specified
        let candles = read_ohlcv_from_zip(&zip_path, None, Some("02/01/2022"))?;

        // Verify results - should include candles up to 02/01/2022
        assert_eq!(candles.len(), 2, "Should return 2 candles up to end date");

        // Verify correct candles are included
        assert_eq!(
            candles[0].date,
            NaiveDate::from_ymd_opt(2022, 1, 1).unwrap()
        );
        assert_eq!(
            candles[1].date,
            NaiveDate::from_ymd_opt(2022, 1, 2).unwrap()
        );

        Ok(())
    }

    #[test]
    fn test_read_ohlcv_invalid_start_date_format() {
        // Create test data
        let csv_data = "date;time;open;high;low;close;volume\n\
                    01/01/2022;10:00:00;100.0;110.0;95.0;105.0;5000";

        let (zip_path, _temp_file) = create_test_zip(csv_data).unwrap();

        // Call our function with invalid start date format
        let result = read_ohlcv_from_zip(&zip_path, Some("2022-01-01"), None);

        // Verify results
        assert!(
            result.is_err(),
            "Should return an error for invalid start date format"
        );
        if let Err(OhlcvError::DateParseError { .. }) = result {
            // This is expected
        } else {
            panic!("Expected DateParseError");
        }
    }

    #[test]
    fn test_read_ohlcv_invalid_end_date_format() {
        // Create test data
        let csv_data = "date;time;open;high;low;close;volume\n\
                    01/01/2022;10:00:00;100.0;110.0;95.0;105.0;5000";

        let (zip_path, _temp_file) = create_test_zip(csv_data).unwrap();

        // Call our function with invalid end date format
        let result = read_ohlcv_from_zip(&zip_path, None, Some("2022-01-01"));

        // Verify results
        assert!(
            result.is_err(),
            "Should return an error for invalid end date format"
        );
        if let Err(OhlcvError::DateParseError { .. }) = result {
            // This is expected
        } else {
            panic!("Expected DateParseError");
        }
    }

    #[test]
    fn test_read_ohlcv_no_matching_dates_with_only_start_date() -> Result<(), OhlcvError> {
        // Create test data
        let csv_data = "date;time;open;high;low;close;volume\n\
                    01/01/2022;10:00:00;100.0;110.0;95.0;105.0;5000\n\
                    02/01/2022;10:00:00;105.0;112.0;104.0;110.0;6000";

        let (zip_path, _temp_file) = create_test_zip(csv_data)?;

        // Call our function with start date after all available dates
        let candles = read_ohlcv_from_zip(&zip_path, Some("03/01/2022"), None)?;

        // Verify results
        assert_eq!(
            candles.len(),
            0,
            "Should return empty vector when no dates match the start date criteria"
        );

        Ok(())
    }

    #[test]
    fn test_read_ohlcv_no_matching_dates_with_only_end_date() -> Result<(), OhlcvError> {
        // Create test data
        let csv_data = "date;time;open;high;low;close;volume\n\
                    01/01/2022;10:00:00;100.0;110.0;95.0;105.0;5000\n\
                    02/01/2022;10:00:00;105.0;112.0;104.0;110.0;6000";

        let (zip_path, _temp_file) = create_test_zip(csv_data)?;

        // Call our function with end date before all available dates
        let candles = read_ohlcv_from_zip(&zip_path, None, Some("31/12/2021"))?;

        // Verify results
        assert_eq!(
            candles.len(),
            0,
            "Should return empty vector when no dates match the end date criteria"
        );

        Ok(())
    }
}