Data Mining Twitter Data with Python

Twitter is an online social networking service that enables users to send and read short 140-character messages called “tweets”. [1]
Twitter users are tweeting about different topics based on their interests and goals.
A word, phrase or topic that is mentioned at a greater rate than others is said to be a “trending topic”. Trending topics become popular either through a concerted effort by users, or because of an event that prompts people to talk about a specific topic. [1]
There is wide interest in analyzing of trending data from Twitter.
And in this post we will look at searching and downloading the tweets related to specific hashtag. We will use Python and Twitter API. Our example will be search tweets related to “deep learning”. After downloading Twitter data we will also look at some data manipulations with the data.

The example of downloading of Twitter data is based on the work [2]
Below is source code:

import twitter
import json
CONSUMER_KEY =”xxxxxx”
CONSUMER_SECRET =”xxxxxx”
OAUTH_TOKEN = “xxxxxx”
OAUTH_TOKEN_SECRET = “xxxxxx”
auth = twitter.oauth.OAuth (OAUTH_TOKEN, OAUTH_TOKEN_SECRET, CONSUMER_KEY, CONSUMER_SECRET)
twitter_api= twitter.Twitter(auth=auth)
q=’#deep learning’
count=100
search_results = twitter_api.search.tweets (q=q, count=count)
statuses=search_results[‘statuses’]
for _ in range(5):
    print “Length of statuses”, len(statuses)
    try:
        next_results=search_results[‘search_metadata’][‘next_results’]
    except KeyError, e: #result does not exist
         break
    kwargs=dict( [kv.split(‘=’) for kv in next_results[1:].split(“&”)])
    search_results = twitter_api.search.tweets(**kwargs)
    statuses += search_results[‘statuses’]
# Show one sample search result by slicing the list
print json.dumps(statuses[0], indent=10)
hashtags = [ hashtag[‘text’]
    for status in statuses
        for hashtag in status[‘entities’][‘hashtags’] ]
urls = [ urls[‘url’]
    for status in statuses
        for urls in status[‘entities’][‘urls’] ]
texts = [ status[‘text’]
    for status in statuses
         ]
#Created_at is date time when created
created_ats = [ status[‘created_at’]
    for status in statuses
        ]
print json.dumps(hashtags[0:50], indent=1)
print json.dumps(urls[0:50], indent=1)
print json.dumps(texts[0:50], indent=1)
print json.dumps(created_ats[0:50], indent=1)
# Now we append some data into the file
with open(“data.txt”, “a”) as myfile:
    for w in hashtags:         myfile.write(w)
        myfile.write(“\n”)
# count of word frequencies
wordcounts = {}
for term in hashtags:
    wordcounts[term] = wordcounts.get(term, 0) + 1
items = [(v, k) for k, v in wordcounts.items()]
for count, word in sorted(items, reverse=True):
    print(“%5d %s” % (count, word))
# in case we need extract date or month or year
for x in created_ats:
    print x
    print x[4:10]
    print x[26:31]
    print x[4:7]

Output example for last for loop (just one cycle)
Wed Mar 30 02:10:20 +0000 2016
Mar 30
2016
Mar

Any comments or suggestions are welcome.

References
[1] https://en.wikipedia.org/wiki/Twitter Twitter, From Wikipedia
[2] http://www-scf.usc.edu/~aupadhya/Mining.pdf MINING DATA FROM
TWITTER by Abhishanga Upadhyay, Luis Mao, Malavika Goda Krishna



7 Ideas for Building Text Mining Application

It is no doubt that the web is growing at an incredible pace. And as the most documents of the web consist of the text, the applications of text analytics or text mining are getting more use. In such applications the textual data are used for extracting intelligence from a large collection of documents. Here are 7 ideas for building this type of applications. Later on during this year 2016 some online working demo examples on this site will be built to test the ideas. The focus is on applications for personal use. Business applications of text mining can be found in [1]

1. Trending is collecting historical data in order to find pattern or predict future. If the usage of word phrase “python programming” is going up from month to month then it is good signal for paying attention to this. There is the tool Google Trends is a public web facility of Google Inc., based on Google Search, that shows how often a particular search-term is entered relative to the total search-volume across various regions of the world, and in various languages. The horizontal axis of the main graph represents time (starting from 2004), and the vertical is how often a term is searched for relative to the total number of searches, globally. [2]

However what if we more focused on the future and we want know what terms will be popular in the future. For example “data science” or “big data” are now popular search terms but back to the time when the usage was the lowest – if the tool can predict high increase of usage in such situation – that would be very useful.

2. Building news feed is another example of application for text mining. Newly published web based content if it matches the user interest has a great value. So the application should allow for user to set the topics for the desired content.
For the same topic the user might be interesting in the ability to set other filters such as source of content, type of content and some other characteristics of content.
Over the time the user interests will change and so the application should learn and adapt to user interests too.

