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.

451

tuples, it is useful to create a unified interface.

To handle the Sentdex sample CSV file a SentdexSentimentHandler object has been written

into QSTrader. As with most handlers it requires a handle to the events queue, a subset of tickers

to act upon as well as a starting and ending date:

class SentdexSentimentHandler(AbstractSentimentHandler):

"""

SentdexSentimentHandler is designed to provide a backtesting

sentiment analysis handler for the Sentdex sentiment analysis

provider (http://sentdex.com/financial-analysis/).

It uses a CSV file with date-ticker-sentiment tuples/rows.

Hence in order to avoid implicit lookahead bias a specific

method is provided "stream_sentiment_events_on_date" that only

allows sentiment signals to be retrieved for a particular date.

"""

def __init__(

self, csv_dir, filename,

events_queue, tickers=None,

start_date=None, end_date=None

):

self.csv_dir = csv_dir

self.filename = filename

self.events_queue = events_queue

self.tickers = tickers

self.start_date = start_date

self.end_date = end_date

self.sent_df = self._open_sentiment_csv()

There are two methods associated with this class. The first is _open_sentiment_csv. It

wraps the opening of a CSV into a Pandas DataFrame along with associated ticker and date

filtering:

def _open_sentiment_csv(self):

"""

Opens the CSV file containing the sentiment analysis

information for all represented stocks and places

it into a pandas DataFrame.

"""

sentiment_path = os.path.join(self.csv_dir, self.filename)

sent_df = pd.read_csv(

sentiment_path, parse_dates=True,

header=0, index_col=0,

names=("Date", "Ticker", "Sentiment")

)

if self.start_date is not None:

sent_df = sent_df[self.start_date.strftime("%Y-%m-%d"):]

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

Saved successfully!

Ooh no, something went wrong!