13.08.2022 Views

advanced-algorithmic-trading

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

387

ues of the market value of a "unit" of the portfolio in self.port_mkt_value. A self.invested

flag allows the strategy itself to keep track of whether it is "in the market" or not:

class CointegrationBollingerBandsStrategy(AbstractStrategy):

"""

Requires:

tickers - The list of ticker symbols

events_queue - A handle to the system events queue

lookback - Lookback period for moving avg and moving std

weights - The weight vector describing

a "unit" of the portfolio

entry_z - The z-score trade entry threshold

exit_z - The z-score trade exit threshold

base_quantity - Number of "units" of the portfolio

to be traded

"""

def __init__(

self, tickers, events_queue,

lookback, weights, entry_z, exit_z,

base_quantity

):

self.tickers = tickers

self.events_queue = events_queue

self.lookback = lookback

self.weights = weights

self.entry_z = entry_z

self.exit_z = exit_z

self.qty = base_quantity

self.time = None

self.latest_prices = np.full(len(self.tickers), -1.0)

self.port_mkt_val = deque(maxlen=self.lookback)

self.invested = None

self.bars_elapsed = 0

The following _set_correct_time_and_price method is similar to that found in the subsequent

QSTrader Kalman Filter chapter. The goal of this method is to make sure that the

self.latest_prices array is populated with the latest market values of each ticker. The strategy

will only execute if this array contains a full set of prices, all containing the same time-stamp.

This ensures that if market events arrive "out of order" then the strategy always has enough

pricing information to act upon.

A previous version of this method was fixed for an array of two prices but the code below

works for any number of tickers, which is necessary for cointegrating portfolios that might contain

three or more assets:

def _set_correct_time_and_price(self, event):

"""

Sets the correct price and event time for prices

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!