Metric

usage: metric [-m {volatility,sharpe,sortino,maxdrawdown,rsquare,skew,kurtosis,gaintopain,trackerr,information,tail,commonsense,jensens,calmar,kelly,payoff,profitfactor}] [-r RISK_FREE_RATE] [-h] [--export EXPORT]

Display metric of choice for different periods

optional arguments:
  -m {volatility,sharpe,sortino,maxdrawdown,rsquare,skew,kurtosis,gaintopain,trackerr,information,tail,commonsense,jensens,calmar,kelly,payoff,profitfactor}, --metric {volatility,sharpe,sortino,maxdrawdown,rsquare,skew,kurtosis,gaintopain,trackerr,information,tail,commonsense,jensens,calmar,kelly,payoff,profitfactor}
                        Set metric of choice (default: False)
  -r RISK_FREE_RATE, --rfr RISK_FREE_RATE
                        Set risk free rate for calculations. (default: 0.0)
  -h, --help            show this help message (default: False)
  --export EXPORT       Export raw data into csv, json, xlsx (default: )

E.g. metric sharpe

Sharpe ratio for Portfolio and Benchmark
┏━━━━━┳━━━━━━━━━━━┳━━━━━━━━━━━┓
┃     ┃ Portfolio ┃ Benchmark ┃
┡━━━━━╇━━━━━━━━━━━╇━━━━━━━━━━━┩
│ mtd │ -0.057    │ -0.027    │
├─────┼───────────┼───────────┤
│ qtd │ -0.220    │ -0.172    │
├─────┼───────────┼───────────┤
│ ytd │ -0.123    │ -0.098    │
├─────┼───────────┼───────────┤
│ 3m  │ -0.103    │ -0.052    │
├─────┼───────────┼───────────┤
│ 6m  │ -0.127    │ -0.070    │
├─────┼───────────┼───────────┤
│ 1y  │ -0.038    │ 0.007     │
├─────┼───────────┼───────────┤
│ 3y  │ 0.018     │ 0.044     │
├─────┼───────────┼───────────┤
│ 5y  │ 0.025     │ 0.046     │
├─────┼───────────┼───────────┤
│ 10y │ 0.026     │ 0.056     │
├─────┼───────────┼───────────┤
│ all │ 0.024     │ 0.050     │
└─────┴───────────┴───────────┘

Below provides an explanation of the metric available. Full credit go to the sources that are linked here, we merely replicate their findings.

Name

Definition

Formula

Tracking Error

Tracking error is the divergence between the price behavior of a position or a portfolio and the price behavior of a benchmark. This is often in the context of a hedge fundmutual fund, or exchange-traded fund (ETF) that did not work as effectively as intended, creating an unexpected profit or loss.

Tracking Error = Standard Deviation of (P - B)

Where P is Portfolio and B is Benchmark

Information Ratio (IR)

The information ratio (IR) is a measurement of portfolio returns beyond the returns of a benchmark, usually an index, compared to the volatility of those returns. The benchmark used is typically an index that represents the market or a particular sector or industry.

Tracking Error = (Portfolio Return - Benchmark Return) / Tracking Error

Tracking Error formula is described above.

Sharpe Ratio

The ratio is the average return earned in excess of the risk-free rate per unit of volatility or total risk. Volatility is a measure of the price fluctuations of an asset or portfolio.

Sharpe Ratio = (Return of the Portfolio - Return on Risk Free asset) / Standard deviation of the Portfolio

Risk-free asset is usually a long-term treasury bond and often 0%.

Sortino Ratio

The Sortino ratio is a variation of the Sharpe ratio that differentiates harmful volatility from total overall volatility by using the asset's standard deviation of negative portfolio returns—downside deviation—instead of the total standard deviation of portfolio returns.

Sortino Rate = (Return of the Portfolio - Return on Risk Free asset) / Standard deviation of the downside Portfolio

Note that he only difference with Sharpe Ratio is that you only consider downside volatility (decreases in value).

Tail Ratio

Mean reversion strategies have low volatility, consistent performance and high Sharpe ratio. On the surface, they are what investors look for. The problem is mean reverting strategies work well, until they don’t. Big losses are unpredictable. LTCM had a great Sharpe ratio, at least until October 15th, 1987… Risk is in the left tail. The best metric for mean reverting strategies is therefore: tail ratio. Tail ratio measures what happens at the ends of both tails.

Tail ratio  = percentile(returns, 95%) / percentile(returns, 5%)

Gain-to-pain ratio

The gain-to-pain ratio for an investor who wants an annual return of 10% and is willing to tolerate a maximum drawdown of 20% is 0.5. An investor expecting an annual return of 15% with a drawdown of 50% has a gain-to-pain ratio of 0.3.

Allow for both user input and actual calculation based on the portfolio and benchmark history.

Gain-to-pain-ratio = desired return / maximum tolerable drawdown

This ratio can be calculated based on historic data of the portfolio and the maximum drawdown. The investor itself can, based on his own expectations and maximum tolerable drawdown decide if this is what he is comfortable with.

