Comments (4)
@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.
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.
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.
Implemented in #52
from vectorbt.
Related Issues (20)
- What is the difference in the documentation of vectorbt PRO vs the open source vectorbt?
- What is the benchmark plotted in pf.plot().show()?
- How to use run_combs in combination with other signals?
- Questions about backtesting
- StopLoss group_by
- Plots missing "close" curve
- Import Errors HOT 5
- Plotting with custom benchmark_rets got error (VectorBT used undefined attribute 'obj')
- Datetime support with from_order_func HOT 2
- Dockerfile changes to run /apps/candlestick-patterns app
- Multiprocessing Error When Creating Portofiolio
- Pandas MultiIndex on axis 0 HOT 1
- Closing all positions at the end of the day HOT 1
- MetaTrader5 Integration for Data and Backtesting
- DeprecationError: `np.float_` is deprecated HOT 1
- Extreme return values (billions %) in alternating long/short position backtests
- tuple out of range error on IndicatorBase.run HOT 1
- Specific values for stop loss BUT DIFFERENT FOR LONG/SHORT STOP
- Consider Migrating from `alpaca-trade-api` to `alpaca-py` HOT 1
- Intraday Trades Not Closing Correctly with Autoclose Function and Stop Loss
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
š Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
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.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ā¤ļø Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from vectorbt.