SharpeLoss

Defined in fynance.models.loss

class SharpeLoss(rf=0., period=252, eps=1e-8)[source]

Bases: BaseLoss

Negative Sharpe ratio as a differentiable loss.

Minimizing this loss is equivalent to maximizing the Sharpe ratio of the predicted return series. All operations are pure PyTorch, so gradients flow through forward without any NumPy conversion.

Parameters:
rffloat, optional

Annualized risk-free rate. Default is 0.

periodint, optional

Number of periods per year. Default is 252.

epsfloat, optional

Numerical stabilizer. Default is 1e-8.

See also

SortinoLoss, DirectionalAccuracyLoss

Notes

The loss is defined as:

\[\mathcal{L} = -\frac{\mu(r - rf_p)}{\sigma(r - rf_p) + \varepsilon}\]

where \(r\) is y_pred, \(rf_p = rf / period\) is the per-period risk-free rate, \(\mu\) and \(\sigma\) are the mean and population standard deviation (correction=0, consistent with sharpe), and \(\varepsilon\) is the numerical stabilizer (eps).

This is a training proxy — the value is not comparable to the numpy sharpe evaluation metric, which annualizes over a price series.

Examples

>>> import torch
>>> from fynance.models.loss import SharpeLoss
>>> torch.manual_seed(0)
<...>
>>> returns = torch.randn(50) * 0.01 + 0.001
>>> loss_fn = SharpeLoss()
>>> loss = loss_fn(returns)
>>> loss.shape
torch.Size([])
>>> loss.item() < 0       # positive mean excess return → negative loss
True

Using with MultiLayerPerceptron:

>>> from fynance.models import MultiLayerPerceptron, SharpeLoss
>>> import torch.optim
>>> X = torch.randn(100, 4)
>>> y = torch.randn(100, 1)
>>> model = MultiLayerPerceptron(X, y, layers=[16])
>>> _ = model.set_optimizer(SharpeLoss, torch.optim.Adam, lr=1e-3)
>>> loss = model.train_on(X, y)
>>> loss.shape
torch.Size([])
forward(y_pred, y_true=None)[source]

Compute the negative Sharpe ratio.

Parameters:
y_predtorch.Tensor

Predicted return series, shape (T,) or (T, M).

y_truetorch.Tensor, optional

Not used; accepted for API compatibility with PyTorch criterions.

Returns:
torch.Tensor

Scalar loss value (negative Sharpe ratio).

Raises:
TypeError

If y_pred is not a torch.Tensor.