13.08.2022 Views

advanced-algorithmic-trading

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

454

a sent_sell corresponding exit threshold. Both of these are specified later in the backtest code.

In addition a base quantity of shares is required for trading. In order to keep the strategy

relatively straightforward the position sizing solely buys and sells such a base quantity for each

ticker at any time point in the strategy. That is, there is no dynamic adjustment of position sizes

or percentage allocation to any ticker. In a production strategy this would be one of the first

parts to optimise. Since this position sizing code is likely to distract from the main "sentiment"

aspect of the strategy, it was decided that it be kept simple for this chapter.

Finally a self.invested dictionary member is created to store whether each ticker is currently

being traded. This is done by adjusting a boolean True/False value for each ticker

depending upon whether a long position is open or not:

class SentdexSentimentStrategy(AbstractStrategy):

"""

Requires:

tickers - The list of ticker symbols

events_queue - A handle to the system events queue

sent_buy - Integer entry threshold

sent_sell - Integer exit threshold

base_quantity - Number of shares to be traded

"""

def __init__(

self, tickers, events_queue,

sent_buy, sent_sell, base_quantity

):

self.tickers = tickers

self.events_queue = events_queue

self.sent_buy = sent_buy

self.sent_sell = sent_sell

self.qty = base_quantity

self.time = None

self.tickers.remove("SPY")

self.invested = dict(

(ticker, False) for ticker in self.tickers

)

As with all subclasses of AbstractStrategy the calculate_signals method is where the

actual event-driven trading rules are placed. In all other QSTrader strategies to date this method

has responded to BarEvent or TickEvent objects.

In every strategy presented thus far the first line in this method always checks what the event

type is (if event.type == EventType...). This provides greater flexibility in AbstractStrategy

subclasses, since they can respond to arbitrary events, not just those based around asset pricing

data.

Once the event has been confirmed as a SentimentEvent the code checks whether that

particular ticker is already being traded. If not, it checks whether the sentiment exceeds the

sentiment integer entry threshold and then creates a long of the base quantity of shares. If it

is already trading this ticker, and the current sentiment threshold is below the provided exit

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

Saved successfully!

Ooh no, something went wrong!