• This repository has been archived on 23/Feb/2022
  • Stars
    star
    189
  • Rank 200,709 (Top 5 %)
  • Language
    Python
  • Created over 9 years ago
  • Updated over 7 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Trend detection algorithms for Twitter time series data

Introduction

This repository contains the "Trend Detection in Social Data" whitepaper, along with software that implements a variety of models for trend detection.

We focus on trend detection in social data times series. A time series is defined by the presence of a word, a phrase, a hashtags, a mention, or any other characteristic of a social media event that can be counted in a series of time intervals. To do trend detection, we quantify the degree to which each count in the time series is atypical. We refer to this figure of merit with the Greek letter eta, and we say that a time series and its associated topic are "trending" if the figure of merit exceeds a pre-defined threshold denoted by the Greek letter theta.

Whitepaper

The trends whitepaper source can be found in the paper directory, which also includes a subdirectory for figures, figs. A PDF version of the paper is included but it is not gaurenteed to be up-to-date. A new version can be generated from the source by running:

pdflatex paper/trends.tex

Installation of pdflatex and/or additional .sty files may be required.

Gnip-Trend-Detection Software

Input Data

The input data consists of CSV records, and is expected to contain data for one quantity ("counter") and one time interval on each line, in the following format:

interval start time interval duration in sec. count counter name
2015-01-01 00:03:25.0 195 201 TweetCounter
2015-01-01 00:03:25.0 195 13 ReTweetCounter
2015-01-01 00:06:40.0 195 191 TweetCounter
2015-01-01 00:06:40.0 195 10 ReTweetCounter

The format of the interval start time can be any of the large number of standard formats recognized by Python's dateutil package.

The recommended way to produce time series data in the correct format is to use the Gnip-Analysis-Pipeline package. With this package, you can enrich and aggregate Tweet data from the Gnip APIs. You can find a set of dummy data in example/example.csv.

Installation

The package can be pip-installed. The 'plotting' extra includes matplotlib, and can be ignored if plotting is not important. Note that the examples below require plotting.

$ pip install gnip_trend_detection[plotting]

The scripts and library in the repository can also be pip-installed locally.

[REPOSITORY] $ pip install -e .[plotting]

Depending on your operating system, you may need to set a Matplotlib backend, often done in ~/.matplotlib/matplotlibrc.

Key functionalities

The software in this package provides three scripts that perform the three main tasks:

  • trend_rebin.py - resize the time intervals of the input data
  • trend_analyze.py - calculate a figure-of-merit (trend score) at each point
  • trend_plot.py - plot the counts and the figure-of-merit

These scripts act on and deliver CSV data.

A fourth script, trend_analyze_many.py, performs these steps sequentially, with re-binning and analysis done in parallel. To manage the (potentially) large number of time series, this script uses JSON-formatted intermediate and final data strutures.

Two final scripts provide extra analysis information:

  • trend_detection.py
    • return information about time series data sets with trend figures-of-merit that exceed a threshold. This script is intended to be used on the analyzed output of the trend_analyze_many.py script.
  • time_series_correlations.py
    • calculate a correlation coefficient between all pairs of time series in a CSV data set (BUGS BE HERE).

Configuration

All the scripts mentioned in the previous sections assume the presence of a configuration file. By default, its name is config.cfg. You can find a template at config.cfg.example. A few parameters can be set with command-line argument. Use the scripts' -h option for more details.

Example

A full example has been provided in the example directory. In it, you will find formatted time series data for mentions of the "#scotus" hashtag in August-September 2014. This file is example/example.csv. In the same directory, there is a configuration file, which specifies what the software will do, including the size of the final time buckets and the trend detection technique and parameter values. This example assumes that you have installed the package, but are working from the repo directory. The example will run from any location, but the paths to input and configuration files would have to change.

The first step to to use the rebin script to get appropriately and evenly sized time buckets. Let's use 2-hour buckets and put the output back in the the example directory.

cat example/example.csv | trend_rebin.py -c example/config.cfg > example/scotus_rebinned.csv

Next, we will run the analysis script on the re-binned data. Remember, all the modeling specification is in the config file.

cat example/scotus_rebinned.csv | trend_analyze.py -c example/config.cfg > example/scotus_analyzed.csv

To view results, let's run the plotting after the analysis, both of which are packaged in the plotting script:

