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.

455

threshold, then it closes the position.

Hence the strategy presented below only goes long. It is a straightforward matter to extend

this to short trading. Example code for shorting has been presented in other trading strategies

to date. In particular the code for the Kalman Filter Pairs Trade provides this capability.

def calculate_signals(self, event):

"""

Calculate the signals for the strategy.

"""

if event.type == EventType.SENTIMENT:

ticker = event.ticker

# Long signal

if (

self.invested[ticker] is False and

event.sentiment >= self.sent_buy

):

print("LONG %s at %s" % (ticker, event.timestamp))

self.events_queue.put(SignalEvent(ticker, "BOT", self.qty))

self.invested[ticker] = True

# Close signal

if (

self.invested[ticker] is True and

event.sentiment <= self.sent_sell

):

print("CLOSING LONG %s at %s" % (ticker, event.timestamp))

self.events_queue.put(SignalEvent(ticker, "SLD", self.qty))

self.invested[ticker] = False

As with all QSTrader implemented strategies, there is a corresponding backtest file that

specifies the parameters of the strategy. It is very similar to the other backtest files found within

the book. Hence the full listing is only presented at the end of this chapter.

The main differences are the instantiation of the SentimentHandler object and setting of

the parameters for the entry and exit thresholds. These are set to 6 for entry and -1 for exit, as

reflected in the underlying strategy rules above. It is instructive (and potentially more profitable!)

to optimise these values for various sets of tickers.

The sentdex_sample.csv is placed in the QSTrader CSV_DATA_DIR, which is where the

pricing data also usually resides. The start and end dates reflect the duration over which the

Sentdex sample file contains sentiment predictions.

..

..

start_date = datetime.datetime(2012, 10, 15)

end_date = datetime.datetime(2016, 2, 2)

..

..

# Use the Sentdex Sentiment trading strategy

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

Saved successfully!

Ooh no, something went wrong!