3.Post editing. While someone online is typing article for blog or paper there is always the need to find something related to topic on the web. Imagine that it will automatically show an additional text box with similar content from the web. This would eliminate switching back to search engine and also can bring something new that the author even did not think about.

4. Automatic creation of data reports is very helpful for people who needs data for their research or business needs. There a lot of data and information freely available on the web however it is tedious go to online on weekly or monthly basis and manually extract data and put in some file or database for further analysis. Such task often will include such things as formatting data, merging the information from different sources and some other processing operations.

5. Sentiment analysis (also known as opinion mining) refers to the use of natural language processing, text analysis and computational linguistics to identify and extract subjective information in source materials. Sentiment analysis is widely applied to reviews and social media for a variety of applications, ranging from marketing to customer service. [3]
Almost each online text analytics web based service is offering sentiment analysis option for users. There are also many online examples how to do sentiment analysis using python or R as programming language. [4]
Sentiment analysis application would be useful for predicting some financial event or collecting opinion about some product.

6. Content Organizing application can organize documents into groups by topic, keywords or by some other means.
We can subscribe and receive email notifications about site news, latest post or new article. The application that is saving links that we liked or decided to review later can help us be more productive. In addition to links it would save some information about links like keywords, topics or description. Such application could also group information by topic or keyword and automatically assign additional keywords.
Text document clustering and classification would be used a lot for this application.

7. Topic detection application can be used for automatic text categorization, for understanding what people are talking about, for automatic processing or preprocessing emails or user submitted online articles, comments.
The task of topic detection might also require the
development of approaches related to the presentation
of topics: topic ranking, relevant image retrieval, title
and keyword extraction. One of the example of using topic detection is shown in [5]
Obviously one document can consist of several segments on different topics. In one of researches simple clustering algorithm was used to group the semantically-related sentences. The distance between two sentences was calculated based on the distance between
all nouns that appear in the sentences. The distance between two nouns was calculated using the Wordnet thesaurus. [6],[7]

References

1. Text Mining and its Business Applications http://www.codeproject.com/Articles/822379/Text-Mining-and-its-Business-Applications

2. https://en.wikipedia.org/wiki/Google_Trends Google Trends
From Wikipedia

3. https://en.wikipedia.org/wiki/Sentiment_analysis Sentiment analysis
From Wikipedia

4. https://support.sas.com/resources/papers/proceedings14/1288-2014.pdf
Analysis of Unstructured Data: Applications of Text Analytics
and Sentiment Mining, Dr. Goutam Chakraborty, Murali Krishna Pagolu

5. http://ceur-ws.org/Vol-1150/petkos.pdf
Two-level message clustering for topic detection in
Twitter. Georgios Petkos ,Symeon Papadopoulos, Yiannis Kompatsiaris

6. A Non-Linear Topic Detection Method for Text
Summarization Using Wordnet

Click to access Wksp-Tec-Info-Ling-Silla-2003.pdf

Carlos N. Silla Jr. , Celso A. A. Kaestner, Alex A. Freitas

7. https://www.uni-weimar.de/medien/webis/events/tir-08/tir08-papers-final/wartena08-topic-detection-by-clustering-keywords.pdf
Topic Detection by Clustering Keywords. Christian Wartena and Rogier Brussee



Calculating Indicators for Stock Data Forecasting

In the previous posts was shown how to download stock data into Google spreadsheet using perl script. Here we will look how to add other data indicators based on downloaded stock data prices and volume. The use for stock data prediction of such indicators based on stock data that is usually is available for downloading can be viewed in data mining papers [1], [2] More links and some notes can be found at input-for-stock-data-prediction. Here is the link to stock data analysis perl module with the source code to calculate simple moving average, force index indicator, momentum and some other. In the near future will be added calculations for other indicators.

And here an example how the functions from this module can be used in any perl program:

use warnings;
use stock_data_analysis;
for($i=0; $i<10; $i++) { $data[$i]=$i; $vol[$i]=2; } for($i=0; $i<10; $i++) { print $data[$i]; print "\n"; } @diff_data= stock_data_analysis::do_diff(@data); for($i=0; $i<10; $i++) { print $diff_data[$i]; print "\n"; } print “\n”; print “mean=”; print stock_data_analysis::get_mean(@data); print “\n\n”; @a=stock_data_analysis::sma(4, @data); for($i=0; $i<10; $i++) { print $a[$i]; print "\n"; } print “\n\n”; @a=stock_data_analysis::get_FI(1, \@data, \@vol); for($i=0; $i<10; $i++) { print $a[$i]; print "\n"; } Thus now we can add above indicators to downloaded stock price data in Google spreadsheet. References 1. Financial Stock Market Forecast using Data Mining Techniques K. Senthamarai Kannan, P. Sailapathi Sekar, M.Mohamed Sathik and P. Arumugam, IMECS 2010 2. The Comparison of Methods Artificial Neural Network with Linear Regression Using Specific Variables for Prediction Stock Price in Tehran Stock Exchange, Reza Gharoie Ahangar, Mahmood Yahyazadehfar, Hassan Pournaghshband, (IJCSIS) International Journal of Computer Science and Information Security, Vol. 7, No. 2, February 2010



