File size: 1,922 Bytes
3621f16
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""
Complete Evaluation Metrics Module (v2).

Includes: MSE, MAE, MAPE, RMSE, Direction Accuracy, IC, R-squared.
"""
import numpy as np


def compute_all_metrics(pred, true):
    """
    Compute all evaluation metrics.
    
    Args:
        pred, true: [B, pred_len] or [B]
        
    Returns:
        dict: All metrics
    """
    pred = np.array(pred).flatten()
    true = np.array(true).flatten()
    
    # Basic metrics
    mse = np.mean((pred - true) ** 2)
    mae = np.mean(np.abs(pred - true))
    rmse = np.sqrt(mse)
    
    # MAPE (Mean Absolute Percentage Error)
    # Note: For normalized log returns near 0, MAPE is not suitable
    # Use: only compute MAPE for samples with |true| > 0.1
    mask = np.abs(true) > 0.1
    if mask.sum() > 0:
        mape = np.mean(np.abs((pred[mask] - true[mask]) / true[mask])) * 100
    else:
        mape = np.nan  # No valid samples
    
    # Direction Accuracy (up/down prediction)
    direction_acc = np.mean((np.sign(pred) == np.sign(true)).astype(float)) * 100
    
    # IC (Information Coefficient, commonly used in finance)
    ic = np.corrcoef(pred, true)[0, 1]
    
    # R-squared (coefficient of determination)
    ss_res = np.sum((true - pred) ** 2)
    ss_tot = np.sum((true - np.mean(true)) ** 2)
    r2 = 1 - ss_res / (ss_tot + 1e-8)
    
    # Maximum error
    max_error = np.max(np.abs(pred - true))
    
    return {
        'mse': mse,
        'mae': mae,
        'rmse': rmse,
        'mape': mape,
        'direction_acc': direction_acc,
        'ic': ic,
        'r2': r2,
        'max_error': max_error
    }


def print_metrics(metrics, prefix=''):
    """Format and print metrics."""
    print(f"{prefix}MSE: {metrics['mse']:.4f} | MAE: {metrics['mae']:.4f} | RMSE: {metrics['rmse']:.4f} | MAPE: {metrics['mape']:.2f}%")
    print(f"{prefix}Direction Acc: {metrics['direction_acc']:.2f}% | IC: {metrics['ic']:.4f} | R2: {metrics['r2']:.4f}")