File size: 8,427 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
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
"""
Custom Loss Functions for Financial Time Series Prediction.

Includes:
- DirectionalMSELoss: Combined MSE + direction accuracy loss
- DirectionalLoss: Pure direction classification loss
"""

import torch
import torch.nn as nn
import torch.nn.functional as F


class DirectionalMSELoss(nn.Module):
    """
    Combined loss for price prediction with direction emphasis.
    
    Loss = (1 - alpha) * MSE + alpha * DirectionLoss
    
    Where DirectionLoss uses Binary Cross-Entropy for differentiable optimization:
    - d_i = 1 if target goes up, 0 if down
    - d̂_i = sigmoid(predicted_change) as probability of going up
    - L_dir = BCE(d̂_i, d_i)
    
    Args:
        direction_weight: Weight for direction loss component (default: 0.3)
    """
    
    def __init__(self, direction_weight: float = 0.3):
        super().__init__()
        self.direction_weight = direction_weight
        self.mse = nn.MSELoss()
        self.bce = nn.BCEWithLogitsLoss()
    
    def forward(self, pred: torch.Tensor, target: torch.Tensor) -> torch.Tensor:
        """
        Compute combined loss with differentiable direction component.
        
        Args:
            pred: [B, pred_len] predicted prices
            target: [B, pred_len] actual prices
            
        Returns:
            Combined loss value
        """
        # MSE component for magnitude prediction
        mse_loss = self.mse(pred, target)
        
        # Direction component using BCE (differentiable)
        # Compute price changes over prediction horizon
        pred_change = pred[:, -1] - pred[:, 0]  # Predicted change
        target_change = target[:, -1] - target[:, 0]  # True change
        
        # True direction: 1 if up, 0 if down
        target_direction = (target_change > 0).float()
        
        # BCE loss: pred_change as logits, target_direction as labels
        # sigmoid(pred_change) gives probability of going up
        direction_loss = self.bce(pred_change, target_direction)
        
        # Combined loss: balance MSE and direction
        total_loss = (1 - self.direction_weight) * mse_loss + self.direction_weight * direction_loss
        
        return total_loss


class DirectionalLoss(nn.Module):
    """
    Pure direction classification loss using cross-entropy.
    
    Converts regression outputs to binary classification (up/down).
    """
    
    def __init__(self):
        super().__init__()
        self.ce = nn.CrossEntropyLoss()
    
    def forward(self, pred: torch.Tensor, target: torch.Tensor) -> torch.Tensor:
        """
        Compute direction classification loss.
        
        Args:
            pred: [B, pred_len] predicted prices
            target: [B, pred_len] actual prices
            
        Returns:
            Cross-entropy loss for direction
        """
        # Convert to binary: 1 = up, 0 = down
        pred_change = pred[:, -1] - pred[:, 0]
        target_direction = (target[:, -1] > target[:, 0]).long()
        
        # Create logits from price change
        logits = torch.stack([
            -pred_change,  # Probability of down
            pred_change    # Probability of up
        ], dim=1)
        
        return self.ce(logits, target_direction)


class WeightedMSELoss(nn.Module):
    """
    Weighted MSE loss giving more importance to later predictions.
    
    Useful when later predictions are more important for trading decisions.
    """
    
    def __init__(self, weight_decay: float = 0.9):
        super().__init__()
        self.weight_decay = weight_decay
    
    def forward(self, pred: torch.Tensor, target: torch.Tensor) -> torch.Tensor:
        """
        Compute weighted MSE.
        
        Args:
            pred: [B, pred_len] predicted prices
            target: [B, pred_len] actual prices
            
        Returns:
            Weighted MSE loss
        """
        pred_len = pred.size(1)
        
        # Create exponentially increasing weights
        weights = torch.pow(
            torch.tensor(self.weight_decay),
            torch.arange(pred_len - 1, -1, -1, dtype=torch.float32)
        ).to(pred.device)
        
        # Normalize weights
        weights = weights / weights.sum()
        
        # Weighted MSE
        squared_errors = (pred - target) ** 2
        weighted_loss = (squared_errors * weights).sum(dim=1).mean()
        
        return weighted_loss


