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.

389

commands, so that the positions can be closed or shorted:

def go_short_units(self):

"""

Go short the appropriate number of "units" of the

portfolio to open a new position or to close out

a long position.

"""

for i, ticker in enumerate(self.tickers):

if self.weights[i] < 0.0:

self.events_queue.put(SignalEvent(

ticker, "BOT",

int(floor(-1.0*self.qty*self.weights[i])))

)

else:

self.events_queue.put(SignalEvent(

ticker, "SLD",

int(floor(self.qty*self.weights[i])))

)

zscore_trade takes the latest calculated z-score of the portfolio market price and uses this

to long, short or close a trade. The logic below encapsulates the "Bollinger Bands" aspect of the

strategy.

If the z-score is less than the negative of the entry threshold, a long position is created.

If the z-score is greater than the positive of the entry threshold, a short position is created.

Correspondingly, if the strategy is already in the market and the z-score exceeds the negative of

the exit threshold, any long position is closed. If the strategy is already in the market and the

z-score is less than the exit threshold, a short position is closed:

def zscore_trade(self, zscore, event):

"""

Determine whether to trade if the entry or exit zscore

threshold has been exceeded.

"""

# If we’re not in the market...

if self.invested is None:

if zscore < -self.entry_z:

# Long Entry

print("LONG: %s" % event.time)

self.go_long_units()

self.invested = "long"

elif zscore > self.entry_z:

# Short Entry

print("SHORT: %s" % event.time)

self.go_short_units()

self.invested = "short"

# If we are in the market...

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

Saved successfully!

Ooh no, something went wrong!