cat example/scotus_analyzed.csv | trend_plot.py -c example/config.cfg

The configuration specifies that the output PNG should be in the example directory. It will look like:

scotus

This analysis is based on a point-by-point Poisson model, with the previous point defining the expectation for the current point. You must still choose the cutoff value of eta (called theta) that defines the presence of a trend. It is clear that, if you wish to flag the large spike as a trend, almost any choice for theta will lead to lots of false positives.

A more robust background model can be used by changing the mode parameter in the Poisson_model section of the example/config.cfg from lc (last count) to a (average). The period_list parameter determines the time interval over which the average is taken.

The output PNG should for this model should look like:

scotus

There is less noise in this result, but we can do better. Choose the data-derived template method in example/config.cfg by uncommenting model_name=WeightedDataTemplates. In this model, eta quantifies the extent to which the test series looks more like a set of known trending time series, or like a set of time series known not to be trending.

The output PNG should for this model should look like:

scotus

In this result, there is virtually no noise, but the eta curve lags the data because of the data smoothing procedure. Nevertheless, this model provides the most robust performance, at the cost of additional complexity and CPU time. The ROC curve for this model looks like:

roc

The previous methods focus on identifying sudden increases, or spikes, in the time series. To identify trends characterized by constant growth over time, you can use a linear regression. Choose the LinearRegressionModel in the config file, and the output PNG should look like:

roc

Analysis Model Details

The various trend detection techniques are implemented as classes in gnip_trend_detection/models.py. The idea is for each model to get updated point-by-point with the time series data, and to store internally whichever data is need to calculate the figure of merit for the latest point.

Each class must define:

  • a constructor that accepts one argument, which is a dictionary containing configuration name/value pairs.
  • an update method that accepts at least a keyword argument "counts", representing the latest data point to be analyzed. No return value.
  • a get_results method, which takes no arguments and returns the figure of merit for the most recent update.

More Repositories

1

Twitter-API-v2-sample-code

Sample code for the Twitter API v2 endpoints
JavaScript
2,444
star
2

twitter-api-typescript-sdk

A TypeScript SDK for the Twitter API
TypeScript
927
star
3

search-tweets-python

Python client for the Twitter 'search Tweets' and 'count Tweets' endpoints (v2/Labs/premium/enterprise). Now supports Twitter API v2 /recent and /all search endpoints.
Python
841
star
4

getting-started-with-the-twitter-api-v2-for-academic-research

A course on getting started with the Twitter API v2 for academic research
Python
534
star
5

twitter-api-java-sdk

A Java SDK for the Twitter API
Java
228
star
6

postman-twitter-api

Postman Collection for the Twitter API v2
203
star
7

cards-player-samples

Sample Code for Player Cards, both for stored and streamed video.
HTML
195
star
8

twitter-python-ads-sdk

A Twitter supported and maintained Ads API SDK for Python.
Python
185
star
9

account-activity-dashboard

Sample web app and helper scripts to get started with the premium Account Activity API
JavaScript
169
star
10

autohook

Automatically setup and serve webhooks for the Twitter Account Activity API
JavaScript
152
star
11

twitter-for-bigquery

Simplest way to get Tweets into BigQuery. Uses Google Cloud & App Engine, as well as Python and D3.
Python
141
star
12

large-video-upload-python

Sample Python code for uploading video up to 140 seconds and/or up to 512Mb.
Python
125
star
13

do_more_with_twitter_data

Tutorials for getting the most out of Twitter data.
Makefile
102
star
14

bookmarks-to-notion

A sample app that exports your bookmarks to a Notion page
Python
89
star
15

real-time-tweet-streamer

JavaScript
79
star
16

SnowBotDev

An example #TwitterBot illustrating the Twitter Account Activity and Direct Message APIs.
Ruby
79
star
17

twitter-webhook-boilerplate-node

A simple Node.js app using Express 4 for Twitter DMs and webhooks.
JavaScript
71
star
18

twitter-ruby-ads-sdk

A Twitter supported and maintained Ads API SDK for Ruby.
Ruby
66
star
19

FactualCat-Twitter-Bot

A Twitter bot example using the v2 manage Tweets functionality
Python
60
star
20

tweet_parser

Reliably parse Tweets delivered by Twitter Data products in both the activity-streams and original formats.
Python
53
star
21

