Tutorial for using Twitter events in your trading strategies

Twitter support depends on tweepy (https://github.com/tweepy/tweepy) so be sure to have it installed before moving forward.

The goal of this short tutorial is to illustrate how to connect to Twitter to process events. We will also be using a live BarFeed since backtesting on Twitter is not supported.

In order to connect to Twitter’s API you’ll need:
  • Consumer key
  • Consumer secret
  • Access token
  • Access token secret

Go to http://dev.twitter.com and create an app. The consumer key and secret will be generated for you after that. Then you’ll need to create an access token under the “Your access token” section.

from pyalgotrade import strategy
from pyalgotrade.mtgox import client
from pyalgotrade.mtgox import barfeed
from pyalgotrade.mtgox import broker
from pyalgotrade.twitter import feed as twitterfeed

import datetime

class Strategy(strategy.BaseStrategy):
    def __init__(self, instrument, feed, brk, mtgoxClient, twitterFeed):
        strategy.BaseStrategy.__init__(self, feed, brk)
        self.__instrument = instrument

        # Subscribe to Twitter events.
        twitterFeed.subscribe(self.onTweet)

        # It is VERY important to add the these to the event dispatch loop before running the strategy.
        self.getDispatcher().addSubject(mtgoxClient)
        self.getDispatcher().addSubject(twitterFeed)

    def onTweet(self, data):
        # Refer to https://dev.twitter.com/docs/streaming-apis/messages#Public_stream_messages for
        # the information available in data.
        try:
            print datetime.datetime.now(), "Twitter:", data["text"]
        except KeyError:
            pass

    def onBars(self, bars):
        print bars.getDateTime(), "Price:", bars[self.__instrument].getClose(), "Volume:", bars[self.__instrument].getVolume()

def main():
    # Go to http://dev.twitter.com and create an app.
    # The consumer key and secret will be generated for you after that.
    consumer_key="<YOUR-CONSUMER-KEY-HERE>"
    consumer_secret="<YOUR-CONSUMER-SECRET-HERE>"

    # After the step above, you will be redirected to your app's page.
    # Create an access token under the the "Your access token" section
    access_token="<YOUR-ACCESS-TOKEN-HERE>"
    access_token_secret="<YOUR-ACCESS-TOKEN-SECRET-HERE>"

    # Create a twitter feed to track BitCoin related events.
    track = ["bitcoin", "btc", "mtgox"]
    follow = []
    languages = ["en"]
    twitterFeed = twitterfeed.TwitterFeed(consumer_key, consumer_secret, access_token, access_token_secret, track, follow, languages)

    # Create a client responsible for all the interaction with MtGox
    mtgoxClient = client.Client("USD", None, None)
    mtgoxClient.setEnableReconnection(False)

    # Create a real-time feed that will build bars from live trades.
    feed = barfeed.LiveTradeFeed(mtgoxClient)

    # Create a backtesting broker.
    brk = broker.BacktestingBroker(200, feed)

    # Run the strategy with the feed and the broker.
    strat = Strategy("BTC", feed, brk, mtgoxClient, twitterFeed)
    strat.run()

if __name__ == "__main__":
    main()
The code is doing 5 things:
  1. Creating a feed to connect to Twitter’s public stream API and setting the proper filtering parameters.
  2. Creating a client to connect to MtGox. For papertrading purposes we only need to specify the currency to use.
  3. Creating a live feed that will build bars from the trades received through the client.
  4. Creating a broker for backtesting. The broker will charge a 0.6 % fee for each order.
  5. Running the strategy with the bars supplied by the feed and the backtesting broker. Note that the strategy adds MtGox client and Twitter feed to the event dispatch loop.

If you run this example you should see something like this:

2013-08-25 00:09:15,137 mtgox [INFO] Initializing MtGox client.
2013-08-25 00:09:15,679 mtgox [INFO] Connection opened.
2013-08-25 00:09:15,679 mtgox [INFO] Initialization ok.
2013-08-25 00:09:15,680 twitter [INFO] Initializing Twitter client.
2013-08-25 00:09:16,599 twitter [INFO] Connected.
2013-08-25 00:09:31.480728 Twitter: Profit: $165.84 (10.3%). BUY B15.02 @ $106.97 (#BTCe). SELL @ $119.30 (#MtGox) #bitcoinarbitrage
2013-08-25 00:09:35.153556 Price: 120.17807 Volume: 0.01404198
2013-08-25 00:09:38.507910 Price: 119.30693 Volume: 0.1
2013-08-25 00:09:39.746267 Twitter: I smile and make that btc mad
2013-08-25 00:09:54.934998 Price: 119.30696 Volume: 0.01076
2013-08-25 00:10:04.020095 Twitter: Grease Payments to Miners https://t.co/yFqCM6ASLN #bitcoin
2013-08-25 00:10:06.902383 Twitter: Profit: $95.59 (8.7%). BUY B10.13 @ $108.50 (#CampBX). SELL @ $119.31 (#MtGox) #bitcoinarbitrage
2013-08-25 00:10:13.842662 Twitter: No sex btc i only want the neck btc
2013-08-25 00:10:20.092048 Twitter: Btc ain wan let me win that iphone 5 tho
2013-08-25 00:10:28.564280 Price: 119.30845 Volume: 0.01
2013-08-25 00:10:38.542615 Twitter: Profit: $111.29 (10.3%). BUY B10.13 @ $106.97 (#BTCe). SELL @ $119.31 (#MtGox) #bitcoinarbitrage
2013-08-25 00:10:41.299799 Price: 119.30921 Volume: 0.01
2013-08-25 00:10:46.162057 Twitter: RT @BitcoinASIA: Hash for Money is the only medication to #bitcoin Hash Addiction !
2013-08-25 00:10:45.987947 Price: 119.30921 Volume: 0.01063
2013-08-25 00:10:46.297285 Twitter: RT @BitcoinASIA: Cure yourself of #bitcoin Hash Addiction, its Very Very Dangerous !
2013-08-25 00:10:46.443162 Twitter: RT @bitcoininfo: Grease Payments to Miners https://t.co/yFqCM6ASLN #bitcoin
2013-08-25 00:10:47.486786 Price: 119.30922 Volume: 0.01
.
.
.

Previous topic

Trading based on Twitter events

Next topic

twitter – Twitter feed reference

This Page