Allocation functions#
-
class sigtech.framework.signal.library.allocation.StandardAllocationFunctions
Class containing references to standard allocation functions.
-
EQUAL_SIGNAL(ts: Series) DataFrame
Weight a list of instruments with the same weights.
- Parameters:
instrument_names – List of instrument names.
ts – Input timeseries.
- Returns:
pandas Dataframe.
equal_signal_driven = sig.signal_library.allocation.equal_signal_driven equal_signal_driven(list('AB'), pd.Series([1,2,3,4,5]))
Returns:
A
B
0
0.5
0.5
1
1.0
1.0
2
1.5
1.5
3
2.0
2.0
4
2.5
2.5
-
IDENTITY() DataFrame
Return allocations unchanged.
- Parameters:
ts – Input timeseries.
- Returns:
pandas Dataframe.
identity = sig.signal_library.allocation.identity identity( pd.DataFrame({'A': [1,10,-1], 'B': [-1, np.nan, -1]}) )
Returns:
A
B
0
1
-1.0
1
10
nan
2
-1
-1.0
-
LONG_SHORT_DOLLAR_NEUTRAL(proportion: float) DataFrame
Take long and short positions over the top and bottom proportion of signal values, with 100% gross exposure.
- Parameters:
ts – Input timeseries.
proportion – Proportion value.
- Returns:
pandas Dataframe.
long_short_dollar_neutral = sig.signal_library.allocation.long_short_dollar_neutral long_short_dollar_neutral( ts=pd.DataFrame({'A':[1,2,3,4], 'B': [-1, -2, -3, -4], 'C': [-2, -1, 0, 1]}), proportion=0.5 )
Returns:
A
B
C
0
0.5
0.0
-0.5
1
0.5
-0.5
0.0
2
0.5
-0.5
0.0
3
0.5
-0.5
0.0
-
NORMALIZE() DataFrame
Normalise weights to have 100% gross notional.
- Parameters:
ts – Input timeseries.
- Returns:
pandas Dataframe.
normalize_weights = sig.signal_library.allocation.normalize_weights normalize_weights( pd.DataFrame({'A': [2, 2, 2], 'B': [1, 2, 1]}) )
Returns:
A
B
0
0.67
0.33
1
0.5
0.5
2
0.67
0.33
-
NORMALIZE_LONG_SHORT() DataFrame
Normalise long and short weights to have both 50% gross exposure. NOTE This function only returns rows when the input
ts
contains both long and short positions.- Parameters:
ts – Input timeseries.
- Returns:
pandas Dataframe.
normalize_long_short = sig.signal_library.allocation.normalize_long_short normalize_long_short( pd.DataFrame({'A': [1,10,-1,1], 'B': [-1, 0, -1,1], 'C': [-1, -1, -1,1]}) )
A
B
C
0
0.5
-0.25
-0.25
1
0.5
0.0
-0.5
-
NORMALIZE_ZERO_FILLED() DataFrame
Normalise weights to have 100% gross notional and fill empty values with zeros.
- Parameters:
ts – Input timeseries.
- Returns:
pandas Dataframe.
normalize_weights_zero_filled = sig.signal_library.allocation.normalize_weights_zero_filled normalize_weights_zero_filled( pd.DataFrame({'A': [1,np.nan,2], 'B': [0.5, np.nan, np.nan]}) )
Returns:
# A
B
0
0.67
0.33
1
0.0
0.0
2
1.0
0.0
-
OPTIMIZER(factor_exposure_object, optimization_problem, optimizer=None, periods=None, optimization_frequency=None, base=None, instrument_mapping=None, decision_time=None, additional_data: Optional[Union[DataFrame, dict]] = None, tolerance: int = 0, initial_base_input: Optional[Series] = None, include_start_date: Optional[bool] = False)
Run a factor optimization task for each signal entry.
- Parameters:
ts – Input timeseries.
factor_exposure_object –
FactorExposures
object.optimization_problem –
OptimizationProblem
object or series ofOptimizationProblem
objects.optimizer –
Optimizer
(optional).periods – Chosen time window (optional).
optimization_frequency – Frequency for optimization. Can be a list of dates, integer steps or schedule string (optional).
base – Optimiser static base (optional).
instrument_mapping – Mapping in dict format from the column name of the signal to the instrument to trade (optional).
decision_time – time for factor exposure asof calculation (optional).
additional_data – additional_data to use in optimization. This can either be a DataFrame or a dictionary in the form
{decision_dt: {source_name : source_value}}
(optional).tolerance – Number of consecutive periods with failed optimizations to allow before raising an exception. This allows sporadic optimization failures to be skipped and the weights updated the next periods. Suggested values are only a few periods (<10). Default of
0
will raise on the first failure. Negative values are not allowed.initial_base_input – allocations in the first optimiser base (if used). If not specified and a non-static base is used then zero allocations will be applied (optional).
include_start_date – used to include start date in schedule built with optimization frequency (optional).
- Returns:
pandas Dataframe.
Example usage:
from sigtech.framework.analytics.optimization.optimization_problem import OptimizationProblem, TermTypes, MetricTypes from sigtech.framework.signal.library import allocation from sigtech.framework.internal.utils.pandas_helpers import concat import pandas as pd import numpy as np mkt_series = sig.default_strategy_objects.rolling_futures.es_index_front().history().ffill().pct_change().dropna() single_stock_returns = concat( [ sig.default_strategy_objects.single_stock_strategies.apple_equity_rs().history(), sig.default_strategy_objects.single_stock_strategies.alphabet_equity_rs().history() ], axis=1 ).droplevel(axis=1, level=[0,1]).ffill().pct_change().loc[pd.to_datetime('2021-01-01'):] fe = sig.FactorExposures() fe.add_regression_factors(mkt_series, names=['Mkt']) fe.fit(single_stock_returns); fop = OptimizationProblem() fop.set_optimizer_objective( TermTypes.EXPOSURE, element='Mkt', metric=MetricTypes.SQUARE, value=-0.0001 ) fop.set_optimizer_bounds( TermTypes.WEIGHT, element='SUM_', metric=MetricTypes.LINEAR, min_value=1, max_value=1 ) optimization_dates = pd.date_range('2021-01-01', periods=6, freq='M') ones = pd.DataFrame( np.ones((len(optimization_dates), single_stock_returns.shape[1])), index=optimization_dates, columns=single_stock_returns.columns ) allocation.optimized_allocations( ts=ones, factor_exposure_object=fe, optimization_problem=fop, periods=252 )
-
OVERRIDE_DIRECTIONAL_EQUAL_WEIGHTS() DataFrame
Return
1/n
weights for all finite entries ints
.n
is taken to be the number of finite elements in each row ofts
. Note that0
values ints
return a correspondingNaN
as they are considered as assets we do not wish to invest in.The signs of the original
ts
are maintained so long and short signals are respected.- Parameters:
ts – Input signal timeseries. Tempotal index and assets as columns.
- Returns:
Weights DataFrame, the same shape as
ts
.
directional_equal_weighted = sig.signal_library.allocation.directional_equal_weighted directional_equal_weighted( pd.DataFrame({'A': [1, 2, 3, 4], 'B': [-1, -2, 3, np.nan], 'C': [0, 1, 2, 3]}) )
Returns:
A
B
C
0
0.5
-0.5
NaN
1
1/3
-1/3
1/3
2
1/3
1/3
1/3
3
0.5
NaN
0.5
-
OVERRIDE_EQUAL_WEIGHTS() DataFrame
Divide allocations by number of instruments.
- Parameters:
ts – Input timeseries.
- Returns:
pandas Dataframe.
equally_weighted = sig.signal_library.allocation.equally_weighted equally_weighted( pd.DataFrame({'A': [1,10,-1], 'B': [-1, np.nan, -1]}) )
Returns:
A
B
0
0.5
-0.5
1
5.0
nan
2
-0.5
-0.5
-
OVERRIDE_STATIC_WEIGHTS(ts: DataFrame) DataFrame
Weight original signals with provided weights.
- Parameters:
weight – Weights in dict format.
ts – Input timeseries.
- Returns:
pandas Dataframe.
static_weighted = sig.signal_library.allocation.static_weighted static_weighted( weight={'A':0.1, 'B': 2}, ts=pd.DataFrame({'A': [1,10,-1], 'B': [-1, np.nan, -1]}) )
Returns:
A
B
0
0.1
-2.0
1
1.0
nan
2
-0.1
-2.0
-
STOP_LOSS(trigger_level: float, trigger_type: str = 'FIXED_PCT_LOSS', instrument_mapping: dict = None, intraday_kwargs: dict = None) DataFrame deprecated
Apply a stop loss to the position
- Parameters:
ts – Input signal timeseries.
trigger_level – Trigger level, 0.1 for a 10% loss.
trigger_type – Type of trigger to use, see sig.StopStrategy docstring for more details
instrument_mapping – Mapping of signal name to instrument name.
intraday_kwargs – Dictionary of intraday_history inputs such as
period
, any input will switch to intraday.
- Returns:
pandas Dataframe.
-
STOP_TRIGGER(trigger_level: float = None, trigger_type: str = 'FIXED_PCT_LOSS', instrument_mapping: dict = None, intraday_kwargs: dict = None, trigger_at_rebalance_dt: bool = False, rebalance_after_trigger: bool = True, trigger_params: dict = None) DataFrame
Apply a stop trigger to the position.
The trigger types available are:
'FIXED_PCT_LOSS'
- Trigger close if percentage loss exceeds level from trade date.'FIXED_ABS_LOSS'
- Trigger close if absolute on one unit loss exceeds level from trade date.'TRAILING_PCT_LOSS'
- Trigger close if percentage loss exceeds level from high.'TRAILING_ABS_LOSS'
- Trigger close if absolute loss on one unit exceeds level from high.'FIXED_PCT_PROFIT'
- Trigger close if percentage profit exceeds level from trade date.'FIXED_ABS_PROFIT'
- Trigger close if absolute profit on one unit exceeds level from trade date.'TRAILING_PCT_PROFIT'
- Trigger close if percentage profit exceeds level from low.'TRAILING_ABS_PROFIT'
- Trigger close if absolute profit on one unit exceeds level from low.'FIXED_PCT_RANGE'
- Trigger close if percentage profit or loss exceeds level from trade date.'FIXED_ABS_RANGE'
- Trigger close if absolute profit or loss on one unit exceeds level from trade date.'TRAILING_PCT_RANGE'
- Trigger close if percentage profit or loss exceeds level from low.'TRAILING_ABS_RANGE'
- Trigger close if absolute profit or loss on one unit exceeds level from low.'CUSTOM_RANGE'
- Trigger close using custom range params.
- Parameters:
ts – Input signal timeseries.
trigger_level – Trigger level, 0.1 for a 10% loss.
trigger_type – Type of trigger to use, see sig.StopStrategy docstring for more details
instrument_mapping – Mapping of signal name to instrument name.
intraday_kwargs – Dictionary of intraday_history inputs such as
period
, any input will switch to intraday.trigger_at_rebalance_dt – if True, trigger decision only happen at rebalance dates (optional). False by default.
rebalance_after_trigger – if True, strategy keeps rebalancing after position are closed.
trigger_params – Optional parameters to use in trigger method.
- Returns:
pandas Dataframe.
-
TIME_VARYING(ts: DataFrame) DataFrame
Weight original signals with dictionary of timeseries weights.
- Parameters:
weight – Weights in dict format.
ts – Input timeseries.
- Returns:
pandas Dataframe.
time_varying_weighted = sig.signal_library.allocation.time_varying_weighted time_varying_weighted( weight={'A':[1,2,3], 'B': [2,2,2]}, ts=pd.DataFrame({'A': [1,10,-1], 'B': [-1, np.nan, -1]}) )
Returns:
A
B
0
1
-2.0
1
20
nan
2
-3
-2.0
-
TWO_INSTRUMENT(short_instrument_name: str, ts: Series) DataFrame
Trade a series signal long on one instrument and short on another.
- Parameters:
long_instrument_name – Name of the long instrument.
short_instrument_name – Name of the short instrument.
ts – Input timeseries.
- Returns:
pandas Dataframe.
long_short = sig.signal_library.allocation.long_short long_short( long_instrument_name='A', short_instrument_name='B', ts=pd.Series(range(-3,4)) )
Returns:
A
B
0
0
3
1
0
2
2
0
1
3
0
0
4
1
0
5
2
0
6
3
0
-
sigtech.framework.signal.library.allocation.directional_equal_weighted(ts: DataFrame) DataFrame
Return
1/n
weights for all finite entries ints
.n
is taken to be the number of finite elements in each row ofts
. Note that0
values ints
return a correspondingNaN
as they are considered as assets we do not wish to invest in.The signs of the original
ts
are maintained so long and short signals are respected.- Parameters:
ts – Input signal timeseries. Tempotal index and assets as columns.
- Returns:
Weights DataFrame, the same shape as
ts
.
directional_equal_weighted = sig.signal_library.allocation.directional_equal_weighted directional_equal_weighted( pd.DataFrame({'A': [1, 2, 3, 4], 'B': [-1, -2, 3, np.nan], 'C': [0, 1, 2, 3]}) )
Returns:
A
B
C
0
0.5
-0.5
NaN
1
1/3
-1/3
1/3
2
1/3
1/3
1/3
3
0.5
NaN
0.5
-
sigtech.framework.signal.library.allocation.equal_signal_driven(instrument_names: list[str], ts: Series) DataFrame
Weight a list of instruments with the same weights.
- Parameters:
instrument_names – List of instrument names.
ts – Input timeseries.
- Returns:
pandas Dataframe.
equal_signal_driven = sig.signal_library.allocation.equal_signal_driven equal_signal_driven(list('AB'), pd.Series([1,2,3,4,5]))
Returns:
A
B
0
0.5
0.5
1
1.0
1.0
2
1.5
1.5
3
2.0
2.0
4
2.5
2.5
-
sigtech.framework.signal.library.allocation.equally_weighted(ts: DataFrame) DataFrame
Divide allocations by number of instruments.
- Parameters:
ts – Input timeseries.
- Returns:
pandas Dataframe.
equally_weighted = sig.signal_library.allocation.equally_weighted equally_weighted( pd.DataFrame({'A': [1,10,-1], 'B': [-1, np.nan, -1]}) )
Returns:
A
B
0
0.5
-0.5
1
5.0
nan
2
-0.5
-0.5
-
sigtech.framework.signal.library.allocation.identity(ts: DataFrame) DataFrame
Return allocations unchanged.
- Parameters:
ts – Input timeseries.
- Returns:
pandas Dataframe.
identity = sig.signal_library.allocation.identity identity( pd.DataFrame({'A': [1,10,-1], 'B': [-1, np.nan, -1]}) )
Returns:
A
B
0
1
-1.0
1
10
nan
2
-1
-1.0
-
sigtech.framework.signal.library.allocation.long_short(long_instrument_name: str, short_instrument_name: str, ts: Series) DataFrame
Trade a series signal long on one instrument and short on another.
- Parameters:
long_instrument_name – Name of the long instrument.
short_instrument_name – Name of the short instrument.
ts – Input timeseries.
- Returns:
pandas Dataframe.
long_short = sig.signal_library.allocation.long_short long_short( long_instrument_name='A', short_instrument_name='B', ts=pd.Series(range(-3,4)) )
Returns:
A
B
0
0
3
1
0
2
2
0
1
3
0
0
4
1
0
5
2
0
6
3
0
-
sigtech.framework.signal.library.allocation.long_short_dollar_neutral(ts: DataFrame, proportion: float) DataFrame
Take long and short positions over the top and bottom proportion of signal values, with 100% gross exposure.
- Parameters:
ts – Input timeseries.
proportion – Proportion value.
- Returns:
pandas Dataframe.
long_short_dollar_neutral = sig.signal_library.allocation.long_short_dollar_neutral long_short_dollar_neutral( ts=pd.DataFrame({'A':[1,2,3,4], 'B': [-1, -2, -3, -4], 'C': [-2, -1, 0, 1]}), proportion=0.5 )
Returns:
A
B
C
0
0.5
0.0
-0.5
1
0.5
-0.5
0.0
2
0.5
-0.5
0.0
3
0.5
-0.5
0.0
-
sigtech.framework.signal.library.allocation.normalize_long_short(ts: DataFrame) DataFrame
Normalise long and short weights to have both 50% gross exposure. NOTE This function only returns rows when the input
ts
contains both long and short positions.- Parameters:
ts – Input timeseries.
- Returns:
pandas Dataframe.
normalize_long_short = sig.signal_library.allocation.normalize_long_short normalize_long_short( pd.DataFrame({'A': [1,10,-1,1], 'B': [-1, 0, -1,1], 'C': [-1, -1, -1,1]}) )
A
B
C
0
0.5
-0.25
-0.25
1
0.5
0.0
-0.5
-
sigtech.framework.signal.library.allocation.normalize_weights(ts: DataFrame) DataFrame
Normalise weights to have 100% gross notional.
- Parameters:
ts – Input timeseries.
- Returns:
pandas Dataframe.
normalize_weights = sig.signal_library.allocation.normalize_weights normalize_weights( pd.DataFrame({'A': [2, 2, 2], 'B': [1, 2, 1]}) )
Returns:
A
B
0
0.67
0.33
1
0.5
0.5
2
0.67
0.33
-
sigtech.framework.signal.library.allocation.normalize_weights_zero_filled(ts: DataFrame) DataFrame
Normalise weights to have 100% gross notional and fill empty values with zeros.
- Parameters:
ts – Input timeseries.
- Returns:
pandas Dataframe.
normalize_weights_zero_filled = sig.signal_library.allocation.normalize_weights_zero_filled normalize_weights_zero_filled( pd.DataFrame({'A': [1,np.nan,2], 'B': [0.5, np.nan, np.nan]}) )
Returns:
# A
B
0
0.67
0.33
1
0.0
0.0
2
1.0
0.0
-
sigtech.framework.signal.library.allocation.optimized_allocations(ts, factor_exposure_object, optimization_problem, optimizer=None, periods=None, optimization_frequency=None, base=None, instrument_mapping=None, decision_time=None, additional_data: Optional[Union[DataFrame, dict]] = None, tolerance: int = 0, initial_base_input: Optional[Series] = None, include_start_date: Optional[bool] = False)
Run a factor optimization task for each signal entry.
- Parameters:
ts – Input timeseries.
factor_exposure_object –
FactorExposures
object.optimization_problem –
OptimizationProblem
object or series ofOptimizationProblem
objects.optimizer –
Optimizer
(optional).periods – Chosen time window (optional).
optimization_frequency – Frequency for optimization. Can be a list of dates, integer steps or schedule string (optional).
base – Optimiser static base (optional).
instrument_mapping – Mapping in dict format from the column name of the signal to the instrument to trade (optional).
decision_time – time for factor exposure asof calculation (optional).
additional_data – additional_data to use in optimization. This can either be a DataFrame or a dictionary in the form
{decision_dt: {source_name : source_value}}
(optional).tolerance – Number of consecutive periods with failed optimizations to allow before raising an exception. This allows sporadic optimization failures to be skipped and the weights updated the next periods. Suggested values are only a few periods (<10). Default of
0
will raise on the first failure. Negative values are not allowed.initial_base_input – allocations in the first optimiser base (if used). If not specified and a non-static base is used then zero allocations will be applied (optional).
include_start_date – used to include start date in schedule built with optimization frequency (optional).
- Returns:
pandas Dataframe.
Example usage:
from sigtech.framework.analytics.optimization.optimization_problem import OptimizationProblem, TermTypes, MetricTypes from sigtech.framework.signal.library import allocation from sigtech.framework.internal.utils.pandas_helpers import concat import pandas as pd import numpy as np mkt_series = sig.default_strategy_objects.rolling_futures.es_index_front().history().ffill().pct_change().dropna() single_stock_returns = concat( [ sig.default_strategy_objects.single_stock_strategies.apple_equity_rs().history(), sig.default_strategy_objects.single_stock_strategies.alphabet_equity_rs().history() ], axis=1 ).droplevel(axis=1, level=[0,1]).ffill().pct_change().loc[pd.to_datetime('2021-01-01'):] fe = sig.FactorExposures() fe.add_regression_factors(mkt_series, names=['Mkt']) fe.fit(single_stock_returns); fop = OptimizationProblem() fop.set_optimizer_objective( TermTypes.EXPOSURE, element='Mkt', metric=MetricTypes.SQUARE, value=-0.0001 ) fop.set_optimizer_bounds( TermTypes.WEIGHT, element='SUM_', metric=MetricTypes.LINEAR, min_value=1, max_value=1 ) optimization_dates = pd.date_range('2021-01-01', periods=6, freq='M') ones = pd.DataFrame( np.ones((len(optimization_dates), single_stock_returns.shape[1])), index=optimization_dates, columns=single_stock_returns.columns ) allocation.optimized_allocations( ts=ones, factor_exposure_object=fe, optimization_problem=fop, periods=252 )
-
sigtech.framework.signal.library.allocation.piecewise_optimized_allocations_kwargs(po_ts, additional_data=None, **kwargs)
Obtain the required parameters to use with the
optimized_allocations
allocation function, with an optimization problem that changes over time, from the series ofPortfolioOptimizer
instances.Example usage:
import pytz # Define instruments to use and inputs instr1 = sig.default_strategy_objects.rolling_futures.es_index_front() instr2 = sig.default_strategy_objects.rolling_futures.nq_index_front() start_date = dtm.date(2017, 12, 1) end_date = dtm.date(2018,1,1) dates = pd.date_range(start_date, end_date, freq="b") target_series = pd.Series({dtm.datetime.combine(dates[0], dtm.time(0, 0, tzinfo=pytz.utc)): 0, dtm.datetime.combine(dates[10], dtm.time(0, 0, tzinfo=pytz.utc)): 1, dtm.datetime.combine(dates[15], dtm.time(0, 0, tzinfo=pytz.utc)): 2}) # Construct example signal dataframe signal = pd.DataFrame( np.full((instr1.history().shape[0], 2), 0.5), index=instr1.history().index, columns=[instr1.name, instr2.name], ).loc[start_date:end_date] # specify initial weights to use in optimizer turnover initial_base = pd.Series(index=[instr1.name, instr2.name], data=[0.25, 0.75]) # Define piecewise series of optimizers opt1 = sig.PortfolioOptimizer().prefer_minimum_turnover() opt2 = sig.PortfolioOptimizer().prefer_minimum_variance().require_fully_invested() opt3 = sig.PortfolioOptimizer().prefer_target_return(value=1, pct_return_target=target_series) opt_series = pd.Series({dtm.datetime.combine(dates[0], dtm.time(0, 0, tzinfo=pytz.utc)): opt1, dtm.datetime.combine(dates[5], dtm.time(0, 0, tzinfo=pytz.utc)): opt2, dtm.datetime.combine(dates[10], dtm.time(0, 0, tzinfo=pytz.utc)): opt3}) # Setup and run a strategy ss = sig.SignalStrategy( currency="USD", start_date=dates[0], end_date = dates[-1], rebalance_frequency="1BD", signal_name=sig.signal_library.from_ts(signal).name, allocation_function=sig.signal_library.allocation.optimized_allocations, allocation_kwargs=sig.signal_library.allocation.piecewise_optimized_allocations_kwargs(opt_series, initial_base_input=initial_base), convert_long_short_weight=False ) ss.history()
- Parameters:
po_ts – Datetime indexed series of
PortfolioOptimizer
instances.additional_data – extra additional data to include (optional).
- Returns:
Dictionary of keyword arguments.
-
sigtech.framework.signal.library.allocation.static_weighted(weight: Union[dict, Series], ts: DataFrame) DataFrame
Weight original signals with provided weights.
- Parameters:
weight – Weights in dict format.
ts – Input timeseries.
- Returns:
pandas Dataframe.
static_weighted = sig.signal_library.allocation.static_weighted static_weighted( weight={'A':0.1, 'B': 2}, ts=pd.DataFrame({'A': [1,10,-1], 'B': [-1, np.nan, -1]}) )
Returns:
A
B
0
0.1
-2.0
1
1.0
nan
2
-0.1
-2.0
-
sigtech.framework.signal.library.allocation.stop_loss(ts: DataFrame, trigger_level: float, trigger_type: str = 'FIXED_PCT_LOSS', instrument_mapping: dict = None, intraday_kwargs: dict = None) DataFrame deprecated
Apply a stop loss to the position
- Parameters:
ts – Input signal timeseries.
trigger_level – Trigger level, 0.1 for a 10% loss.
trigger_type – Type of trigger to use, see sig.StopStrategy docstring for more details
instrument_mapping – Mapping of signal name to instrument name.
intraday_kwargs – Dictionary of intraday_history inputs such as
period
, any input will switch to intraday.
- Returns:
pandas Dataframe.
-
sigtech.framework.signal.library.allocation.stop_trigger(ts: DataFrame, trigger_level: float = None, trigger_type: str = 'FIXED_PCT_LOSS', instrument_mapping: dict = None, intraday_kwargs: dict = None, trigger_at_rebalance_dt: bool = False, rebalance_after_trigger: bool = True, trigger_params: dict = None) DataFrame
Apply a stop trigger to the position.
The trigger types available are:
'FIXED_PCT_LOSS'
- Trigger close if percentage loss exceeds level from trade date.'FIXED_ABS_LOSS'
- Trigger close if absolute on one unit loss exceeds level from trade date.'TRAILING_PCT_LOSS'
- Trigger close if percentage loss exceeds level from high.'TRAILING_ABS_LOSS'
- Trigger close if absolute loss on one unit exceeds level from high.'FIXED_PCT_PROFIT'
- Trigger close if percentage profit exceeds level from trade date.'FIXED_ABS_PROFIT'
- Trigger close if absolute profit on one unit exceeds level from trade date.'TRAILING_PCT_PROFIT'
- Trigger close if percentage profit exceeds level from low.'TRAILING_ABS_PROFIT'
- Trigger close if absolute profit on one unit exceeds level from low.'FIXED_PCT_RANGE'
- Trigger close if percentage profit or loss exceeds level from trade date.'FIXED_ABS_RANGE'
- Trigger close if absolute profit or loss on one unit exceeds level from trade date.'TRAILING_PCT_RANGE'
- Trigger close if percentage profit or loss exceeds level from low.'TRAILING_ABS_RANGE'
- Trigger close if absolute profit or loss on one unit exceeds level from low.'CUSTOM_RANGE'
- Trigger close using custom range params.
- Parameters:
ts – Input signal timeseries.
trigger_level – Trigger level, 0.1 for a 10% loss.
trigger_type – Type of trigger to use, see sig.StopStrategy docstring for more details
instrument_mapping – Mapping of signal name to instrument name.
intraday_kwargs – Dictionary of intraday_history inputs such as
period
, any input will switch to intraday.trigger_at_rebalance_dt – if True, trigger decision only happen at rebalance dates (optional). False by default.
rebalance_after_trigger – if True, strategy keeps rebalancing after position are closed.
trigger_params – Optional parameters to use in trigger method.
- Returns:
pandas Dataframe.
-
sigtech.framework.signal.library.allocation.time_varying_weighted(weight: Union[dict, DataFrame], ts: DataFrame) DataFrame
Weight original signals with dictionary of timeseries weights.
- Parameters:
weight – Weights in dict format.
ts – Input timeseries.
- Returns:
pandas Dataframe.
time_varying_weighted = sig.signal_library.allocation.time_varying_weighted time_varying_weighted( weight={'A':[1,2,3], 'B': [2,2,2]}, ts=pd.DataFrame({'A': [1,10,-1], 'B': [-1, np.nan, -1]}) )
Returns:
A
B
0
1
-2.0
1
20
nan
2
-3
-2.0