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.

453

if event.type == EventType.TICK or event.type == EventType.BAR:

self.cur_time = event.time

# Generate any sentiment events here

if self.sentiment_handler is not None:

self.sentiment_handler.stream_next(

stream_date=self.cur_time

)

self.strategy.calculate_signals(event)

self.portfolio_handler.update_portfolio_value()

self.statistics.update(event.time, self.portfolio_handler)

elif event.type == EventType.SENTIMENT:

self.strategy.calculate_signals(event)

elif event.type == EventType.SIGNAL:

self.portfolio_handler.on_signal(event)

elif event.type == EventType.ORDER:

self.execution_handler.execute_order(event)

elif event.type == EventType.FILL:

self.portfolio_handler.on_fill(event)

else:

raise NotImplemented(

"Unsupported event.type ’%s’" % event.type

)

That concludes the modifications to QSTrader. These changes are now in the latest version

found on Github, so if you wish to replicate these strategies, make sure to update your local

QSTrader version.

30.4.2 Sentiment Analysis Strategy Code

The full code listings for this strategy and backtest are presented at the end of the chapter.

The above modifications to QSTrader provide the necessary structure to run a sentiment

analysis strategy. However it remains to be shown how the above entry and exit rules are

actually implemented. As it turns out the majority of the "hard work" has been done in the

above modules. The strategy implementation itself is relatively straightforward.

As always the first task is to import the necessary libraries. There are no surprises here,

simply Python2/3 compatibility and the basic QSTrader objects that interact with a Strategy

subclass:

# sentdex_sentiment_strategy.py

from __future__ import print_function

from qstrader.event import (SignalEvent, EventType)

from qstrader.strategy.base import AbstractStrategy

The new subclass is called SentdexSentimentStrategy. It only requires a list of tickers to

act upon, a handle to the events queue, a sent_buy integer sentiment threshold entry value and

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

Saved successfully!

Ooh no, something went wrong!