TradePricer#
-
class sigtech.framework.transaction_cost.transaction_cost.TradePricer
A class implementing trade price calculations for the application of transaction costs.
There are default transaction costs defined either on the
TradePricer
class or on the instrument class. These can be overridden when the environment is initialised.A transaction cost model can be set by its instrument classname, its instrument group or its individual ticker. If the transaction model is not defined in the register, it defaults to the model defined on the instrument class.
The parameters used in the transaction cost can be updated or a new transaction model with new models can be passed.
The available models can be listed by calling
TradePricer.AVAILABLE_MODELS
and new models can be added withTradePricer.add_model
.The overrides passed are a dictionary with the keys being the class name, group ticker or instrument ticker. The values of the dictionary are a tuple with the first value being the name of the transaction model to use and the second any parameters the model might use, entered as a dictionary.
An example of adding a custom model and then defining it to be used is given below:
import datetime as dtm import sigtech.framework as sig # Define a custom model to use def my_transaction_cost_model(self): # Gets gross price base_price = self.instrument.valuation_price_base(self.d) # Depending on whether we are long or short, return different multiples if self.quantity >= 0: return base_price * self.params_dict['long_multiple'] else: return base_price * self.params_dict['short_multiple'] # Add the model sig.TradePricer.add_model(my_transaction_cost_model) # list available models available_models = sig.TradePricer.AVAILABLE_MODELS env = sig.init(repeat_mode='REINIT', echo_set_logging=False) # Setting custom costs per instrument class / group / instrument env[sig.config.T_COST_OVERRIDES] = { 'Future': ('fixed_cost', {'spread': 0.03}), 'VG INDEX FUTURES GROUP': ('fixed_relative_cost', {'spread': 0.02}), 'ESZ20 INDEX': ('my_transaction_cost_model', {'long_multiple': 1.2, 'short_multiple': 0.95}), } # Query models applied for i in ['Z Z20 INDEX', 'VGZ20 INDEX', 'ESZ20 INDEX', 'EURUSD FXFORWARD']: tc_model = sig.TradePricer.get_tc_model(i, display=False) # Retrieve prices dt = dtm.datetime(2020, 12, 3) ask = sig.TradePricer('Z Z20 INDEX', dt, 1, 'USD', 'outright').trade_price() bid = sig.TradePricer('Z Z20 INDEX', dt, -1, 'USD', 'outright').trade_price()
To plot costs vs trade quantity, use
sig.TradePricer.plot_transaction_costs('ESZ20 INDEX', dt)
Transaction cost models can be assigned to instruments based on the following criteria, ordered by ascending specificity of scope:
Class name (e.g.
SingleStock
,Future
,CommodityFuture
)Group ticker (e.g.
'ES COMDTY FUTURES GROUP'
,'US GOVT BOND GROUP'
)Instrument ticker (e.g.
'1000045.SINGLE_STOCK.TRADABLE'
,'ESH18 COMDTY'
,'US 2.5 2006/10/31 GOVT'
)
Please see the
SIG_transaction_costs.ipynb
notebook for more details on usage of this class.-
AVAILABLE_MODELS = {'brl_swap', 'combined_spread_market_impact', 'credit_index', 'default_fx_digital_option', 'default_fx_fwd', 'default_fx_option', 'default_fx_spot', 'defined_on_instrument', 'fixed_commission', 'fixed_cost', 'fixed_cost_taken_from_attr', 'fixed_relative_cost', 'futures_t_cost', 'fx_forward', 'index_forward', 'ir_swap', 'lme_otc', 'market_impact_square_root', 'no_cost', 'ois_swap', 'vega_based', 'xccy_swap', 'yield_spread', 'yield_transaction_type'}
-
classmethod add_model(callback: Callable, instrument_callback: Optional[Callable] = None) None
Add a new model. The model should be a method, which takes the
TradePricer
as the first argument and returns the trade price. This returned trade price can be as a float orPricingResult
object, which includes information on the quantity executed. The name of the method will be used to identity the model.From the first argument, which is an instance of
TradePricer
, the following details of the trade are available:'instrument'
: Instrument object being traded.'dt'
: Datetime of trade execution.'quantity'
: Quantity of platform units being traded.'currency'
: Currency of payment'strategy_timeline'
: Link to originating trading strategy timeline.'d'
: UTC date of trade execution.'params_dict'
: Dictionary of parameters.
- Parameters:
callback – Method to use for the model.
instrument_callback – Method to use for the creation of new OTC instruments (Optional).
-
brl_swap()
Transaction Cost Model - For use with BRL swaps
Price adjusted by transaction cost for entering or exiting an offshore BRL swap.
Model parameters:
'existing'
: Spread in bps to the fair rate, used for an existing swap.'new'
: Spread in bps to the fair rate, spread used for a new swap.
-
brl_swap_instrument()
Offshore BRL swap at market (bid/ask adjusted) rate, that will have zero extra cost to trade.
-
combined_spread_market_impact()
Transaction Cost Model - For general usage
Applies a relative spread plus a market impact cost of the “square root” type:
\[C = k + c~\sigma~r^\alpha\]where \(C\) is the cost, \(k\) is a relative spread, \(c, \alpha\) are constants, \(\sigma\) is the average daily volatility over the last 252 days and \(r\) is the participation rate, defined as the ratio of number of units traded to the average daily volume over the last 30 days. The resulting C is used as a relative spread from mid.
If the trade currency is different the fx conversion costs will be applied on top of this.
Model parameters:
'k'
: Value used for k.'c'
: Value used for c.'alpha'
: Value used for \(\alpha\).'sigma'
: Value used for \(\sigma\) (Optional, defaults to the realized volatility based on last 252 days).
-
credit_index()
Transaction Cost Model - For use with credit index instruments
Price adjusted by transaction cost for entering or exiting credit index. (relative spread scale).
Bid/Ask adjustment versus mid is a spread times risky dv01, on a notional adjusted by defaults. Spread is assumed relative to the quote spread (i.e. 0.01 means absolute adjustment of 0.01*quote_spread)
Overall, the difference to mid is given by
spread * quote_spread * risky_pv01 * notional_scale
.Model parameters:
'spread'
: Spread to the fair rate in bps (Optional if'param_lookup'
is supplied).'param_lookup'
: Dictionary of spread values for each index (Optional if'spread'
is supplied).'multiplier_dict'
: Dictionary of optional'roll_multiplier'
and'post_start_multiplier values'
.
-
default_fx_digital_option()
Transaction Cost Model - For use with FX digital options
Default cost model for fx digital options - uses bid/ask prices derived from the bid/ask volsurface data
-
default_fx_fwd()
Transaction Cost Model - For use with FX forward points
Return the default bid/ask FX forward history read from the market data.
-
default_fx_option()
Transaction Cost Model - For use with vanilla FX options
Default cost model for fx options - uses bid/ask prices derived from the bid/ask volsurface data
-
default_fx_spot()
Transaction Cost Model - For use in fx spot transactions
Return the default side of the market adjusted FX spot timeseries.
If ‘use_bid_ask_data’` is
True
this will first try to use the market bid and ask data.Otherwise, or if the data is missing, a relative spread to mid is applied. 0.01 would equate to a charge of 1% of mid.
This can be given via the
'spread'
parameter. A lookup dictionary can also be passed with values for different crosses. If no value is given the defaults are read fromSPOT_TRADING_COSTS
.Model parameters:
'use_bid_ask_data'
: Boolean to use market bid/ask if available (Optional, defaults toTrue
).'spread'
: relative spread or lookup dictionary (Optional, uses platform defaults when missing).
-
defined_on_instrument()
Transaction Cost Model - For general usage
Use the transaction cost model defined on the instrument to price the trade. This uses the logic given in the instrument’s
'.trade_price'
method.
-
fixed_commission()
Transaction Cost Model - For general usage
Apply a fixed commission to the trade, irrespective of quantity traded or price of the instrument.
If the trade currency is different the fx conversion costs will be applied on top of this.
Model parameters:
'commission'
: The cost incurred for every trade in the instrument currency.
-
fixed_cost()
Transaction Cost Model - For general usage
Apply a spread from mid expressed in the currency of the instrument, e.g. 1.5 would equate to a $1.5 spread from mid. This is applied for each unit traded so the total incurred costs increase with the quantity.
If the trade currency is different the fx conversion costs will be applied on top of this.
Model parameters:
'spread'
: The absolute spread applied from mid in the instrument currency.'roll_spread'
: Spread for roll trades when relevant (Optional, defaults to'spread'
value).
-
fixed_cost_intraday() deprecated
Apply a spread from mid expressed in units of currency of the trade, e.g. 1.5 would equate to a $1.5 spread from mid (if the trade was in USD).
-
fixed_cost_taken_from_attr()
Transaction Cost Model - For general usage
Apply a spread from mid. This can be in terms of the currency of the instrument, which is the default or when
'relative'
is set toFalse
, e.g. 1.5 would equate to a $1.5 spread. When'relative'
is set toTrue
a fixed cost relative to the mid of the instrument. 0.01 would equate to a charge of 1% of mid. This is applied for each unit traded so the total incurred costs increase with the quantity.The spread is taken from an attribute of the object with the name. The attribute name is specified with the parameter
spread_attr
, with it defaulting to'spread'
If the trade currency is different the fx conversion costs will be applied on top of this.
Model parameters:
'spread_attr'
: Name of attribute to use for the spread (Optional, defaults to'spread'
)'relative'
: Apply as a relative percentage spread rather than absolute (Optional, defaults toFalse
)
-
fixed_cost_transaction_type() deprecated
Apply a spread from mid expressed in units of currency of the trade plus a fixed cost.
-
fixed_relative_cost()
Transaction Cost Model - For general usage
Apply a fixed cost relative to the mid of the instrument. 0.01 would equate to a charge of 1% of mid. This is applied for each unit traded so the total incurred costs increase with the quantity.
If the trade currency is different the fx conversion costs will be applied on top of this.
Model parameters:
'spread'
: The relative spread applied from mid.'roll_spread'
: Spread for roll trades when relevant (Optional, defaults to'spread'
value).
-
futures_t_cost()
Transaction Cost Model - For use with futures
Price adjusted by transaction cost for futures. This applies an absolute spread which is split in two parts. It is formed of a fixed cost per contract
contract_fixed_trade_cost
and amarket_impact
component.\[C = F M ( f / m + i )\]where \(C\) is the absolute cost, \(F\) is the price factor to account for quoting units, \(M\) is the trading_cost_multiplier, \(f\) is the fixed cost per contract, \(m\) is the value per point to apply per contract and \(i\) is the market impact component.
The market impact component takes the closest superior clip size to the traded quantity as entry in the supplied market_impact dictionary. If no market impact data is supplied twice the tick size is used.
If a
future_roll_tcosts
dictionary is supplied the value from here is used in the case of a roll trade.A multiplier based on the transaction_type is applied.
An example of parameter inputs are given below (here the largest ‘100’ market impact value will be used) :
import pandas as pd import datetime { 'market_impact': {'50': 0.1289082114225, '100': 0.132489763622840,}, 'future_roll_tcosts': {}, 'trading_cost_multiplier': { 'outright': pd.Series({datetime.date(2000,1,1): 1.0}), 'roll': pd.Series({datetime.date(2000,1,1): 0.5}) } }
Model parameters:
'market_impact'
: Dictionary of market impact spread used for different clip sizes (Optional).'future_roll_tcosts'
: Dictionary of market impact spread used for roll trades (Optional).'trading_cost_multiplier'
: Dictionary of multiplier used for transaction types.'contract_fixed_trade_cost'
: Fixed contract cost.'quantity_override'
: traded quantity.
- Returns:
price adjusted with t-cost
-
fx_forward()
Transaction Cost Model - For use with FX forwards
Price adjusted by transaction cost for FX forward. This applies a spread on quoted fwd points (units of 0.0001). The spread is supplied for different maturities (in terms of months to maturity) and these are interpolated. Values should be given for roll and outright trades.
The costs should be set and queried on identifiers of the form
'#cross# FXFORWARD'
. For example,'EURUSD FXFORWARD'
and'DEFAULT FXFORWARD'
.For example:
{ 'outright': {'0.25': 4, '1': 4, '3': 4, '6': 6, '12': 8, '24': 12}, 'roll': {'0.25': 0.5, '1': 0.5, '3': 1, '6': 3, '12': 5, '24': 9} }
Model parameters:
'outright'
: Dictionary of fwd point bps spread for each monthly time to maturity, applied for outright.'roll'
: Dictionary of fwd point bps spread for each monthly time to maturity, applied for roll.
-
fx_forward_instrument()
FX forward instrument at a market strike (zero extra transaction cost to enter).
-
fx_forward_strike()
Bid/ask adjusted FX forward strike.
-
get_current_quantity() float
Quantity currently available.
-
get_instrument() TradableInstrument
Return a new OTC instrument.
-
classmethod get_tc_model(instr_name: str, display: Optional[bool] = False) Union[None, dict]
Obtain the name, parameters, source and description of the transaction cost model for a given instrument.
Summary contents include:
'instrument'
: instrument name'name'
: model name'parameters'
: model parameters'source'
: name of the instrument, group or class where the transaction cost model is defined'info'
: description of the transaction cost model.
- Parameters:
instr_name – Name of the instrument.
display – If True, print the summary about the model; if False, return the summary.
- Returns:
None (if display is
True
), dict with the model information or list of dict for each model.
-
index_forward()
Transaction Cost Model - For use with index forward instruments
Price adjusted by transaction cost of index forward trade (strike adjustment).
Model parameters:
'param_lookup'
: Dictionary of spread to the strike values used for each index.
-
index_forward_instrument()
Create an index forward instrument, taking into account bid/ask adjustment, that would be traded at zero additional cost.
-
ir_swap()
Transaction Cost Model - For use with Libor IR swaps
Price adjusted by transaction cost of ir-swap trade, modelled as bid/ask adjustment of the fair spread. Since swaps are modelled as a receiver, spread adjustment is opposite sign to the corresponding pv adjustment.
If no
'spread'
value is supplied platform defaults are used which depend on the currency, tenor, date and transaction type. These can be obtained by calling the methodsig.InterestRateSwap.swap_trading_spread
.Model parameters:
'spread'
: Spread to the fair rate in bps (Optional).'roll_spread'
: Spread to apply for roll trades (Optional, will use'spread'
if no value is specified).
-
ir_swap_instrument()
Create an IR swap instrument, taking into account bid/ask adjustment, that would be traded at zero additional cost.
-
lme_otc()
Transaction Cost Model - For use with LME instruments
Price adjusted by transaction cost of trading LME instruments (spot, future, forward, spread).
Model parameters:
'param_lookup'
: Dictionary of absolute adjustment values for each LME future code.'is_spread'
: Boolean set toTrue
for spread instruments.'multiplier_dict'
: Dictionary of optional'roll_multiplier'
and'post_start_multiplier values'
.
-
lme_otc_instrument()
LME future or forward with fair bid/ask adjusted market strike, such that there is no extra transaction cost to trade this instrument.
-
lme_otc_strike(is_spread=False)
Fair bid/ask adjusted strike of LME future/forward, such that entering a trade with this strike will have zero additional cost.
- Parameters:
is_spread – Adjust for spread (default is False).
- Returns:
Bid/ask adjusted strike.
-
market_impact_square_root()
Transaction Cost Model - For general usage
Apply a market impact cost of the square root type:
\[C = c~\sigma~r^\alpha\]where \(C\) is the cost, \(c, \alpha\) are constants, \(\sigma\) is the average daily volatility over the last 252 days and \(r\) is the participation rate, defined as the ratio of number of units traded to the average daily volume over the last 30 days. The resulting C is used as a relative spread from mid.
If the trade currency is different the fx conversion costs will be applied on top of this.
Model parameters:
'c'
: Value used for c.'alpha'
: Value used for \(\alpha\).'sigma'
: Value used for \(\sigma\) (Optional, defaults to the realized volatility based on last 252 days).
-
no_cost()
Transaction Cost Model - For general usage
Apply no cost to the trade.
-
ois_swap()
Transaction Cost Model - For use with OIS swaps
Price adjusted by transaction cost of ois-swap trade, modelled as running bid/ask adjustment of the fair spread. Since swaps are modelled as a receiver, spread adjustment is opposite sign to the corresponding pv adjustment.
Model parameters:
'spread'
: Spread to the fair rate in bps (Optional if'param_lookup'
is supplied).'param_lookup'
: Dictionary of spread values for each currency (Optional if'spread'
is supplied).
-
ois_swap_instrument()
Create an OIS swap instrument, taking into account bid/ask adjustment, that would be traded at zero additional cost.
-
static plot_transaction_costs(instr_name: str, dt: datetime = datetime.datetime(2024, 12, 18, 18, 49, 45, 747587), ccy=None, transaction_type=None, upper_volume_log10=6, steps=10, log_axis=False, chart_type='ABSOLUTE', unit_type='MODEL') None
Method to plot transaction costs as function of the trade quantity.
- Parameters:
instr_name – Instrument identifier.
dt – Transaction cost evaluation datetime, default is now.
ccy – Currency.
transaction_type – String identifier to indicate type of transaction, e.g.
'outright'
,'roll'
.upper_volume_log10 – Upper bound for the log of volume.
steps – Number of points on the plot.
log_axis – If True, plot the quantity on log scale, default is False.
chart_type – Type of chart, should be one of:
'ABSOLUTE'
,'RELATIVE'
,'TOTAL'
.unit_type – Units used for quantity, should be one of:
'MODEL'
(default),'TRADE'
.
-
spread_from_mid(t_cost=None) deprecated
Price computed as mid price plus/minus spread.
- Parameters:
t_cost – Transaction cost.
-
spread_from_mid_intraday(t_cost=None) deprecated
Price computed as mid price plus/minus spread, used in the case of intraday data.
- Parameters:
t_cost – Transaction cost.
-
spread_from_mid_relative(t_cost=None) deprecated
Price computed as mid price plus/minus a spread multiplied by the price.
- Parameters:
t_cost – Transaction cost.
-
trade_price() Union[float, PricingResult]
Return the trade prices available for the object.
-
vega_based()
Transaction Cost Model - For use with options
Price adjusted by transaction cost based on a multiple of vega. A spread to mid is applied based on a multiple of Vega. There is the option to limited by zero to avoid over-adjustment and negative prices.
Model parameters:
'vega_cost'
: Spread to mid in a quantity of Vega (Optional if'param_lookup'
is supplied).'param_lookup'
: Dictionary of spread values for each currency (Optional if'vega_cost'
is supplied).'zero_limit'
: Boolean to use clip to zero to prevent negative prices (Optional, defaults toTrue
).
-
vega_based_positive() deprecated
Price adjusted by transaction cost based on a multiple of vega, limited by zero to avoid over-adjustment and negative prices.
-
xccy_swap()
Transaction Cost Model - For use with xccy swaps
Price adjusted by transaction cost of cross currency swap trade, modelled as running bid/ask adjustment of the pay leg spread, or the receiving fixed rate, depending on the swap type (Fixed-Float vs Float-Float).
Model parameters:
'spread'
: Spread to the rate in bps (Optional if'param_lookup'
is supplied).'param_lookup'
: Dictionary of spread values for each currency pair (Optional if'spread'
is supplied).
-
xccy_swap_instrument()
Create a cross currency swap instrument, taking into account bid/ask adjustment, that would be traded at zero additional cost.
-
yield_spread()
Transaction Cost Model - For use with bonds
Default cost model for bonds - applies a
yield_spread
(in bps), which is scaled by the modified duration to give a relative spread from mid.The
yield_spread
can be a float,pd.DataFrame
formed of transaction type and then spreads for different maturities (in years) or dictionary of these. The applied yield spread is interpolated from these maturity values.An example of input is given below.
from sigtech.framework.instruments.constants import STRATEGY_DATE_MIN { 'yield_spread': pd.DataFrame({STRATEGY_DATE_MIN: { 'outright': { 10: 0.25, 30: 0.75, }, 'roll': { 10: 0.1, 30: 0.15, }, }}) }
Model parameters:
'yield_spread'
: Spread in bps or lookup dictionary (Optional, defaults to platform defaults when missing).
-
yield_transaction_type()
Transaction Cost Model - For use with bonds
Apply a spread from mid in terms of the yield. The input
spread_ts
gives a timeseries of bps spread values. These are interpolated for values given at different maturities (in years) and transaction types ('roll'
and ‘’outright’`).An example of the format is given below:
{'spread_ts': {dtm.date(1954, 7, 1): {'roll': {10: 0.1, 30: 0.15}, 'outright': {10: 0.25, 30: 0.75}}}}
Model parameters:
'spread_ts'
: Data used for the yield spread.