def compute_direction_accuracy(pred: torch.Tensor, target: torch.Tensor) -> float:
    """
    Compute direction accuracy as a metric.
    
    Args:
        pred: [B, pred_len] predicted prices
        target: [B, pred_len] actual prices
        
    Returns:
        Direction accuracy percentage (0-100)
    """
    pred_direction = torch.sign(pred[:, -1] - pred[:, 0])
    target_direction = torch.sign(target[:, -1] - target[:, 0])
    
    accuracy = (pred_direction == target_direction).float().mean().item() * 100
    return accuracy


def get_loss_function(loss_type: str, direction_weight: float = 0.3):
    """
    Get loss function by name.
    
    Args:
        loss_type: 'mse', 'mape', 'direction', 'directional_mse'
        direction_weight: Weight for directional loss
        
    Returns:
        Loss function
    """
    if loss_type == 'mse':
        return nn.MSELoss()
    elif loss_type == 'mape':
        return MAPELoss()
    elif loss_type == 'direction':
        return PureDirectionLoss()
    elif loss_type == 'directional_mse':
        return DirectionalMSELoss(direction_weight=direction_weight)
    else:
        raise ValueError(f"Unknown loss type: {loss_type}")


def compute_f1_score(pred: torch.Tensor, target: torch.Tensor) -> float:
    """
    Compute F1 score for direction prediction.
    
    Args:
        pred: [B, pred_len] predicted prices
        target: [B, pred_len] actual prices
        
    Returns:
        F1 score percentage (0-100)
    """
    pred_up = (pred[:, -1] > pred[:, 0])
    target_up = (target[:, -1] > target[:, 0])
    
    # True positives, false positives, false negatives
    tp = (pred_up & target_up).sum().float()
    fp = (pred_up & ~target_up).sum().float()
    fn = (~pred_up & target_up).sum().float()
    
    # Precision and recall
    precision = tp / (tp + fp + 1e-8)
    recall = tp / (tp + fn + 1e-8)
    
    # F1
    f1 = 2 * precision * recall / (precision + recall + 1e-8)
    
    return f1.item() * 100


class MAPELoss(nn.Module):
    """
    Mean Absolute Percentage Error Loss.
    
    MAPE = mean(|pred - target| / |target|) * 100
    """
    
    def __init__(self):
        super().__init__()
    
    def forward(self, pred: torch.Tensor, target: torch.Tensor) -> torch.Tensor:
        """
        Compute MAPE loss.
        
        Args:
            pred: [B, pred_len] predicted prices
            target: [B, pred_len] actual prices
            
        Returns:
            MAPE loss value
        """
        return torch.mean(torch.abs((pred - target) / (target + 1e-8)))


class PureDirectionLoss(nn.Module):
    """
    Pure direction loss without price prediction.
    
    Only optimizes for correct direction prediction (up/down).
    Uses a differentiable approximation of direction accuracy.
    """
    
    def __init__(self):
        super().__init__()
    
    def forward(self, pred: torch.Tensor, target: torch.Tensor) -> torch.Tensor:
        """
        Compute pure direction loss using differentiable formulation.
        
        Args:
            pred: [B, pred_len] predicted prices
            target: [B, pred_len] actual prices
            
        Returns:
            Direction loss (lower is better)
        """
        # Calculate changes (differentiable)
        pred_change = pred[:, -1] - pred[:, 0]
        target_change = target[:, -1] - target[:, 0]
        
        # Direction loss: penalize when signs differ
        # Use negative correlation as loss: -sign(pred) * sign(target)
        # When same sign: -1*1=-1 or -(-1)*(-1)=-1 (good, negative loss)
        # When diff sign: -1*(-1)=1 or -(-1)*1=1 (bad, positive loss)
        direction_loss = -torch.sign(pred_change) * torch.sign(target_change)
        
        # Add MSE of the change magnitude to keep gradients flowing
        magnitude_loss = F.mse_loss(pred_change, target_change)
        
        # Combine: direction is primary, magnitude helps gradients
        return direction_loss.mean() + 0.1 * magnitude_loss