search-tweets-ruby

Ruby client for the Twitter search endpoints (v2/Labs/premium/enterprise). Now supports Twitter API v2 /recent and /all search endpoints.
Ruby
53
star
22

bookmarks-search

Search your Twitter Bookmarks
JavaScript
50
star
23

postman-twitter-ads-api

Postman collection for the Twitter Ads API
JavaScript
46
star
24

chrome-extension-collections

Chrome extension for reporters to organize tweets and oEmbed them into their CMS system.
JavaScript
43
star
25

tweet-search

Sample code showing Tweet activity volume using Twitter's Enterprise full-archive search API. Built with Django, Tweet embeds and C3.
JavaScript
42
star
26

open-evolution

Open evolution proposals for the Twitter API
42
star
27

node-timeline-visualizations

Interactive timeline of when your friends joined Twitter. Uses Node.js, twit and vis.js.
JavaScript
37
star
28

remote-dev-jobs-streamer

Match Tweets containing remote developer jobs using Filtered Stream and Tweet Annotations
JavaScript
37
star
29

tweet-updates

This repository contains information about the 2017 updates to Tweet formats for attachments and simplified replies.
HTML
34
star
30

ruby-app-tweetmap

Simple Ruby app to read Twitter stream and map geo-tweets on a Google Map.
Ruby
33
star
31

spotatweet

A Spotify & Twitter API mashup showing what people are listening to now. Written in Node.js.
JavaScript
32
star
32

Gnip-Insights-Interface

Interface to Twitter's Engagement API
Python
31
star
33

twitter-context-annotations

Flat files containing available context annotation entities.
30
star
34

labs-sample-code

Sample code for Twitter Developer Labs
JavaScript
25
star
35

oauth2.0-bot

Sample code for creating a bot with OAuth 2.0 Authorization Code Flow with PKCE and V2 of the Twitter API.
Python
23
star
36

extract-usernames-from-tweet-replies

Python script to pull replies to a specific Tweet and extract user mentions
Python
23
star
37

ios-conversation-id-sample

Easily read recent public threads
Swift
22
star
38

tweet-notifier

A serverless app on AWS that gets Tweets of interest and publishes those to Slack, Amazon Chime & via Twilio SMS
Java
21
star
39

engagement-api-client-ruby

This example Engagement API Client helps manage the process of generating engagement metadata for large Tweet collections.
Ruby
21
star
40

weekly-tweet-sentiment

A tutorial which walks you through how you can create code that pulls your Tweets from the past 7 days and gives you a score to let you know exactly how your week has been.
Jupyter Notebook
21
star
41

web-recipes

Recipes to build #hashtag campaigns, Tweet intents and other experiences using Twitter for Web.
JavaScript
20
star
42

streaming-demos-node

Basic demos using Twitter streaming APIs with sample/filter streams. Built with node.js.
JavaScript
19
star
43

twitter-streaming-framework

TypeScript/Node.js framework for processing Twitter data stream.
TypeScript
18
star
44

Twitter-API-to-Google-Sheets

A code sample that allows you to send a payload from the Twitter API to Google Sheets.
Jupyter Notebook
16
star
45

account-activity-dashboard-enterprise

Sample web app and helper scripts to get started with the enterprise Account Activity API
JavaScript
14
star
46

Bookmarks-Notion-Notebook

Jupyter Notebook
14
star
47

gcloud-toolkit-recent-search

JavaScript
14
star
48

spaces-reach

A template app to show you how to get started with the Twitter Spaces API endpoints
JavaScript
14
star
49

compliant-client

A set of Python scripts for the Tweet and User batch compliance endpoints. Includes an app that manages it all in one go.
Python
14
star
50

enterprise-scripts-python

Sample Python scripts to help get started with the Twitter Enterprise APIs
Python
13
star
51

chrome-extension-tweetbar

Chrome Extension to add sidebar of Tweets to Youtube.
JavaScript
13
star
52

5-ways-to-convert-json-to-csv

JavaScript
12
star
53

.github

TwitterDev GitHub Organization-wide files
12
star
54

bot-profile-append

A Python script to help you add user attributions to your Twitter bots
Python
11
star
55

Gnip-Analysis-Pipeline

A processing pipeline for JSON-formatted Tweet data, such as that returned by Twitter APIs.
Python
11
star
56

