-
I was trying to set up a simple stoploss after filled order. But it seems the errors showing I failed to pass necessary var. From other examples on git, I followed those by passing tuple from "earlier" func like group_prep to later one like order_nb, but I couldn't find why my code here fails. import numpy as np
import pandas as pd
from vectorbt.base.reshape_fns import flex_select_auto_nb, to_2d
from vectorbt.portfolio.enums import NoOrder, OrderStatus, OrderSide, Direction
from vectorbt.portfolio.nb import order_nb
import vectorbt as vbt
from numba import njit # why I need to import njit after vectorbt??
@njit
def group_prep_func_nb(c):
# We need to define stop price per column, thus we do it in group_prep_func_nb
stop_price = np.full(c.target_shape[1], np.nan, dtype=np.float_)
return (stop_price,)
@njit
def order_func_nb(c, stop_price, entries, exits, size):
# Select info related to this order
# flex_select_auto_nb allows us to pass size as single number, 1-dim or 2-dim array
# If flex_2d is True, 1-dim array will be per column, otherwise per row
size_now = flex_select_auto_nb(c.i, c.col, np.asarray(size), True)
# close is always 2-dim array
price_now = c.close[c.i, c.col]
stop_price_now = stop_price[c.col]
# Our logic
if entries[c.i, c.col]:
if c.shares_now == 0:
return order_nb(
size=size_now,
price=price_now,
direction=Direction.LongOnly)
elif exits[c.i, c.col] or price_now >= stop_price_now:
if c.shares_now > 0:
return order_nb(
size=-size_now,
price=price_now,
direction=Direction.LongOnly)
return NoOrder
@njit
def post_order_func_nb(c, order_result, stop_price, stop):
# Same broadcasting as for size
stop_now = flex_select_auto_nb(c.i, c.col, np.asarray(stop), True)
if order_result.status == OrderStatus.Filled:
if order_result.side == OrderSide.Buy:
# Position entered: Set stop condition
stop_price[c.col] = (1 + stop_now) * order_result.price
else:
# Position exited: Remove stop condition
stop_price[c.col] = np.nan
def simulate(close, entries, exits, threshold):
return vbt.Portfolio.from_order_func(
close,
order_func_nb,
to_2d(entries, raw=True), # 2-dim array
to_2d(exits, raw=True), # 2-dim array
np.inf, # will broadcast
group_prep_func_nb=group_prep_func_nb,
after_order_func_nb=post_order_func_nb,
after_order_args=(
threshold
)
# ,group_by=True ## need to add this to avoid grouping
)
close = pd.Series([10, 11, 12, 13, 14])
entries = pd.Series([True, True, False, False, False])
exits = pd.Series([False, False, False, True, True])
simulate(close, entries, exits, 0.1).share_flow()
|
Beta Was this translation helpful? Give feedback.
Answered by
polakowo
Sep 19, 2021
Replies: 1 comment
-
Func names such as |
Beta Was this translation helpful? Give feedback.
0 replies
Answer selected by
Oriono
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Func names such as
group_prep_func_nb
have changed, see new argument names.