Metrics module¶
Some tools to compute financial metrics.
fynance.tools.metrics.accuracy (y_true, y_pred) |
Compute the accuracy of prediction. |
fynance.tools.metrics.calmar (series[, period]) |
Compute the Calmar Ratio [1]. |
fynance.tools.metrics.diversified_ratio (series) |
Compute diversification ratio of a portfolio. |
fynance.tools.metrics.drawdown (series) |
Measures the drawdown of series. |
fynance.tools.metrics.mad (series) |
Compute the Mean Absolute Deviation. |
fynance.tools.metrics.mdd (series) |
Compute the maximum drwdown. |
fynance.tools.metrics.perf_index (series[, base]) |
Compute performance of prices or index values along time axis. |
fynance.tools.metrics.perf_returns (returns) |
Compute performance of returns along time axis. |
fynance.tools.metrics.roll_calmar (series[, …]) |
Compute the rolling Calmar ratio [1]. |
fynance.tools.metrics.roll_mad (series[, win]) |
Compute rolling Mean Absolut Deviation. |
fynance.tools.metrics.roll_sharpe (series[, …]) |
Compute rolling sharpe ratio [6]. |
fynance.tools.metrics.roll_z_score (series[, …]) |
Compute vector of rolling/moving Z-score function. |
fynance.tools.metrics.sharpe (series[, …]) |
Compute the Sharpe ratio [6]. |
fynance.tools.metrics.z_score (series[, kind_ma]) |
Compute Z-score function. |
Scalar functions¶
The following functions return a scalar.
-
fynance.tools.metrics.
accuracy
(y_true, y_pred, sign=True)¶ Compute the accuracy of prediction.
Parameters: - y_true : np.ndarray[ndim=1, dtype=np.float64]
Vector of true series.
- y_pred : np.ndarray[ndim=1, dtype=np.float64]
Vector of predicted series.
- sign : bool, optional
Check sign accuracy if true, else check exact accuracy, default is True.
Returns: - float
Accuracy of prediction as float between 0 and 1.
Examples
>>> y_true = np.array([1., .5, -.5, .8, -.2]) >>> y_pred = np.array([.5, .2, -.5, .1, .0]) >>> accuracy(y_true, y_pred) 0.8 >>> accuracy(y_true, y_pred, sign=False) 0.2
-
fynance.tools.metrics.
calmar
(series, period=252)¶ Compute the Calmar Ratio [1].
Parameters: - series : np.ndarray[np.float64, ndim=1]
Time series (price, performance or index).
- period : int, optional
Number of period per year, default is 252 (trading days).
Returns: - np.float64
Value of Calmar ratio.
See also
Notes
It is the compouned annual return over the Maximum DrawDown.
References
[1] (1, 2) https://en.wikipedia.org/wiki/Calmar_ratio Examples
Assume a series of monthly prices:
>>> series = np.array([70, 100, 80, 120, 160, 80]) >>> calmar(series, period=12) 0.6122448979591835
-
fynance.tools.metrics.
diversified_ratio
(series, w=None, std_method='std')¶ Compute diversification ratio of a portfolio.
Parameters: - series : np.array[ndim=2, dtype=np.float64] of shape (T, N)
Portfolio matrix of N assets and T time periods, each column correspond to one series of prices.
- w : np.array[ndim=1 or 2, dtype=np.float64] of size N, optional
Vector of weights, default is None it means it will equaly weighted.
- std_method : str, optional /!\ Not yet implemented /!\
Method to compute variance vector and covariance matrix.
Returns: - np.float64
Value of diversification ratio of the portfolio.
Notes
Diversification ratio, denoted D, is defined as the ratio of the portfolio’s weighted average volatility to its overll volatility, developed by Choueifaty and Coignard [2].
\[D(P) = \frac{P' \Sigma}{\sqrt{P'VP}}\]With \(\Sigma\) vector of asset volatilities, \(P\) vector of weights of asset of portfolio, and \(V\) matrix of variance-covariance of these assets.
References
[2] tobam.fr/wp-content/uploads/2014/12/TOBAM-JoPM-Maximum-Div-2008.pdf
-
fynance.tools.metrics.
mad
(series)¶ Compute the Mean Absolute Deviation.
Compute the mean of the absolute value of the distance to the mean [4].
Parameters: - series : np.ndarray[np.float64, ndim=1]
Time series (price, performance or index).
Returns: - np.float64
Value of mean absolute deviation.
See also
References
[4] https://en.wikipedia.org/wiki/Average_absolute_deviation Examples
>>> series = np.array([70., 100., 90., 110., 150., 80.]) >>> mad(series) 20.0
-
fynance.tools.metrics.
mdd
(series)¶ Compute the maximum drwdown.
Drawdown is the measure of the decline from a historical peak in some variable [5] (typically the cumulative profit or total open equity of a financial trading strategy).
Parameters: - series : np.ndarray[np.float64, ndim=1]
Time series (price, performance or index).
Returns: - np.float64
Value of Maximum DrawDown.
References
[5] https://www.investopedia.com/terms/m/maximum-drawdown-mdd.asp Examples
>>> series = np.array([70, 100, 80, 120, 160, 80]) >>> mdd(series) 0.5
-
fynance.tools.metrics.
sharpe
(series, period=252, log=False)¶ Compute the Sharpe ratio [6].
Parameters: - series : numpy.ndarray(dim=1, dtype=float)
Prices of the index.
- period : int, optional
Number of period per year, default is 252 (trading days).
- log : bool, optional
If true compute sharpe with the formula for log-returns, default is False.
Returns: - np.float64
Value of Sharpe ratio.
See also
Notes
It is computed as the total return over the volatility (we assume no risk-free rate) such that:
\[\text{Sharpe ratio} = \frac{E(r)}{\sqrt{Var(r)}}\]References
[6] (1, 2) https://en.wikipedia.org/wiki/Sharpe_ratio Examples
Assume a series of monthly prices:
>>> series = np.array([70, 100, 80, 120, 160, 80]) >>> sharpe(series, period=12) 0.22494843872918127
-
fynance.tools.metrics.
z_score
(series, kind_ma='sma', **kwargs)¶ Compute Z-score function.
Parameters: - series : np.ndarray[np.float64, ndim=1]
Series of index, prices or returns.
- kind_ma : {‘ema’, ‘sma’, ‘wma’}
Kind of moving average/standard deviation, default is ‘sma’. - Exponential moving average if ‘ema’. - Simple moving average if ‘sma’. - Weighted moving average if ‘wma’.
- **kwargs
Any parameters for the moving average function.
Returns: - float
Value of Z-score.
See also
Notes
Compute the z-score function for a specific average and standard deviation function such that:
\[z = \frac{series_t - \mu_t}{\sigma_t}\]Where \(\mu_t\) is the average and \(\sigma_t\) is the standard deviation.
Examples
>>> series = np.array([70, 100, 80, 120, 160, 80]) >>> z_score(series, kind_ma='ema') -0.009636022213064485 >>> z_score(series, lags=3) -1.224744871391589
Vectorized functions¶
The following functions return a vector.
-
fynance.tools.metrics.
drawdown
(series)¶ Measures the drawdown of series.
Function to compute measure of the decline from a historical peak in some variable [3] (typically the cumulative profit or total open equity of a financial trading strategy).
Parameters: - series : np.ndarray[np.float64, ndim=1]
Time series (price, performance or index).
Returns: - np.ndarray[np.float64, ndim=1]
Series of DrawDown.
References
[3] https://en.wikipedia.org/wiki/Drawdown_(economics) Examples
>>> series = np.array([70, 100, 80, 120, 160, 80]) >>> drawdown(series) array([0. , 0. , 0.2, 0. , 0. , 0.5])
-
fynance.tools.metrics.
perf_index
(series, base=100.0)¶ Compute performance of prices or index values along time axis.
Parameters: - series : np.ndarray[ndim=1, dtype=np.float64]
Time-series of prices or index values.
- base : float, optional
Initial value for measure the performance, default is 100.
Returns: - np.ndarray[ndim=1, dtype=np.float64]
Performances along time axis.
See also
perf_returns
,perf_strat
Examples
>>> series = np.array([10., 12., 15., 14., 16., 18., 16.]) >>> perf_index(series, base=100.) array([100., 120., 150., 140., 160., 180., 160.])
-
fynance.tools.metrics.
perf_returns
(returns, log=False, base=100.0)¶ Compute performance of returns along time axis.
Parameters: - returns : np.ndarray[ndim=1, dtype=np.float64]
Time-series of returns.
- log : bool, optional
Considers returns as log-returns if True. Default is False.
- base : float, optional
Initial value for measure the performance, default is 100.
Returns: - np.ndarray[ndim=1, dtype=np.float64]
Performances along time axis.
See also
perf_index
,perf_strat
Examples
>>> returns = np.array([0., 20., 30., -10., 20., 20., -20.]) >>> perf_returns(returns, base=100., log=False) array([100., 120., 150., 140., 160., 180., 160.])
-
fynance.tools.metrics.
roll_calmar
(series, period=252.0)¶ Compute the rolling Calmar ratio [1].
It is the compouned annual return over the rolling Maximum DrawDown.
Parameters: - series : np.ndarray[np.float64, ndim=1]
Time series (price, performance or index).
- period : int, optional
Number of period per year, default is 252 (trading days).
- win : int, optional /! NOT YET WORKING /!
Size of the rolling window. If less of two, rolling calmar is compute on all the past. Default is 0.
Returns: - np.ndarray[np.float64, ndim=1]
Series of rolling Calmar ratio.
See also
roll_mdd
,roll_sharpe
,calmar
References
[1] (1, 2) https://en.wikipedia.org/wiki/Calmar_ratio Examples
Assume a monthly series of prices:
>>> series = np.array([70, 100, 80, 120, 160, 80]) >>> roll_calmar(series, period=12) array([ 0. , 0. , 3.52977926, 20.18950437, 31.35989887, 0.6122449 ])
-
fynance.tools.metrics.
roll_mad
(series, win=0)¶ Compute rolling Mean Absolut Deviation.
Compute the moving average of the absolute value of the distance to the moving average [4].
Parameters: - series : np.ndarray[np.float64, ndim=1]
Time series (price, performance or index).
Returns: - np.ndarray[np.float64, ndim=1]
Series of mean absolute deviation.
See also
References
[4] https://en.wikipedia.org/wiki/Average_absolute_deviation Examples
>>> series = np.array([70., 100., 90., 110., 150., 80.]) >>> roll_mad(series) array([ 0. , 15. , 11.11111111, 12.5 , 20.8 , 20. ])
-
fynance.tools.metrics.
roll_sharpe
(series, period=252, win=0, cap=True)¶ Compute rolling sharpe ratio [6].
It is the rolling compouned annual returns divided by rolling annual volatility.
Parameters: - series : np.ndarray[dtype=np.float64, ndim=1]
Financial series of prices or indexed values.
- period : int, optional
Number of period in a year, default is 252 (trading days).
- win : int, optional
Size of the rolling window. If less of two, rolling sharpe is compute on all the past. Default is 0.
- cap : bool, optional
Cap extram values (some time due to small size window), default is True.
Returns: - np.ndarray[np.float64, ndim=1]
Serires of rolling Sharpe ratio.
See also
roll_calmar
,sharpe
,roll_mdd
References
[6] (1, 2) https://en.wikipedia.org/wiki/Sharpe_ratio Examples
Assume a monthly series of prices:
>>> series = np.array([70, 100, 80, 120, 160, 80]) >>> roll_sharpe(series, period=12) array([0. , 0. , 0.77721579, 3.99243019, 6.754557 , 0.24475518])
-
fynance.tools.metrics.
roll_z_score
(series, kind_ma='sma', **kwargs)¶ Compute vector of rolling/moving Z-score function.
Parameters: - series : np.ndarray[np.float64, ndim=1]
Series of index, prices or returns.
- kind_ma : {‘ema’, ‘sma’, ‘wma’}
Kind of moving average/standard deviation, default is ‘sma’. - Exponential moving average if ‘ema’. - Simple moving average if ‘sma’. - Weighted moving average if ‘wma’.
- **kwargs
Any parameters for the moving average function.
Returns: - np.ndarray[np.float64, ndim=1]
Vector of Z-score at each period.
See also
z_score
,roll_mdd
,roll_calmar
,roll_mad
,roll_sharpe
Notes
Compute for each observation the z-score function for a specific moving average function such that:
\[z = \frac{seres - \mu_t}{\sigma_t}\]Where \(\mu_t\) is the moving average and \(\sigma_t\) is the moving standard deviation.
Examples
>>> series = np.array([70, 100, 80, 120, 160, 80]) >>> roll_z_score(series, kind_ma='ema') array([ 0. , 3.83753384, 1.04129457, 3.27008748, 3.23259291, -0.00963602]) >>> roll_z_score(series, lags=3) array([ 0. , 1. , -0.26726124, 1.22474487, 1.22474487, -1.22474487])