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.

450

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

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

)

This code continues looping until the backtest finishes (this being determined by the PriceHandler

object). It attempts to pull the latest Event from the queue and dispatches it to the correct

event handler object.

However the challenge here is that the previously mentioned sentiment signals CSV file also

contains timestamped sentiment signals. Hence it is necessary to "inject" the appropriate sentiment

signal for a particular ticker at the correct time point in the backtest.

This has been achieved by creating a new event called SentimentEvent. It stores a timestamp,

a ticker and a sentiment value (which can be a floating-point value, integer or a string)

that is sent to the Strategy object in order to generate SignalEvents. The QSTrader code for

SentimentEvent is as follows:

class SentimentEvent(Event):

"""

Handles the event of streaming a "Sentiment" value associated

with a ticker. Can be used for a generic "date-ticker-sentiment"

service, often provided by many data vendors.

"""

def __init__(self, timestamp, ticker, sentiment):

"""

Initialises the SentimentEvent.

Parameters:

timestamp - The timestamp when the sentiment was generated.

ticker - The ticker symbol, e.g. ’GOOG’.

sentiment - A string, float or integer value of "sentiment",

e.g. "bullish", -1, 5.4, etc.

"""

self.type = EventType.SENTIMENT

self.timestamp = timestamp

self.ticker = ticker

self.sentiment = sentiment

An additional object hierarchy called AbstractSentimentHandler has also been created.

It allows subclassing of sentiment handler objects for various vendor APIs, all shared through

a common interface. Since sentiment indicators are nearly always "timestamp-ticker-sentiment"

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

Saved successfully!

Ooh no, something went wrong!