Tags & Backtesting Module

Tagging utils.

Functions:

tag_value(serie, value[, gt, ge, eq, le, ...])

It tags values of a serie compared to one value and a gt,ge,eq,le,lt condition.

tag_comparison(serie_a, serie_b[, gt, ge, ...])

It tags values of a serie compared to other serie by methods gt,ge,eq,le,lt condition.

tag_cross(serie_a, serie_b[, echo, ...])

It tags points where serie_a crosses over serie_b or optionally below.

tag_column_to_strategy_group(column, group, ...)

Tags a columns as part of Strategy group of columns.

merge_series(predominant, other)

Predominant serie will be filled nans with values, if existing, from the other serie.

clean_in_out(serie[, in_tag, out_tag])

Balance from in tag to first out tag and discards any other tag until next in tag.

buy_base_backtesting(row, price, base, quote)

A simple backtesting buy function.

sell_base_backtesting(row, price, base, quote)

A simple backtesting sell function.

evaluate_wallets(df_, base_serie, ...[, ...])

Obtains total wallet values in a quote value through time.

check_action_labels_for_backtesting(actions, ...)

This function verify labels in actions series, if labels for in actions and labels for out actions are or not the specified ones. Also

simple_backtesting(df, actions[, base, ...])

Returns two pandas series as base wallet and quote wallet over time.

backtesting(df, actions_column, ...[, ...])

Returns two pandas series as base wallet and quote wallet over time.

add_future_index_threshold_label(data[, ...])

Adds next indices for each kline touching prices percentage thresholds as usable target labels for a given threshold to a DataFrame.

is_alternating(lst)

Verify if a list is alternating 1 to -1 or -1 to 1 alternatively.

tag_value(serie: Series, value: int | float, gt: bool = False, ge: bool = False, eq: bool = False, le: bool = False, lt: bool = False, match_tag=1, mismatch_tag=0, to_numeric=True) Series[source]

It tags values of a serie compared to one value and a gt,ge,eq,le,lt condition.

Parameters:
  • serie (pd.Series) – A numeric serie.

  • value (int or float or Decimal) – Value of comparison.

  • gt (bool) – Value to match if strictly greater than value.

  • ge (bool) – Value to match if greater or equal than value.

  • eq (bool) – Value to match if equal than value.

  • le (bool) – Value to match if lower or equal than value.

  • lt (bool) – Value to match if strictly lower than value.

  • match_tag (int or str) – Value to tag previous logic.

  • mismatch_tag – Value to tag not matched previous logic.

  • to_numeric (bool) – If true, if possible, downcast type until the most basic numeric type (integer)

Return pd.Series:

A serie with tags as values.

tag_comparison(serie_a: Series, serie_b: Series, gt: bool = False, ge: bool = False, eq: bool = False, le: bool = False, lt: bool = False, match_tag=1, mismatch_tag=0, to_numeric=True) Series[source]

It tags values of a serie compared to other serie by methods gt,ge,eq,le,lt condition.

Parameters:
  • serie_a (pd.Series) – A numeric serie.

  • serie_b (pd.Series) – A numeric serie.

  • gt (bool) – Value to match if strictly greater than serie_b values.

  • ge (bool) – Value to match if greater or equal than serie_b values.

  • eq (bool) – Value to match if equal than serie_b values.

  • le (bool) – Value to match if lower or equal than serie_b values.

  • lt (bool) – Value to match if strictly lower than serie_b values.

  • match_tag (int or str) – Value to tag previous logic.

  • mismatch_tag – Value to tag not matched previous logic.

  • to_numeric (bool) – If true, if possible, downcast type until the most basic numeric type (integer)

Return pd.Series:

A serie with tags (argument) as values.

tag_cross(serie_a: Series, serie_b: Series, echo: int = 0, cross_over_tag='buy', cross_below_tag='sell', name='Cross', non_zeros: bool = True) Series[source]

It tags points where serie_a crosses over serie_b or optionally below.

