Download src/utils/losses_old_backup.py from GoldenGrapeGentleman1/FinMM-Project-FinMM: direct link, hf CLI and curl.
- Browser
- Download file 8.25 kB
-
https://huggingface.co/GoldenGrapeGentleman1/FinMM-Project-FinMM/resolve/main/src/utils/losses_old_backup.py
- Command line
-
hf download hf://GoldenGrapeGentleman1/FinMM-Project-FinMM/src/utils/losses_old_backup.py
-
curl -L -o losses_old_backup.py https://huggingface.co/GoldenGrapeGentleman1/FinMM-Project-FinMM/resolve/main/src/utils/losses_old_backup.py
8.25 kB
| """ | |
| 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 = MSE + alpha * DirectionLoss | |
| Where DirectionLoss penalizes incorrect direction predictions: | |
| - If predicted direction != actual direction, add penalty | |
| 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() | |
| def forward(self, pred: torch.Tensor, target: torch.Tensor) -> torch.Tensor: | |
| """ | |
| Compute combined loss. | |
| Args: | |
| pred: [B, pred_len] predicted prices | |
| target: [B, pred_len] actual prices | |
| Returns: | |
| Combined loss value | |
| """ | |
| # MSE component | |
| mse_loss = self.mse(pred, target) | |
| # Direction component: compare first vs last prediction | |
| pred_direction = torch.sign(pred[:, -1] - pred[:, 0]) | |
| target_direction = torch.sign(target[:, -1] - target[:, 0]) | |
| # Direction mismatch penalty (0 if correct, 1 if wrong) | |
| direction_mismatch = (pred_direction != target_direction).float() | |
| direction_loss = direction_mismatch.mean() | |
| # Combined loss | |
| total_loss = 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 |