Coder Social home page Coder Social logo

Comments (4)

polakowo avatar polakowo commented on July 27, 2024 1

@NowBothWhiteAndRed
Here is an example how to do just that:

import vectorbt as vbt
import numpy as np
import pandas as pd
from numba import njit

@njit
def exit_choice_func_nb(col, from_i, to_i, ts, sl_stops, tp_stops, trailing):
    # Get indices of stop loss and take profit exits and return the first
    sl_idxs = vbt.signals.nb.sl_choice_nb(col, from_i, to_i, ts, sl_stops, trailing, True)
    tp_idxs = vbt.signals.nb.tp_choice_nb(col, from_i, to_i, ts, tp_stops, True)
    return np.sort(np.concatenate((sl_idxs, tp_idxs)))[:1]

@njit
def custom_iter_apply_nb(i, entries, ts, sl_stops, tp_stops, trailing):
    # Run exit_choice_func_nb for stop at index i
    return vbt.signals.nb.generate_enex_nb(
        entries.shape,
        vbt.signals.nb.true_choice_nb,
        exit_choice_func_nb,
        (entries,), (ts, sl_stops[i, :, :], tp_stops[i, :, :], trailing))

@njit
def generate_custom_exits_nb(entries, ts, sl_stops, tp_stops, trailing=False):
    # Run custom_iter_apply_nb for each stop value and concatenate results
    return vbt.base.combine_fns.apply_and_concat_multiple_nb(
        len(sl_stops), custom_iter_apply_nb, entries, ts, sl_stops, tp_stops, trailing)

def generate_custom_exits(entries, price, sl_stops, tp_stops, trailing=False, 
                          keys=None, broadcast_kwargs={}):
    vbt.utils.checks.assert_type(price, (pd.Series, pd.DataFrame))
    # Broadcast pandas objects
    entries, price = vbt.base.reshape_fns.broadcast(entries, price, **broadcast_kwargs, writeable=True)
    # Broadcast stop values for each to match the shape of entries
    sl_stops = vbt.base.reshape_fns.broadcast_to_array_of(sl_stops, entries.vbt.to_2d_array())
    tp_stops = vbt.base.reshape_fns.broadcast_to_array_of(tp_stops, entries.vbt.to_2d_array())
    # Broadcast stop values between each other
    sl_stops, tp_stops = np.broadcast_arrays(sl_stops, tp_stops)
    sl_stops = np.copy(sl_stops)
    tp_stops = np.copy(tp_stops)
    # Build column hierarchy
    if keys is not None:
        param_columns = keys
    else:
        sl_param_columns = vbt.base.index_fns.index_from_values(sl_stops, name='stop_loss')
        tp_param_columns = vbt.base.index_fns.index_from_values(tp_stops, name='take_profit')
        param_columns = vbt.base.index_fns.stack_indexes(sl_param_columns, tp_param_columns)
    columns = vbt.base.index_fns.combine_indexes(param_columns, entries.vbt.columns)
    # Execute
    new_entries, exits = generate_custom_exits_nb(
        entries.vbt.to_2d_array(),
        price.vbt.to_2d_array(),
        sl_stops, 
        tp_stops, 
        trailing
    )
    # Wrap numpy arrays into pandas objects and return
    return entries.vbt.wrap(new_entries, columns=columns), entries.vbt.wrap(exits, columns=columns)

entries = pd.DataFrame({
    'a': [True, False, False, False, False],
    'b': [True, False, True, False, True],
    'c': [True, True, True, False, False]
})
price = pd.Series([1., 2., 3., 2., 1.])
generate_custom_exits(entries, price, 0.1, 0.15)

# stop_loss      0.1              
# take_profit    0.1              
#                  a      b      c
# 0             True   True   True
# 1            False  False  False
# 2            False   True   True
# 3            False  False  False
# 4            False   True  False

# stop_loss      0.1              
# take_profit    0.1              
#                  a      b      c
# 0            False  False  False
# 1             True   True   True
# 2            False  False  False
# 3            False   True   True
# 4            False  False  False

While the code seems complex, the only thing that I created was the exit_choice_func_nb that combines signals using OR. All other functions are what vectorbt is doing under the hood: broadcasting inputs and parameters, preparing inputs for numba, iterating over parameters and concatenating the results, and wrapping the results back into pandas objects. So the generate_custom_exits function is the most complete you can get.

from vectorbt.

polakowo avatar polakowo commented on July 27, 2024

Maybe there is a need to integrate such use cases into the library but for now I'm more concerned with having multi-asset portfolios in vectorbt.

@TheSnowGuru it won't work since stop values are not absolute values but percentages relative to the price at the entry point. There is no (at least efficient) way of deciding which came first without utilizing numba.

from vectorbt.

NowBothWhiteAndRed avatar NowBothWhiteAndRed commented on July 27, 2024

Thanks! The example code works as expected. It helped me a lot.

This case could be generalized to "chain any signal with iterative logic with others" so it would definitely be worthwhile to support for building more advanced strategies.

from vectorbt.

polakowo avatar polakowo commented on July 27, 2024

Implemented in #52

from vectorbt.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    šŸ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. šŸ“ŠšŸ“ˆšŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ā¤ļø Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.