Parameters:
  • serie_a (pd.Series) – A numeric serie.

  • serie_b (pd.Series) – A numeric serie.

  • echo (int) – It tags a fixed amount of candles forward the crossed point not including cross candle.

  • cross_over_tag (int or str) – Value to tag over cross. Default is “buy”.

  • cross_below_tag (int or str) – Value to tag below cross. Default is “sell”

  • name (str) – Name for the resulting serie.

  • non_zeros (bool) – Substitutes zeros by nans. If echo want to be used, must be used non_zeros.

Return pd.Series:

A serie with tags as values.

tag_column_to_strategy_group(column: str, group: str, strategy_groups: dict) dict[source]

Tags a columns as part of Strategy group of columns.

Parameters:
  • column (str) – A column to tag with a strategy group.

  • group (str) – Name of the group.

  • strategy_groups (str) – The existing strategy groups.

Return dict:

Updated strategy groups of columns.

merge_series(predominant: Series, other: Series) Series[source]

Predominant serie will be filled nans with values, if existing, from the other serie.

Same kind of index needed.

Parameters:
  • predominant (pd.Series) – A serie with nans to fill from other serie.

  • other (pd.Series) – A serie to pick values for the nans.

Return pd.Series:

A merged serie.

clean_in_out(serie: Series, in_tag=1, out_tag=-1) Series[source]

Balance from in tag to first out tag and discards any other tag until next in tag. This cleans redundant in or out tags.

Parameters:
  • serie (pd.Series) – A serie with in and out tags.

  • in_tag – Tag for in tags. Default is 1.

  • out_tag – Tag for out tags. Default is -1.

Return pd.Series:

Clean serie with ech in with next out.

buy_base_backtesting(row: Series, price: float, base: float, quote: float, fee=0.001) tuple[source]

A simple backtesting buy function.

Parameters:
  • row (pd.Series) – A row of a BinPan DataFrame with prices.

  • price (float) – Price of the action.

  • base (float) – Inverted base.

  • quote (float) – Inverted quote.

  • fee (float) – Fee applied to the operation.

Return tuple:

A tuple with resulting base and quote after operation.

sell_base_backtesting(row: Series, price: float, base: float, quote: float, fee=0.001) tuple[source]

A simple backtesting sell function.

Parameters:
  • row (pd.Series) – A row of a BinPan DataFrame with prices.

  • price (float) – Price of the action.

  • base (float) – Inverted base.

  • quote (float) – Inverted quote.

  • fee (float) – Fee applied to the operation.

Return tuple:

A tuple with resulting base and quote after operation.

evaluate_wallets(df_: DataFrame, base_serie: Series, quote_serie: Series, evaluating_quote: str, info_dic: dict = None, suffix: str = '') tuple[Series, Series, Series][source]

Obtains total wallet values in a quote value through time.

Parameters:
  • df (pd.DataFrame) – A BinPan’s dataframe.

  • base_serie (pd.Series) – A wallet serie for symbol’s base.

  • quote_serie (pd.Series) – A wallet serie for symbol’s quote.

  • evaluating_quote (str) – a Binance valid quote to evaluate operations.

  • info_dic (dict) – BinPan exchange info dict to extract information about quotes and bases of symbols.

  • suffix (str) – A suffix for the names of the columns.

Return pd.DataFrame:

It returns a dataframe with base and quote series plus an evaluated serie in any quote coin of both wallets merged.

check_action_labels_for_backtesting(actions: Series, label_in: int, label_out: int) tuple[any, any][source]
This function verify labels in actions series, if labels for in actions and labels for out actions are or not the specified ones. Also

if there are any other label it will throw an exception.

Parameters:
  • actions (pd.Series) – A serie with labels to check if there are just in and out labels or not.

  • label_in (int) – Usually 1

  • label_out (int) – Usually -1

Return tuple:

Returns verified label in and label out.

simple_backtesting(df: DataFrame, actions: Series, base: float = 0, quote: float = 1000, priced_actions_col: str = 'Open', fee: float = 0.001, label_in=1, label_out=-1, suffix: str = '', evaluating_quote: str = 'BUSD', info_dic: dict = None) DataFrame[source]

Returns two pandas series as base wallet and quote wallet over time. Its expected a serie with strings like ‘buy’ or ‘sell’. That serie is called the “actions”. If it is available a column with the exact price of the actions, can be passed in actions_col parameter by column name or a pandas series, if not, Closed price column can be a good approximation.