Common Sense Ratio

Regardless of the asset class, there are only two types of strategy: mean reversion or trend following. They both have different risk profiles. Common Sense Ratio recaptures the risks associated with both mean reversion and trend following strategies. An alternative to Sharpe Ratio.

Common Sense Ratio = tail ratio * gain to pain ratio

The formulas to these ratios can be found above.

Maximum Drawdown (MDD)

A maximum drawdown (MDD) is the maximum observed loss from a peak to a through of a portfolio, before a new peak is attained. Maximum drawdown is an indicator of downside risk over a specified time period.

Maximum Drawdown = (through - Peak) / Peak

through is defined as the minimum of the portfolio (e.g. from 750k to 350k)

Peak is defined as the maximum of the portfolio (e.g. 750k) before the through. For example an increase to 800k after the 350k is not the peak.

Volatility

Volatility is a statistical measure of the dispersion of returns for a given security or market index. In most cases, the higher the volatility, the riskier the security. Volatility is often measured as either the standard deviation or variance between returns from that same security or market index.

You can simply use .std commands but below explains what actually happens:

  1. Calculate the mean, Mean = average of all stock prices

  2. Determine deviations, deviation = stock price minus mean

  3. Square the deviations, deviation_squared = deviation ** 2

  4. Sum the deviations, sum_of_squared_deviations = sum(deviation_squared)

  5. Determine variance, variance = sum_of_squared_deviations / total amount of stock prices

  6. Determine standard deviation, standard_deviation = root of variance

R-squared

In investing, R-squared is generally interpreted as the percentage of a fund or security's movements that can be explained by movements in a benchmark index.

Requires the use of a simple linear regression model. Please see the Investopedia page: What Is R-Squared?

Beta

Beta, primarily used in the capital asset pricing model (CAPM), is a measure of the volatility–or systematic risk–of a security or portfolio compared to the market (= benchmark) as a whole. By definition, the benchmark beta is 1.

Beta = covariance of return of portfolio and benchmark / variance of benchmark

Covariance is calculated by the sum of the deviations of the portfolio times that of the benchmark divided by the the amount of stock prices - 1. See: Covariance

Jensen’s Alpha (also see Alpha)

The Jensen's measure, or Jensen's alpha, is a risk-adjusted performance measure that represents the average return on a portfolio or investment, above or below that predicted by the capital asset pricing model (CAPM), given the portfolio's or investment's beta and the average market return. This metric is also commonly referred to as simply alpha.

Jensen's alpha = return of the portfolio - (return on the risk free rate + the beta of the portfolio times (the return on the benchmark minus the return on the risk free rate))

For example 15% - (3% + 1.2 x (12% - 3%)) = 15% - 13.8% = 1.2% which means, adjusted for risk, the portfolio manager added value.

Calmar Ratio

It is a function of the fund's average compounded annual rate of return versus its maximum drawdown. The higher the Calmar ratio, the better it performed on a risk-adjusted basis during the given time frame, which is mostly commonly set at 36 months.

Calmar Ratio = annual return / maximum drawdown

Kelly Criterion

The formula is used by investors who want to trade with the objective of growing capital, and it assumes that the investor will reinvest profits and put them at risk for future trades. The goal of the formula is to determine the optimal amount to put into any one trade.

Kelly Criterion = W - (1 - W) / R

Where W is historical "wins" (percentage of returns that are positive). This can be based on the historical data.

Where R is trader "wins" (percentage of returns that are positive of the trader). This can be based on the orderbook

Risk of Ruin (also see Risk of ruin )

Risk of ruin is the probability that an individual will lose substantial amounts of money through investing, trading, or gambling—to the point where it is no longer possible to recover the losses or continue.

For a random walk with a starting value of s, and at every iterative step, is moved by a normal distribution having mean μ and standard deviation σ and failure occurs if it reaches 0 or a negative value.

Value at Risk (VaR)

Value at risk (VaR) is a statistic that quantifies the extent of possible financial losses within a firm, portfolio, or position over a specific time frame.

Create a normal distribution of the daily returns and take the 1th, 2.5th, 5th and 10th percentile.

Conditional Value at Risk (CVaR) or Expected Shortfall (ES)

Conditional Value at Risk (CVaR), also known as the expected shortfall, is a risk assessment measure that quantifies the amount of tail risk an investment portfolio has. CVaR is derived by taking a weighted average of the “extreme” losses in the tail of the distribution of possible returns, beyond the value at risk (VaR) cutoff point.

Take the weighted average of all occurrences that go past VaR percentile. This number will be by definition higher than that of VaR.

Payoff Ratio

The payoff ratio is defined as the average winner per trade divided by the average loser per trade for a trading system. The higher the payoff ratio the better the trading system performs. 


Profit Factor

The profit factor is the gross profit of a trading system divided by the gross loss of a trading system. Simply put. it’s the total amount of money you win divided by the total amount of money you lost.