API Reference¶
-
class
blotter.blotter.
Blotter
(prices=None, interest_rates=None, accrual_time=Timedelta('0 days 16:00:00'), eod_time=Timedelta('0 days 16:00:00'), sweep_time=Timedelta('0 days 16:00:00'), base_ccy='USD', margin_charge=0.015)¶ This is a financial blotter which is used for maintaing positions and PnL in conjunction with backtesting a strategy historically. The main purpose is for calculating historical PnL for both open and closed trades as well as maintaining marked to market holdings.
This class maintains market pricing data for marking holdings to market as well as interest rate data for charging interest and margin on open positions. The class manages interest and margin charges based of a user defined time of day and also provides functionality for repatriating closed PnL to the user defined base currency on a daily user defined time.
-
automatic_events
(timestamp)¶ Update the current time of the Blotter, triggering all scheduled events between previous clock time and new clock time such as interest charges, margin charges, PnL calculations and PnL sweeps. See create_events() for more information on the type of events.
Parameters: timestamp: pandas.Timestamp
Time to update clock to and tigger internal events up until
-
connect_market_data
()¶ Initialize MarketData class, should be called before calling trade()
-
create_events
(timestamp, action)¶ Create internal event for updating Holdings class contained within Blotter instance. Manages creation of INTEREST, MARGIN, PNL and PNL_SWEEP events based on internal Blotter data.
This method is exposed to allow users greater flexibility in calling internal events however by default this is automatically called through automatic_events() and best not called unless user understands what they are doing.
MARGIN event charges interest in the base currency based on the margin required for the current open positions at a rate equal to the base currency interest rate + the margin_charge.
INTEREST events charges interest on the outstandings cash balances in different currencies based on the current interest rates.
PNL event calculates and saves the PNL based on current market prices for all open positions.
PNL_SWEEP event repatriates closed PnL for non base currencies to the base currency based on the current FX rates.
Parameters: timestamp: pandas.Timestamp
Time to create event for
action: str
Type of event to create, supports INTEREST, MARGIN, PNL and PNL_SWEEP
Returns: A list of events for being dispatched using dispatch_events()
-
define_generic
(generic, ccy=None, margin=0, multiplier=1, commission=0, isFX=False)¶ Define meta data for a tradeable instruments associated with a generic.
Parameters: generic: str
Name for the instrument type used for looking up meta data, e.g. we would define ‘CL’ and the associated meta data for these type of contracts
ccy: str
Currency that contract is traded in, default is base currency of blotter
margin: float
Amount of margin required for contract
multiplier: int
The multiplier to multiply the price by to get the notional amount of the instrument
commission: float
Commission charged for trading the instrument
isFX: boolean
Indicate if this instrument is an FX instrument. Affects whether cash balances are updated for calculating payable interest.
-
dispatch_events
(events)¶ Update Blotter._holdings based on event. See create_events() for the type of events supported. This method is best not called directly unless user understands what is going on.
Parameters: events: list
list of _Event to dispatch
-
event_log
¶ Returns the event log of events which have acted on the Blotter
-
get_holdings_value
(timestamp)¶ Return pandas.Series of values of holdings converted to Blotter base currency sorted by index name. Note that for each currency for which instruments are traded in, FX rates must be available for the given timestamp in order to convert. E.g. if Blotter base ccy is USD, and an instrument traded is in AUD, then AUDUSD must be available in the prices data folder.
Parameters: timestamp: pandas.Timestamp which corresponds to the time for
marking to market blotter holdings
-
get_instruments
()¶ Return pandas.Series of the number of instruments held.
-
map_instrument
(generic, instrument)¶ Define a mapping between tradeable instruments and generics, used for looking up meta data on instruments. Note in the case of a single instrument such as a currency pair the generic and the instrument can be the same value.
Parameters: generic: str
Name for the instrument type used for looking up meta data, e.g. we would define ‘CL’ and the associated meta data for these type of contracts
instrument: str
Tradeable instrument name
-
read_log
(fp)¶ Reconstitute a Blotter object from an event log. Note that this will only replay all the events, meta data and market data sources will need to be reloaded as well.
Parameters: fp: str
path to read log from
-
read_meta
(fp)¶ Reconstitute the meta data of a Blotter from a file. Reads as input files output by write_meta(). File formats should be of the following form
Parameters: fp: str
Path to file. File should have the following format
{“ccy”: “CAD”, “margin”: 0.1, “multiplier”: 100, “commission”: 2.5,”isFX”: false}|{“CL”: [“CLU16”, “CLZ16”]} {“ccy”: “CAD”, “margin”: 0, “multiplier”: 1, “commission”: 2.5, “isFX”: true}|{“USDCAD”: [“USDCAD”]}
...
-
trade
(timestamp, instrument, quantity, price)¶ Record an instrument trade in the Blotter. This will also make a call to automatic_events to trigger all automatic events up to the time of this trade.
Parameters: timestamp: pandas.Timestamp
Time of trade
instrument: str
Tradeable instrument name
quantity: int
Number of instrument traded
price: float
Price of trade
-
write_log
(fp)¶ Write log of blotter events to file. This can be used for reconstituting blotter.
Parameters: fp: str
path to write log to
-
write_meta
(fp)¶ Write meta data of associated instruments in a Blotter to a file. This can be used later to reconstitute a Blotter.
Parameters: fp: str
path to write meta data
-
-
class
blotter.blotter.
Holdings
¶ The Holdings class is designed to manage holdings data and PnL data. The class stores instrument level holdings data on a per currency basis and calculates PnL on a per currency basis given instrument prices. The class is primarily designed to manage these aspects from within the context of the Blotter class however can also provide this functionality stand alone.
The main features of the Holdings class include:
- Store per currency per instrument holindgs
- Calculate per currency per instrument PnL
- Maintain interest payable cash balances per currency
- Maintain charged/payed interest per currency
- Provide functionality to sweep PnL from one currency to another
- Return historical holdings
- Return historical PnL
Calculating PnL is done on a as of current holdings basis, there is no functionality for looking up historical holdings for calculating historic PnL.
Note: For interest bearing instruments, when users are using the Holdings call standalone, users are responsible for calling charge_interest() at appropriate intervals and with appropriate interest rates to ensure that the PnL calculations are correct. This is handled by the Blotter class.
All actions on the Holdings class must follow in time sequential order.
-
charge_interest
(timestamp, ccy, quantity)¶ Update the amount of interest charged in the account of a currency.
Parameters: timestamp: pandas.Timestamp
Time of trade
ccy: str
currency of interest charge/payment
quantity: float
Amount of interest
-
get_assets
()¶ Get the names of instruments held.
Returns: list
Sorted list of strings of current assets which have holdings
-
get_cash_balances
()¶ Return a pandas.Series of the cash balances for each currency
-
get_holdings
()¶ Get the current instrument holdings. This includes any multiplier associated with the instrument.
Returns: dictionary
Dictionary with currencies as keys and pandas.Series as values where that Series contain the most recent holdings for each of the holdings in a given currency
-
get_holdings_history
()¶ Get the full history of holdings for each instrument traded. This includes any multiplier associated with the instrument.
Returns: dictionary
Dictionary with currencies as keys and dictionary of pandas.Series as values where the keys of the nested dictionary are instrument names and the pandas.Series is a timeseries of holdings
-
get_instrument_pnl
(timestamp, prices=None, cache=True)¶ Calculate and return pnl, closed pnl and open pnl for traded instruments in each currency.
Parameters: timestamp: pandas.Timestamp
Time of PnL calculation, used for caching the result
prices: pandas.Series
series of instrument prices for current holdings
cache: boolean
Cache this result for later retrieval and advance internal Holdings event clock
Returns: dictionary
Dictionary with currencies as keys and pandas.DataFrame as values where the DataFrame contains columns [‘pnl’, ‘closed pnl’, ‘open pnl’] and the index is the set of holdings of current instruments
-
get_instrument_pnl_history
()¶ Return open, closed and total PnL in each currency for each traded instrumentbased on cached values from previous calls to get_instrument_pnl
Returns: dictionary
Dictionary of dictionaries where to top level dictionary contains keys for each currency where there has been PnL historically and the nested dictionaries contain keys for each instrument and values which are pandas.DataFrame with columns [‘pnl’, ‘closed pnl’, ‘open pnl’] and index of timestamps
-
get_pnl
(timestamp, prices=None, cache=True)¶ Calculate open, closed and total pnl in each currency where instruments are traded based on given prices.
Parameters: timestamp: pandas.Timestamp
Time of PnL calculation
prices: pandas.Series
series of instrument prices
cache: boolean
Cache this result for later retrieval and advance internal Holdings event clock
Returns: pandas.DataFrame
DataFrame with columns [‘pnl’, ‘closed pnl’, ‘open pnl’] and an index of currencies of instrument denominations. Note that this will return a row for each currency that an instrument has ever been traded in, even if the current PnL in the currency is all 0’s due to sweeps.
-
get_pnl_history
()¶ Return open, closed and total PnL in each currency where instruments are traded based on cached values from previous calls to get_instrument_pnl
Returns: dictionary
Dictionary of pandas.DataFrames where keys are currencies and the DataFrames have columns [‘pnl’, ‘closed pnl’, ‘open pnl’] and index of timestamps
-
record_trade
(timestamp, instrument, price, quantity, commission, ccy)¶ Record an instrument trade in Holdings. Trades must be time ordered.
Parameters: timestamp: pandas.Timestamp
Time of trade
instrument: str
Tradeable instrument name
price: float
Price of trade
quantity: int
Number of instruments traded. This should include any multiplier associated with the contract. E.g. for trading an ES contract, this has a multipler of 50, therefore 1 ES contract should correspond to a quantity of 50 * 1
commission: float
total commission for the trade
ccy: str
currency of instrument denomination
-
sweep_pnl
(timestamp, ccy1, quantity1, ccy2, quantity2)¶ Convert PnL from one currency to another. The user is responsible for ensuring that the implicit FX rates used are sensible.
Parameters: timestamp: pandas.Timestamp
Time of trade
ccy1: str
currency of first leg of sweep
quantity1: float
Amount of currency from first leg of sweep
ccy2: str
currency of second leg of sweep
quantity2: float
Amount of currency from second leg of sweep
Examples
>>> ts = pd.Timestamp('2016-12-01T10:00:00') aud = 5000 usd = 5000 * 0.80 holder.sweep_pnl(ts, 'AUD', -aud, 'USD', usd)
-
timestamp
¶ Returns the current timestamp of the Holdings
-
update_cash
(timestamp, ccy, quantity)¶ Update the amount of cash in a certain type of currency, used for charging interest on that balance.
Parameters: timestamp: pandas.Timestamp
Time of trade
ccy: str
currency of cash balance
quantity: float
Amount of cash