All actions will be considered to buy all base as possible or to sell all base as posible.

Parameters:
  • df (pd.DataFrame) – A BinPan dataframe.

  • actions (pd.Series) – A pandas series with buy or sell strings for simulate actions.

  • base (float) – A starting quantity of symbol’s base.

  • quote (float) – A starting quantity of symbol’s quote.

  • priced_actions_col (pd.Series or str) – Column with the prices for the action emulation.

  • fee (float) – Binance applicable fee for trading. DEfault is 0.001.

  • label_in (str or int) – A label consider as trade in trigger.

  • label_out (str or int) – A label consider as trade out trigger.

  • evaluating_quote (str) – a Binance valid quote to evaluate operations.

  • info_dic (dict) – BinPan exchange info dict to extract information about quotes and bases of symbols.

  • suffix (str) – A suffix for the names of the columns.

Return tuple:

Two series with the base wallet and quote wallet funds in time.

backtesting(df: DataFrame, actions_column: Series | str, target_column: str | Series, stop_loss_column: str | Series, entry_filter_column: str | Series = None, priced_actions_col: str | Series = 'Open', fixed_target: bool = True, fixed_stop_loss: bool = True, base: float = 0, quote: float = 1000, fee: float = 0.001, label_in=1, label_out=-1, suffix: str = '', evaluating_quote: str = None, info_dic: dict = None, direction: str = 'long') DataFrame[source]

Returns two pandas series as base wallet and quote wallet over time. Its expected a serie with numbers like 1 for ins and -1 for outs. By ins and out I mean buys or sells, shorts and repays, etc.

If it is available a column with the exact price of the actions, can be passed in actions_col parameter by column name or a pandas

series, if not, Open price column can be a good approximation because operations start at the next candle of the tagged one.

All actions will be considered to buy all base as possible or to sell all base as posible.

Supports both long and short positions backtesting via the direction parameter.

Parameters:
  • df (pd.DataFrame) – A BinPan dataframe.

  • actions_column (pd.Series or str) – A pandas series with buy or sell strings for simulate actions.

  • target_column (pd.Series or str) – Column with data for operation target values.

  • stop_loss_column (pd.Series or str) – Column with data for operation stop loss values.

  • entry_filter_column (pd.Series or str) – A serie or colum with ones or zeros to allow or avoid entries.

  • priced_actions_col (pd.Series or str) – Column with the prices for the action emulation.

  • fixed_target (bool) – Target for any operation will be calculated and fixed at the beginning of the operation.

  • fixed_stop_loss (bool) – Stop loss for any operation will be calculated and fixed at the beginning of the operation.

  • base (float) – A starting quantity of symbol’s base.

  • quote (float) – A starting quantity of symbol’s quote.

  • fee (float) – Binance applicable fee for trading. DEfault is 0.001.

  • label_in (str or int) – A label consider as trade in trigger.

  • label_out (str or int) – A label consider as trade out trigger.

  • evaluating_quote (str) – a Binance valid quote to evaluate operations.

  • info_dic (dict) – BinPan exchange info dict to extract information about quotes and bases of symbols.

  • suffix (str) – A suffix for the names of the columns.

  • direction (str) – Direction of the backtesting: 'long' (default) or 'short'.

Return tuple:

Two series with the base wallet and quote wallet funds in time.

add_future_index_threshold_label(data: DataFrame, thresholds: list = [0.002, -0.002, 0.006, -0.006], max_lookahead=30)[source]

Adds next indices for each kline touching prices percentage thresholds as usable target labels for a given threshold to a DataFrame.

Parameters:
  • data – DataFrame containing the OHLC (Open, High, Low, Close) price data.

  • thresholds – List of thresholds for which to create future action labels. Positive values indicate a price increase, negative values indicate a price decrease.

  • max_lookahead – Maximum number of bars to look ahead to determine if a threshold is met. Default is 30.

Returns:

DataFrame with additional columns for each threshold. Each column contains the number of bars until the price change defined by the threshold is met. If the price change is not met within max_lookahead bars, the value is NaN.

is_alternating(lst: list) bool[source]

Verify if a list is alternating 1 to -1 or -1 to 1 alternatively. :param lst: A list of integers. :return: