Metrics
Metrics.METRICS
— ConstantAll the metrics that supported.
Metrics.TradesTuple
— TypeA NamedTuple representing trade data, including date
, amount
, price
, value
, fees
, fees_base
, size
, leverage
, entryprice
, and order
.
Metrics._annualize
— MethodAnnualizes a volatility value.
_annualize(v, tf)
This function takes a volatility value v
and a timeframe tf
as parameters. It multiplies v
by the square root of the ratio of the number of days in a year times the period of tf
to the period of a day. This effectively converts v
from a volatility per tf
period to an annual volatility.
Metrics._cum_value_balance
— MethodCalculates the cumulative value balance for a MarginInstance.
_cum_value_balance(
ai::Instances.AssetInstance{<:AbstractAsset, <:ExchangeID, M} where M<:Misc.WithMargin,
df
) -> Any
This function takes a MarginInstance
ai
and a DataFrame df
as parameters. It defines a helper function cvb
that calculates the value of an order based on various parameters, and updates some variables (last_lev
, last_ep
, last_side
) with the details of the last non-missing order.
The function then applies cvb
to each order in df
, along with the corresponding ai
, entryprice
, cum_base
, leverage
, and close
values from df
. The earned amounts for each order are returned as a vector.
Metrics._earned
— FunctionCalculates the earned amount in a trade considering entryprice
, amount
, leverage
, price
, and fees
.
_earned(
o,
entryprice,
amount,
leverage,
price,
value,
fees
) -> Any
_earned(
o,
entryprice,
amount,
leverage,
price,
value,
fees,
fees_base
) -> Any
The function computes the earned amount as the absolute value of the product of entryprice
and amount
divided by leverage
, plus the profit and loss (pnl) calculated from the entryprice
, price
, amount
, and the position side of the order, minus fees
.
Metrics._rawcalmar
— MethodComputes the non-annualized Calmar ratio.
_rawcalmar(returns; tf) -> Any
Calculates the Calmar ratio given an array of returns
. The ratio is the annual return divided by the maximum drawdown. tf
specifies the timeframe for the returns and defaults to one day.
Metrics._rawexpectancy
— MethodComputes the trading expectancy.
_rawexpectancy(returns) -> Any
Calculates the trading expectancy given an array of returns
. This is a measure of the mean value of both winning and losing trades. It takes into account both the probability and the average win/loss of trades.
Metrics._rawsharpe
— MethodComputes the non-annualized Sharpe ratio.
_rawsharpe(returns; rfr, tf) -> Any
Calculates the Sharpe ratio given an array of returns
. The ratio is computed as the excess of the mean return over the risk-free rate rfr
, divided by the standard deviation of the returns
. tf
specifies the timeframe for the returns and defaults to one day.
Metrics._rawsortino
— MethodComputes the non-annualized Sortino ratio.
_rawsortino(returns; rfr, tf) -> Any
Calculates the Sortino ratio given an array of returns
. The ratio is the excess of the mean return over the risk-free rate rfr
, divided by the standard deviation of the negative returns
. tf
specifies the timeframe for the returns and defaults to one day.
Metrics._returns_arr
— MethodCalculates the simple returns for an array of prices.
_returns_arr(arr)
This function takes an array of prices arr
as a parameter, calculates the differences between successive prices, divides each difference by the corresponding previous price, and returns the resulting array of simple returns. Please note that the first element of the return array would be NaN
due to the lack of a previous price for the first element in arr
.
Metrics._spent
— MethodCalculates the spent amount in a trade considering leverage
, value
and fees
.
_spent(
_,
_,
_,
leverage,
price,
value,
fees,
fees_base
) -> Any
The function calculates the spent amount as the value
divided by leverage
plus fees
, and returns the negative absolute value of this amount. An assertion ensures that the calculated value is non-negative before negation.
Metrics._tradesdf
— FunctionRetrieves trades from an AssetInstance
within a specified range and transforms them into a DataFrame.
_tradesdf(
ai::Instances.AssetInstance
) -> Union{Nothing, DataFrames.DataFrame}
_tradesdf(
ai::Instances.AssetInstance,
from
) -> Union{Nothing, DataFrames.DataFrame}
_tradesdf(
ai::Instances.AssetInstance,
from,
to
) -> Union{Nothing, DataFrames.DataFrame}
The function retrieves trades within this range and then transforms them into a DataFrame using the _tradesdf()
function.
Metrics._tradesdf
— MethodTransforms an AbstractVector
of trades into a DataFrame.
_tradesdf(trades::AbstractVector) -> DataFrames.DataFrame
The function creates an empty DataFrame from TradesTuple
and appends the trades. Afterwards, it renames the :date
column to :timestamp
.
Metrics._valueat
— FunctionCalculates the value of a position at a given timestamp.
_valueat(
ai,
cum_amount,
timestamp,
leverage,
entryprice,
pos,
fees
)
_valueat(
ai,
cum_amount,
timestamp,
leverage,
entryprice,
pos,
fees,
fees_base
)
This function takes a MarginInstance
ai
, a cum_amount
, a timestamp
, a leverage
, an entryprice
, and a position pos
as parameters. It first calculates the closing price at the given timestamp, the value of the position based on the cumulative amount and the closing price, and the fees based on this value. It then returns the earned amount based on these values, using the _earned
function.
Metrics._valueat
— MethodCalculates the value of a position at a given timestamp for a NoMarginInstance.
_valueat(ai, cum_amount, timestamp, args)
This function takes a NoMarginInstance
ai
, a cum_amount
, and a timestamp
as parameters, along with any number of additional arguments. It calculates the value of the position as the product of the cumulative amount and the closing price at the given timestamp, and returns this value. Note: For a NoMarginInstance
, leverage is not considered, hence the value is directly dependent on the cumulative amount and the closing price.
Metrics.applytimeframe!
— MethodApplies a given timeframe to the timestamps in a DataFrame.
applytimeframe!(df, tf) -> Any
This function removes the sample
column from the DataFrame df
and applies the tf
timeframe to the timestamp
column. The DataFrame is then returned with the updated timestamps.
Metrics.aroundtrades
— MethodProvides trade data for a given asset instance around a specified timeframe.
aroundtrades(ai, tf)
It calculates a start and a stop date based on the dates of the first and last trades in the AssetInstance
history and the specified timeframe. It then extracts the OHLCV data for the AssetInstance
within this date range, and resamples this data to the specified timeframe. The resultant resampled DataFrame is returned.
Metrics.bydate
— MethodGroups trade data by date and other specified tags.
bydate(
data,
tf,
tags...;
sort
) -> DataFrames.GroupedDataFrame
The function converts timestamps in data
to a suitable format based on tf
and then groups the data by the specified tags
and the converted timestamps. The sort
parameter determines whether the resulting grouped data should be sorted or not.
Metrics.cagr
— FunctionComputes the Compound Annual Growth Rate (CAGR) for a given strategy.
cagr(s::Strategies.Strategy) -> Any
cagr(s::Strategies.Strategy, prd::Dates.Period) -> Any
cagr(
s::Strategies.Strategy,
prd::Dates.Period,
initial
) -> Any
cagr(
s::Strategies.Strategy,
prd::Dates.Period,
initial,
price_func
) -> Any
Calculates the CAGR for a Strategy
s
over a specified Period
prd
, defaulting to the period of the strategy's trades. The initial cash amount initial
and the pricing function price_func
can also be specified.
Metrics.calmar
— FunctionComputes the Calmar ratio for a given strategy.
calmar(s::Strategies.Strategy) -> Any
calmar(s::Strategies.Strategy, tf) -> Any
Calculates the Calmar ratio for a Strategy
s
over a specified timeframe tf
, defaulting to one day.
Metrics.entryexit
— MethodCounts the number of entries and exits in a trade.
entryexit(
g
) -> NamedTuple{(:entries, :exits), <:Tuple{Any, Any}}
The function takes a trade as input, counts the number of entries (negative values) and exits (positive values) and returns a tuple with these counts.
Metrics.expand
— FunctionExpands a DataFrame to include all timestamps in a range.
expand(df) -> Any
expand(df, tf) -> Any
This function takes a DataFrame df
and an optional timeframe tf
(which defaults to the timeframe of df
). It creates a new DataFrame that includes all timestamps within the range of df
and the given timeframe, and then joins this new DataFrame with df
using an outer join on the timestamp
column. The resulting DataFrame is then sorted by timestamp
.
Metrics.expectancy
— FunctionComputes the trading expectancy for a given strategy.
expectancy(s::Strategies.Strategy) -> Any
expectancy(s::Strategies.Strategy, tf) -> Any
Calculates the trading expectancy for a Strategy
s
over a specified timeframe tf
, defaulting to one day.
Metrics.ffill!
— FunctionForward fills missing values in a vector.
ffill!(v)
ffill!(v, out)
This function takes a vector v
and an optional output vector out
(which defaults to v
itself). It starts with the first value in v
(which must not be missing) and applies the coalesce
function to each subsequent pair of values in v
and out
. The coalesce
function replaces each missing value in v
with the corresponding value from out
. The function then returns out
with the filled missing values. This is effectively a forward fill operation, carrying the most recent non-missing value forward to replace missing values.
Metrics.isincreaseorder
— MethodChecks if an Order
is an IncreaseOrder
.
Metrics.isreduceorder
— MethodChecks if an Order
is a ReduceOrder
.
Metrics.maxdd
— MethodComputes the maximum drawdown for a series of returns.
maxdd(
returns
) -> NamedTuple{(:dd, :ath, :cum_returns), <:Tuple{Any, Any, Any}}
Calculates the maximum drawdown given an array of returns
. The drawdown is the largest percentage drop in the cumulative product of 1 plus the returns.
Metrics.multi
— MethodReturns a dict of calculated metrics for a given strategy.
multi(
s::Strategies.Strategy,
metrics::Symbol...;
tf,
normalize,
norm_max
) -> Union{Dict, Vector}
For a Strategy
s
, calculates specified metrics
over a specified timeframe tf
, defaulting to one day. If normalize
is true
, the metrics are normalized with respect to norm_max
.
Metrics.normalize_metric
— FunctionNormalize a metric. Based on the value of max
.
Metrics.resample_trades
— FunctionAggregates all trades of a strategy in a single dataframe
resample_trades(s::Strategies.Strategy; ...) -> Any
resample_trades(
s::Strategies.Strategy,
tf;
style,
byinstance,
custom,
expand_dates
) -> Any
byinstance
: (trades_df, ai) -> nothing
can modify the dataframe of a single instance before it is appended to the full df. style
: :full
or :minimal
specifies what columns should be aggregated in the resampled df custom
: similar to style
but instead allows you to define custom aggregation rules (according to DataFrame
) expand_dates
: returns a contiguous dataframe from the first trade date to the last (inserting default ohlcv rows where no trades have happened.)
Metrics.resample_trades
— MethodResamples trades data from a smaller to a higher timeframe.
resample_trades(
ai::Instances.AssetInstance,
to_tf;
style,
custom
) -> Any
This function takes an AssetInstance
and a target timeframe to_tf
as parameters, as well as optional style
and custom
parameters for additional customization. It extracts the trades data from the AssetInstance
and resamples it to the target timeframe. Volume adjustments are made based on the margin mode of the AssetInstance
. The data is then grouped by date, transformed according to the margin mode, style, and custom parameters, and combined into a new DataFrame. Finally, the target timeframe is applied to the timestamps in the DataFrame.
Metrics.sharpe
— FunctionComputes the Sharpe ratio for a given strategy.
sharpe(s::Strategies.Strategy; ...) -> Any
sharpe(s::Strategies.Strategy, tf; rfr) -> Any
Calculates the Sharpe ratio for a Strategy
s
over a specified timeframe tf
, defaulting to one day. The risk-free rate rfr
can be specified, and defaults to 0.0.
Metrics.sortino
— FunctionComputes the Sortino ratio for a given strategy.
sortino(s::Strategies.Strategy; ...) -> Any
sortino(s::Strategies.Strategy, tf; rfr) -> Any
Calculates the Sortino ratio for a Strategy
s
over a specified timeframe tf
, defaulting to one day. The risk-free rate rfr
can be specified, and defaults to 0.0.
Metrics.trades_balance
— MethodReplays the trade history of a single asset instance.
trades_balance(
ai::Instances.AssetInstance;
tf,
return_all,
df,
initial_cash
) -> Any
return_all
: if true
returns a dataframe where:
base/quote_balance
the volume generated by the trades that happened at that timestamp.:cum_total
represents the total balance held for each timestamp.:cum_value_balance
represents the value in quote currency of the asset for each timestamp.
Metrics.trades_balance
— MethodPlots the trade history for all the assets in a strategy.
trades_balance(s; tf, return_all, byasset, kwargs...)
return_all
[true
]: similar to the function for single assets, plus:
cum_quote
: the balance of cash for each timestampcum_value_balance
: the balance of all held assets in quote currency for each timestamp.
byasset
[false
]: also return a column that tracks the value balance by asset for each timestamp normalize_timeframes
:
Metrics.trades_duration
— MethodComputes the average duration of trades for an asset instance.
trades_duration(ai::Instances.AssetInstance; raw, f) -> Any
Calculates the average duration between trades for an AssetInstance
ai
. The raw
parameter determines whether the result should be in raw format (in milliseconds) or a compact time format. The function f
is used to aggregate the durations and defaults to the mean.
Metrics.trades_duration
— MethodComputes the average duration of trades for a strategy.
trades_duration(s::Strategies.Strategy; f) -> Any
Calculates the average duration between trades for a Strategy
s
. The function f
is used to aggregate the durations and defaults to the mean.
Metrics.trades_hour
— MethodComputes the average hour of trades for an asset instance.
trades_hour(ai::Instances.AssetInstance; f) -> Any
Calculates the average hour of trades for an AssetInstance
ai
. The function f
is used to aggregate the hours and defaults to the mean.
Metrics.trades_leverage
— MethodComputes the average leverage for trades of an asset instance.
trades_leverage(ai::Instances.AssetInstance; f) -> Any
Calculates the average leverage of trades for an AssetInstance
ai
. The function f
is used to aggregate the leverages and defaults to the mean.
Metrics.trades_monthday
— MethodComputes the average day of the month for trades of an asset instance.
trades_monthday(ai::Instances.AssetInstance; f) -> Any
Calculates the average day of the month for trades for an AssetInstance
ai
. The function f
is used to aggregate the days and defaults to the mean.
Metrics.trades_size
— MethodComputes the average trade size for an asset instance.
trades_size(ai::Instances.AssetInstance; f) -> Any
Calculates the average size of trades for an AssetInstance
ai
. The function f
is used to aggregate the sizes and defaults to the mean.
Metrics.trades_size
— MethodComputes the average trade size for a strategy.
trades_size(s::Strategies.Strategy; f) -> Any
Calculates the average size of trades for a Strategy
s
. The function f
is used to aggregate the sizes and defaults to the mean.
Metrics.trades_weekday
— MethodComputes the average weekday of trades for an asset instance.
trades_weekday(ai::Instances.AssetInstance; f) -> Any
Calculates the average weekday of trades for an AssetInstance
ai
. The function f
is used to aggregate the weekdays and defaults to the mean.
Metrics.tradesvolume!
— MethodEntries subtract quote currency, Exits subtract base currency.
tradesvolume!(_::Misc.WithMargin, data) -> Any
This function adjusts the volume of trades in the WithMargin
mode. It assigns size
to quote_volume
and amount
to base_volume
in the data
. It then modifies these volumes based on whether each order in data
is an increase order or not. For non-increase orders, base_volume
is made non-positive and quote_volume
is made non-negative. For increase orders, base_volume
is made non-negative and quote_volume
is made non-positive.
Metrics.tradesvolume!
— MethodBuys subtract quote currency, while sells subtract base currency.
tradesvolume!(_::NoMargin, data)
This function adjusts the volume of trades in the NoMargin
mode. It assigns size
to quote_volume
and amount
to base_volume
in the data
. In debug mode, it asserts that all sell orders have non-positive base volume and non-negative quote volume, and all buy orders have non-negative base volume and non-positive quote volume.
Metrics.transforms
— MethodApplies custom transformations based on margin mode, style, and custom parameters.
transforms(m::Misc.MarginMode, style, custom) -> Vector{Any}
Depending on the provided MarginMode
, style
and custom
parameters, this function applies different transformations to the data. The customization allows for flexibility in data processing and analysis.
Metrics.zeromissing!
— MethodReplaces missing values in a vector with 0.0.
zeromissing!(v)
This function iterates over each index of the vector v
. If the value at a given index is missing, it replaces it with 0.0. The vector v
is then returned with the replaced values.
Metrics.@balance_arr
— MacroGenerates code to calculate the cumulative total balance for a given set of trades over a given timeframe.
This macro generates code that calculates the cumulative total balance for a given set of trades s
over a given timeframe tf
. It first gets a DataFrame of balances for s
and tf
using the trades_balance
function. If this DataFrame is nothing
(which means there are no trades), it immediately returns -Inf
. Otherwise, it extracts the cum_total
column from the DataFrame, which represents the cumulative total balance, and assigns this to balance
. The generated code is then returned.