Calculating Indicators for Stock Data Forecasting

In the previous posts was shown how to download stock data into Google spreadsheet using perl script. Here we will look how to add other data indicators based on downloaded stock data prices and volume. The use for stock data prediction of such indicators based on stock data that is usually is available for downloading can be viewed in data mining papers [1], [2] More links and some notes can be found at input-for-stock-data-prediction. Here is the link to stock data analysis perl module with the source code to calculate simple moving average, force index indicator, momentum and some other. In the near future will be added calculations for many others indicators. And here an example how the functions from this module can be used in any perl program: use warnings; use stock_data_analysis; for($i=0; $i<10; $i++) { $data[$i]=$i; $vol[$i]=2; } for($i=0; $i<10; $i++) { print $data[$i]; print "\n"; } @diff_data= stock_data_analysis::do_diff(@data); for($i=0; $i<10; $i++) { print $diff_data[$i]; print "\n"; } print "\n"; print "mean="; print stock_data_analysis::get_mean(@data); print "\n\n"; @a=stock_data_analysis::sma(4, @data); for($i=0; $i<10; $i++) { print $a[$i]; print "\n"; } print "\n\n"; @a=stock_data_analysis::get_FI(1, \@data, \@vol); for($i=0; $i<10; $i++) { print $a[$i]; print "\n"; } Thus now we can add above indicators to downloaded stock price data in Google spreadsheet. References 1. Financial Stock Market Forecast using Data Mining Techniques K. Senthamarai Kannan, P. Sailapathi Sekar, M.Mohamed Sathik and P. Arumugam, IMECS 2010 2. The Comparison of Methods Artificial Neural Network with Linear Regression Using Specific Variables for Prediction Stock Price in Tehran Stock Exchange, Reza Gharoie Ahangar, Mahmood Yahyazadehfar, Hassan Pournaghshband, (IJCSIS) International Journal of Computer Science and Information Security, Vol. 7, No. 2, February 2010



Input for Stock Data Prediction Algorithms

What can be used for input to stock data prediction system? In this post we will consider some indicator that often are used for stock data forecasting. The links to information about indicators and how to calculate will be also provided.

Moving averages are often used in technical analysis. A few examples: Simple Moving Average (SMA) – to calculate SMA for period of n days we take sum of prices for the n days going back and divide by n. Then move to next day and do it again.

Exponential Moving Average (EMA) – with this moving average the recent data are getting more weight than other. With SMA all data points are getting the same weight.

Here is the indicator that uses prices and volume: Force Index. In two words it is showing how strong is the current trend, how likely it will continue or change.[1] Force index for 1 period can be calculated as

Force Index(1) = (Close_Price (current) – Close_Price (prev)) x Volume

The list of indicators with the information how they are calculated can be found at [2]. They are divided in 3 groups, price based, volume based and breadth indicators. Breadth indicators are based on statistics derived from the broad market. Some papers on stock data forecasting also describe very well the list of variables that were chosen for input.

If we look we can find that there are many different choices but it can improve the quality of forecast accuracy.[3],[4] Not only price , volume or other market statistics can be used for stock market forecasting. Textual web data can be also used but it requires web/text mining processing. You can find some example at [5]

References

1.How to Use Force Index
2.Technical analysis From Wikipedia, the free encyclopedia
3. The Comparison of Methods Artificial Neural Network with Linear Regression Using Specific Variables for Prediction Stock Price in Tehran Stock Exchange Reza Gharoie Ahangar,Mahmood Yahyazadehfar,Hassan Pournaghshband (IJCSIS) International Journal of Computer Science and Information Security, Vol. 7, No. 2, February 2010
4.Financial Stock Market Forecast using Data Mining Techniques K. Senthamarai Kannan, P. Sailapathi Sekar, M.Mohamed Sathik and P. Arumugam, IMECS 2010, hong Kong
5.Daily Stock Market Forecast from Textual Web Data B. Wuthrich, V. Cho, S. Leung, D. Permunetilleke, K. Sankaran, J. Zhang, W. Lam, The Hong Kong University of Science and Technology
6. Technical Indicators and Overlays From StockCharts.com – ChartSchool 7.Financial Stock Market Forecast using Data Mining Techniques K. Senthamarai Kannan, P. Sailapathi Sekar, M.Mohamed Sathik and P. Arumugam