parking

Jupyter Notebook
10
star
57

gcloud-toolkit-filtered-stream

Google Cloud Toolkit for the Filtered Stream API
JavaScript
10
star
58

ETL

An example app demonstrating storing Tweets in a Google Spreadsheet
TypeScript
9
star
59

dog-facts

A repository of sample code designed to help you Tweet random dog facts
Python
9
star
60

remote-dev-jobs-analytics

Learn 5 must know things about remote developer jobs posts on Twitter
JavaScript
9
star
61

twitter-aws-samples

Sample scripts for Twitter data processing and storage on AWS
Python
9
star
62

live-leaderboard

This Flask app listens for incoming scores via Twitter Direct Messages, ranks them, and Tweets the rankings.
Python
9
star
63

gcloud-toolkit-power-track

Google Cloud Toolkit for Twitter Enterprise - PowerTrack API
JavaScript
9
star
64

micpic

Easily stan your favorite K-pop stars via an iOS 14 widget
Swift
8
star
65

export-bookmarks

Export your Bookmarked Tweets with Flask
Python
8
star
66

twitter-alexa-skill-apl

A sample Alexa skill that brings the Twitter experience to Alexa Devices that support APL. For multimodal devices, you can see Tweets about a certain topic, or trends for a city.
Java
8
star
67

Pull-Tweet-Annotations-data-for-Twitter-profiles

Python code to identify most common topics mentioned by a Twitter profile, using Tweet Annotations and Recent Search API
Python
7
star
68

search-tweets-python-in-r

Running the Python library search-tweets-python in R
R
6
star
69

Tweet-Annotations

App to demo various features and functionality powered by Tweet Annotations and the Twitter API v2
Python
6
star
70

covid19-helper

Chatbot template to help developer direct users towards useful COVID-19 resources in their own language.
JavaScript
6
star
71

cat-pics

Resources for Tweeting cat pictures.
Python
5
star
72

noun-verb

A bot that Tweets noun/verb pairings
Python
4
star
73

Gnip-Tweet-Evaluation

Python
4
star
74

mytwitterjam

Create a Spotify Playlist from songs shared on Twitter
JavaScript
4
star
75

make-music-together

Code for Jessica Garson's PyCon talk on making music with SuperCollider, FoxDot and Python.
Python
4
star
76

ruby-enterprise-scripts

Sample Ruby scripts for using the Twitter Enterprise APIs
Ruby
3
star
77

analytics-tag-check

Chrome extension to check for proper installation of Twitter Conversion Tracking tags
JavaScript
3
star
78

getting-started-with-r

Sample code for a blog post about how to use R with the Twitter API. Uses the rtweet library
R
3
star
79

twitter-full-archive-search-ui

React based UI integrated to full archive search API
JavaScript
3
star
80

serverless-flow-framework

Run and scale realtime data analysis flows on serverless infrastructure
TypeScript
3
star
81

gnip-python-sdk

Simple wrapper around Gnip Search API in Python.
Python
3
star
82

getting-started-with-dash

Getting started with data visualization with Dash and recent search counts
Python
2
star
83

run-your-favorite-python-package-in-r

An example of how to call a the Twitter API from a Python package inside of R.
R
2
star
84

engagement-api-explorer

A fun way to explore metrics for your Tweets or for the public conversation
JavaScript
2
star
85

hashtag-graph-viz

Example graph vizualisations for Mozfest 2022
Jupyter Notebook
2
star
86

Gnip-Analysis-Tools

Python
1
star
87

cashtag-counts

Jupyter Notebook
1
star
88

twitter-enterprise-gcp

Enterprise API usage examples on Google Cloud Platform
JavaScript
1
star
89

Plot-Bookmarks

Plot your Bookmarks with Python
Python
1
star
90

JSON-to-CSV-livestream

Jupyter Notebook
1
star
91

Code-from-TwitterDev-Twitch-streams

Sample code from @TwitterDev Twitch streams
Python
1
star
92

Gnip-Filter-Optimization

Tools for optimizing Gnip PowerTrack rules and other downstream filters
Python
1
star
93

aws-toolkit-recent-search

Python
1
star
94

TwitterDev-live-streams

Code from live streams
Python
1
star
95

sports-coach

An example app showing how to use the Hide Replies API to keep conversations on topic.
JavaScript
1
star