File size: 2,675 Bytes
8481f3c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import os
import pandas as pd
from tqdm import tqdm

def validate_csv(filepath):
    """Updated validation with more flexible timestamp checking"""
    try:
        df = pd.read_csv(filepath)
        
        # Basic checks
        assert not df.empty, "Empty DataFrame"
        required_columns = {'timestamp', 'open', 'high', 'low', 'close', 'volume'}
        assert required_columns.issubset(df.columns), f"Missing columns: {required_columns - set(df.columns)}"
        
        # Data quality checks
        duplicates = df.duplicated().sum()
        assert duplicates == 0, f"{duplicates} duplicates found"
        
        nulls = df.isnull().sum().sum()
        assert nulls == 0, f"{nulls} null values found"
        
        # Convert timestamps
        df['timestamp'] = pd.to_datetime(df['timestamp'])
        
        # Check OHLC relationships
        assert (df['high'] >= df['low']).all(), "High < Low found"
        assert (df['high'] >= df['open']).all(), "High < Open found"
        assert (df['high'] >= df['close']).all(), "High < Close found"
        assert (df['low'] <= df['open']).all(), "Low > Open found"
        assert (df['low'] <= df['close']).all(), "Low > Close found"
        
        # Check for major gaps in timeline (more flexible than strict order)
        time_diff = df['timestamp'].diff().dt.total_seconds()
        if (time_diff < 0).any():
            print(f"Warning: {filepath} has {sum(time_diff < 0)} timestamp decreases")
        
        return True, "Validation passed with warnings"
    
    except Exception as e:
        return False, str(e)

def validate_dataset(data_dir="data"):
    """Validate all CSV files in a directory."""
    results = {}
    
    for root, _, files in os.walk(data_dir):
        for file in tqdm(files, desc="Validating files"):
            if file.endswith('.csv'):
                filepath = os.path.join(root, file)
                is_valid, message = validate_csv(filepath)
                results[file] = {
                    "valid": is_valid,
                    "message": message,
                    "path": filepath
                }
    
    # Print summary
    print("\nValidation Summary:")
    print("-" * 50)
    for file, result in results.items():
        status = "PASSED" if result["valid"] else "FAILED"
        print(f"{file:<50} {status:<10} {result['message']}")
    
    return results

if __name__ == "__main__":
    # Example usage
    validation_results = validate_dataset()
    
    # Save validation report
    pd.DataFrame.from_dict(validation_results, orient='index').to_csv("validation_report.csv")
    print("\nValidation report saved to validation_report.csv")