Metrics
PlanarCore.Metrics.METRICS — Constant
All the metrics that supported.
PlanarCore.Metrics.TradesTuple — Type
A NamedTuple representing trade data, including date, amount, price, value, fees, fees_base, size, leverage, entryprice, and order.
PlanarCore.Metrics._annualize — Method
Annualizes 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.
PlanarCore.Metrics._cum_value_balance — Method
Calculates the cumulative value balance for a MarginInstance.
_cum_value_balance(
ii::PlanarCore.Instances.InstrumentInstance{<:PlanarCore.Instruments.AbstractInstrument, <:ExchangeID, M} where M<:PlanarCore.Misc.WithMargin,
df
) -> Any
This function takes a MarginInstance ii 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 ii, entryprice, cum_base, leverage, and close values from df. The earned amounts for each order are returned as a vector.
PlanarCore.Metrics._earned — Function
Calculates 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.
PlanarCore.Metrics._rawcalmar — Method
Computes 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.
PlanarCore.Metrics._rawexpectancy — Method
Computes 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.
PlanarCore.Metrics._rawsharpe — Method
Computes 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.
PlanarCore.Metrics._rawsortino — Method
Computes 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.
PlanarCore.Metrics._returns_arr — Method
Calculates 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.
PlanarCore.Metrics._spent — Method
Calculates 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.
PlanarCore.Metrics._tradesdf — Function
Retrieves trades from an InstrumentInstance within a specified range and transforms them into a DataFrame.
_tradesdf(
ii::PlanarCore.Instances.InstrumentInstance
) -> Union{Nothing, DataFrames.DataFrame}
_tradesdf(
ii::PlanarCore.Instances.InstrumentInstance,
from
) -> Union{Nothing, DataFrames.DataFrame}
_tradesdf(
ii::PlanarCore.Instances.InstrumentInstance,
from,
to
) -> Union{Nothing, DataFrames.DataFrame}
The function retrieves trades within this range and then transforms them into a DataFrame using the _tradesdf() function.
PlanarCore.Metrics._tradesdf — Method
Transforms 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.
PlanarCore.Metrics._valueat — Function
Calculates the value of a position at a given timestamp.
_valueat(
ii,
cum_amount,
timestamp,
leverage,
entryprice,
pos,
fees
)
_valueat(
ii,
cum_amount,
timestamp,
leverage,
entryprice,
pos,
fees,
fees_base
)
This function takes a MarginInstance ii, 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.
PlanarCore.Metrics._valueat — Method
Calculates the value of a position at a given timestamp for a NoMarginInstance.
_valueat(ii, cum_amount, timestamp, args)
This function takes a NoMarginInstance ii, 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.
PlanarCore.Metrics.applytimeframe! — Method
Applies a given timeframe to the timestamps in a DataFrame.
applytimeframe!(
df,
tf
) -> Union{DataFrames.DataFrame, DataFrames.GroupedDataFrame, DataFrames.SubDataFrame}
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.
PlanarCore.Metrics.aroundtrades — Method
Provides trade data for a given asset instance around a specified timeframe.
aroundtrades(ii, tf)
It calculates a start and a stop date based on the dates of the first and last trades in the InstrumentInstance history and the specified timeframe. It then extracts the OHLCV data for the InstrumentInstance within this date range, and resamples this data to the specified timeframe. The resultant resampled DataFrame is returned.
PlanarCore.Metrics.bydate — Method
Groups trade data by date and other specified tags.
bydate(
data,
tf,
tags...;
sort
) -> Union{DataFrames.GroupedDataFrame{DataFrames.DataFrame}, DataFrames.GroupedDataFrame{T} where T<:DataFrames.SubDataFrame}
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.
PlanarCore.Metrics.cagr — Function
Computes the Compound Annual Growth Rate (CAGR) for a given strategy.
cagr(s::PlanarCore.Strategies.Strategy) -> Any
cagr(
s::PlanarCore.Strategies.Strategy,
prd::Dates.Period
) -> Any
cagr(
s::PlanarCore.Strategies.Strategy,
prd::Dates.Period,
initial
) -> Any
cagr(
s::PlanarCore.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.
PlanarCore.Metrics.calmar — Function
Computes the Calmar ratio for a given strategy.
calmar(s::PlanarCore.Strategies.Strategy) -> Any
calmar(s::PlanarCore.Strategies.Strategy, tf) -> Any
Calculates the Calmar ratio for a Strategy s over a specified timeframe tf, defaulting to one day.
PlanarCore.Metrics.entryexit — Method
Counts 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.
PlanarCore.Metrics.expand — Function
Expands 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.
PlanarCore.Metrics.expectancy — Function
Computes the trading expectancy for a given strategy.
expectancy(s::PlanarCore.Strategies.Strategy) -> Any
expectancy(s::PlanarCore.Strategies.Strategy, tf) -> Any
Calculates the trading expectancy for a Strategy s over a specified timeframe tf, defaulting to one day.
PlanarCore.Metrics.ffill! — Function
Forward 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.
PlanarCore.Metrics.isincreaseorder — Method
Checks if an Order is an IncreaseOrder.
PlanarCore.Metrics.isreduceorder — Method
Checks if an Order is a ReduceOrder.
PlanarCore.Metrics.maxdd — Method
Computes 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.
PlanarCore.Metrics.multi — Method
Returns a dict of calculated metrics for a given strategy.
multi(
s::PlanarCore.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.
PlanarCore.Metrics.normalize_metric — Function
Normalize a metric. Based on the value of max.
PlanarCore.Metrics.resample_trades — Function
Aggregates all trades of a strategy in a single dataframe
resample_trades(
s::PlanarCore.Strategies.Strategy;
...
) -> Any
resample_trades(
s::PlanarCore.Strategies.Strategy,
tf;
style,
byinstance,
custom,
expand_dates
) -> Any
byinstance: (trades_df, ii) -> 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.)
PlanarCore.Metrics.resample_trades — Method
Resamples trades data from a smaller to a higher timeframe.
resample_trades(
ii::PlanarCore.Instances.InstrumentInstance,
to_tf;
style,
custom
) -> DataFrames.DataFrame
This function takes an InstrumentInstance 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 InstrumentInstance and resamples it to the target timeframe. Volume adjustments are made based on the margin mode of the InstrumentInstance. 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.
PlanarCore.Metrics.sharpe — Function
Computes the Sharpe ratio for a given strategy.
sharpe(s::PlanarCore.Strategies.Strategy; ...) -> Any
sharpe(s::PlanarCore.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.
PlanarCore.Metrics.sortino — Function
Computes the Sortino ratio for a given strategy.
sortino(s::PlanarCore.Strategies.Strategy; ...) -> Any
sortino(s::PlanarCore.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.
PlanarCore.Metrics.trades_balance — Method
Replays the trade history of a single asset instance.
trades_balance(
ii::PlanarCore.Instances.InstrumentInstance;
tf,
return_all,
df,
initial_cash
) -> Any
return_all: if true returns a dataframe where:
base/quote_balancethe volume generated by the trades that happened at that timestamp.:cum_totalrepresents the total balance held for each timestamp.:cum_value_balancerepresents the value in quote currency of the asset for each timestamp.
PlanarCore.Metrics.trades_balance — Method
Plots 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:
PlanarCore.Metrics.trades_duration — Method
Computes the average duration of trades for an asset instance.
trades_duration(
ii::PlanarCore.Instances.InstrumentInstance;
raw,
f
) -> Any
Calculates the average duration between trades for an InstrumentInstance ii. 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.
PlanarCore.Metrics.trades_duration — Method
Computes the average duration of trades for a strategy.
trades_duration(
s::PlanarCore.Strategies.Strategy;
f
) -> Dates.Period
Calculates the average duration between trades for a Strategy s. The function f is used to aggregate the durations and defaults to the mean.
PlanarCore.Metrics.trades_hour — Method
Computes the average hour of trades for an asset instance.
trades_hour(
ii::PlanarCore.Instances.InstrumentInstance;
f
) -> Any
Calculates the average hour of trades for an InstrumentInstance ii. The function f is used to aggregate the hours and defaults to the mean.
PlanarCore.Metrics.trades_leverage — Method
Computes the average leverage for trades of an asset instance.
trades_leverage(
ii::PlanarCore.Instances.InstrumentInstance;
f
) -> Any
Calculates the average leverage of trades for an InstrumentInstance ii. The function f is used to aggregate the leverages and defaults to the mean.
PlanarCore.Metrics.trades_monthday — Method
Computes the average day of the month for trades of an asset instance.
trades_monthday(
ii::PlanarCore.Instances.InstrumentInstance;
f
) -> Any
Calculates the average day of the month for trades for an InstrumentInstance ii. The function f is used to aggregate the days and defaults to the mean.
PlanarCore.Metrics.trades_size — Method
Computes the average trade size for an asset instance.
trades_size(
ii::PlanarCore.Instances.InstrumentInstance;
f
) -> Any
Calculates the average size of trades for an InstrumentInstance ii. The function f is used to aggregate the sizes and defaults to the mean.
PlanarCore.Metrics.trades_size — Method
Computes the average trade size for a strategy.
trades_size(s::PlanarCore.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.
PlanarCore.Metrics.trades_weekday — Method
Computes the average weekday of trades for an asset instance.
trades_weekday(
ii::PlanarCore.Instances.InstrumentInstance;
f
) -> Any
Calculates the average weekday of trades for an InstrumentInstance ii. The function f is used to aggregate the weekdays and defaults to the mean.
PlanarCore.Metrics.tradesvolume! — Method
Buys 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.
PlanarCore.Metrics.tradesvolume! — Method
Entries subtract quote currency, Exits subtract base currency.
tradesvolume!(_::PlanarCore.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.
PlanarCore.Metrics.transforms — Method
Applies custom transformations based on margin mode, style, and custom parameters.
transforms(m::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.
PlanarCore.Metrics.zeromissing! — Method
Replaces 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.
PlanarCore.Metrics.@balance_arr — Macro
Generates 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.