1 Algorithmic Trading Of Cryptocurrency Based On Twitter .

1y ago
399.15 KB
5 Pages
Last View : 4d ago
Last Download : 4m ago
Upload by : Mariam Herr

1Algorithmic Trading of CryptocurrencyBased on Twitter Sentiment AnalysisStuart Colianni, Stephanie Rosales, and Michael SignorottiF1A BSTRACTPAST research has shown that real-time Twitter data canbe used to predict market movement of securities andother financial instruments [1]. The goal of this paper isto prove whether Twitter data relating to cryptocurrencies can be utilized to develop advantageous crypto cointrading strategies. By way of supervised machine learningtechniques, our team will outline several machine learningpipelines with the objective of identifying cryptocurrencymarket movement. The prominent alternative currency examined in this paper is Bitcoin (BTC). Our approach tocleaning data and applying supervised learning algorithmssuch as logistic regression, Naive Bayes, and support vector machines leads to a final hour-to-hour and day-to-dayprediction accuracy exceeding 90%. In order to achieve thisresult, rigorous error analysis is employed in order to ensurethat accurate inputs are utilized at each step of the model.This analysis yields a 25% accuracy increase on average.2I NTRODUCTIONCryptocurrency is an alternative medium of exchangeconsisting of numerous decentralized crypto coin types.The essence of each crypto coin is in its cryptographicfoundation. Secure peer to peer transactions are enabledthrough cryptography in this secure and decentralizedexchange network. Since its inception in 2009, the Bitcoinhas become a digital commodity of interest as some believethe crypto coins’ worth is comparable to that of traditionalfiat currency.Considering the exchange rates of cryptocurrencies arenotorious for being volatile, our team strives to develop aneffective trading strategy that can be applied to a variety ofcryptocurrencies. Our method for determining the optimaltime to trade involves correlating prices with one of today’smost popular social media sources, Twitter. The advantagesof using Twitter include having access to some of theearliest and fastest news updates in a concise format as wellas being able to extract data from this social media platformwith relative ease.Our trading strategy applies supervised machine learningalgorithms including support vector machines, logistic regression, and Naive Bayes to determine whether the price ofa particular digital currency will increase or decrease withina predetermined time interval. The two approaches fortraining these classifiers involve using direct text, otherwiseknown as tweets, from Twitter users and using third partyopen-source sentiment analysis APIs to rate the positivityand negativity of words within each post. Both of thesetraining methods prove to be effective in estimating the trajectory of cryptocurrency prices. In order to predict marketmovement to a particular granularity, a time series of tweetsequal in length to the trading period is required one cyclebeforehand. This time series of Twitter posts is used as aninput to the classifiers.3R ELATED W ORKApplying machine learning to cryptocurrency is a relativelynew field with limited research efforts. Using Bayesianregression, Shah et al. achieved an 89% return on investmentover fifty days of buying and selling Bitcoins [8]. Anotherapproach predicted the price change of Bitcoin usingrandom forests with 98.7% accuracy [4]. These approachesfail to consider the feelings of individuals about Bitcoin,and therefore, fail to harness these potential features in theirlearning algorithms. Twitter sentiment analysis has beenwidely researched. Bollen et al. utilized the Profile of MoodStates (POMS) to predict the movement of the Dow JonesIndustrial Average with 87.6% accuracy. Go et. al focusedonly on classifying tweets and used several approachesto achieve an accuracy of 84.2% with Multinomial NaiveBayes, 79.2% with maximum entropy, and 82.9% using asupport vector machine [2]. This paper will expand on theapproaches of researches in the past and apply Twittertext classification and sentiment analysis to cryptocurrencymarkets.4DATAIn order to create a training and testing data set for thelearning algorithms, we utilize Tweepy - an open-sourcePython library for accessing the Twitter API [10]. Thekeyword,bitcoin, is searched in real time and tweetscontaining this token is placed into a text file. Additionaldata being collected for each post containing the keywordincludes the user ID, a unique identifier which cannotbe changed, and a time stamp. In addition, the pricesof the cryptocurrency is collected every hour via thecryptonator.com API and placed into text files to create a

2price history [6].While tweets are collected in real time, excess white spaceis removed and the text is changed to lowercase. To cleanthe data, the following procedure is carried out. Thefirst step is to remove all non-alphabetic characters. Thesecond step is to remove duplicates. The reason for doingthis is because of the prevalence of Twitter bots, manyof which instantaneously disseminate tweets containingparticular keywords. Not removing these tweets will causethe distribution of words in our training set to be skewed.Invalid English words which remain are identified andremoved based on not having membership in the ”words”corpus of the Natural Language Toolkit [5]. Stop words aresubsequently removed from tweets based on membershipin the ”stopwords” corpus of the Natural Language Toolkit.We then create two data sets: one with stemming andone without. In the stemming set, all remaining wordsare stemmed using the Porter Stemming algorithm. Then,entries which no longer contain words are removed fromthe data set.The duration of the data collection process was 463 hoursspanning over twenty-one days. During this period, over 1million tweets pertaining solely to Bitcoin were collected.The processed data set consists of over 350,000 individualswho posted at least once about Bitcoin. The distribution ofthe number of Bitcoin related tweets per user is exhibited inFigure 1. Please note that the x axis is in log scale due to thelarge variance in tweets per user.In order to ensure accurate prediction results across all days,it is important to consider whether the number of datapoints each day is fairly consistent. Figure 2, which displaysthe number of tweets that mention Bitcoin per day, provesthe posting frequency for this particular class of tweet isrelatively uniform.Fig. 2. The above chart shows the number of Bitcoin related tweets perday from November 15, 2015 to December 3, 2015. The dates includedare limited to days with continuous data collection.5In order to determine digital currency market movementwith the Twitter data set, text classification and sentimentanalysis algorithms are utilized. The goal of each algorithmis to predict whether the price of Bitcoin will increase ordecrease over a set time frame. For the text classificationapproach, the implementations of Naive Bayes, logisticregression, and support vector machines in the Scikit Pythonlibrary are utilized [7]. Training and testing on sentimentanalysis data requires the same implementation of supportvector machines and logistic regression. Although bothtypes of algorithms are trained on the same data set, thefundamental approaches to formatting each model’s featurevector is quite different.5.1Fig. 1. The number of Bitcoin related tweets per user is displayed above.The x axis is in log scale. The data was collected from November 15,2015 to December 4, 2015.M ETHODFeature VectorsFor the examples below, suppose that we wish to reconstructthe processed version of the following tweet into a featurevector (without the removal of stop words).Bitcoin has a bright future in the world’s economy.As displayed in Figure 1, the majority of individualscontributed only a few times throughout the data collectionperiod. Although some users tweet far more than others,the individuals with the most posts only contribute to afraction of the 1 million tweet data set. Half of all users whoposted at least one tweet about Bitcoin only tweeted onceabout the digital currency.The features for text classification consist of a vector ofall unique words in the data set lexicon. Since the vectorencompasses all possible unique entries, it is sparse evenfor the longest of tweets. Suppose that there are n words inthe learning algorithm’s vocabulary. An example of a textclassification feature vector for this model with each entry x {0, 1}n is as follows.

3 00 . . . . 1 bright . . . . 1 economy . . . . x 1 f uture . . . . 0 0 . . . . 1 worlds . . . .00When a particular word is observed at least once, a binaryvalue of one is recorded in the position of that word inthe feature vector. When the total count of each word isrepresented in the same format of feature vector, the inputis modeled as multinomial rather than Bernoulli. Therefore,the entries in a multinomial feature vector will take onvalues x {1, 2, .k}n .Training and testing feature vectors for sentiment analysismodels are fundamentally different. In order to generatefeature vectors of this structure, preprocessed tweets areanalyzed word-by-word in the text-processing.com API [9].This API returns scores between zero and one for words’positivity, negativity, and neutrality. These scores are aggregated into a single vector similar to the one below. 0.80x 0.76 .205.2Naive BayesThe Naive Bayes is a generative learning algorithm whichis commonly applied to text classification and sentimentanalysis machine learning problems. This approach to textclassification utilizes the first format of feature vector wherethe appearance of a word is modeled by either the Bernoullior multinomial distribution. In both versions of this algorithm, we assume the xi variable given Y in the Naive Bayesmathematical program below to be conditionally independent of one another.argmax P (Y yj )yjmYP (xi Y yj )built for both positive and negative variation in the market.For each observation in the training set, the above productof probabilities is calculated assuming each market trend,and the results are compared. The classification resultingin the higher probability is assumed true and subsequentlyassigned to that particular post.5.3Logistic RegressionDiscriminative learning algorithms such as logistic regression are also useful in the field of text classification andsentiment analysis. Unlike generative learning algorithms,this model examines two classes in the training set anddetermines the best separation. The logistic regression learning algorithm can be derived by maximizing the followinglikelihood function.L(θ) mY(i)(hθ (x(i) ))y (1 hθ (x(i) ))1 y(i)i 1In this likelihood function, x( i) takes the form of eitherof the previously mentioned feature vectors. The index, i,maps the feature vector to one of the observations in thetraining set of size m. The exponent, y (i) , represents thestate of the market for feature vector i. The function hθ isthe sigmoid function below.g(z) 11 exp zIn order to determine an update rule for the parameters,theta, the log likelihood function can be formulated. Thisfunction can then be differentiated in order to derive thestochastic gradient ascent formula below.(i)θj : θj α(y (i) hθ (x(i) ))xjAfter reaching convergence, the parameters, theta, are utilized in the sigmoid function in order to classify the state ofthe digital currency market.5.4Support Vector MachinesSupport vector machines are supervised learning algorithmsthat can perform nonlinear classifications by mapping datato higher dimensions through the use of the kernel trick.Support vector machines are an effective tool in sentimentanalysis as proven by Go [2]. The L1 Norm Soft Marginmodel below can be trained with either the text classificationfeature vector or the sentiment analysis feature vector.i 1mminIn this formulation, yj represents the classification ofwhether the Bitcoin price is increasing or decreasing overa predetermined time interval. The variable xi is the featurevector for tweet i where a total of m tweets are collected.Since this is a generative learning algorithm, a model can beX1kwk22 Cξi2i 1s.t. y (i) (wT x(i) b) 1 ξiξi 0i 1, ., mi 1, ., m

4Fig. 4. Accuracy Using Sentiment as Feature VectorThis support vector machine has the L1 norm soft marginformulation which includes a penalty term for points whichare not linearly separable. This penalty term for this modelis below.mXCξii 1The term, ξi , is a slack variable. The penalty equation acts asa trade off between having a large separation between termsand incorrectly classifying observations. The feature vector,x( i), is used with both the text classification and sentimentanalysis forms outlined earlier in the section. The variable,y (i) , is the observed class for a particular observation.5.5Fig. 5. Confusion Matrix - Bernoulli NB Day-to-DayTraining and TestingTraining and testing the models for the text classificationand sentiment analysis problems involves nearly identicalsteps. We partitioned the training set in a 70-30 split where70% of the data is reserved for training and 30% is markedfor testing. When performing this random sampling, weassure there is an equal representation of tweets from bothclasses while maintaining an accurate timeseries representation. After training the model on this balanced training set,we record the rate at which samples are classified correctlywith respect to the test set data points. We repeat thisprocedure ten times and aggregate the correct classificationrates over all iterations.6classifier (Logistic Regression using sentiment scores) andthe most accurate day to day classifier (Bernoulli NaiveBayes and Multinomial Naive Bayes using the tweet as afeature vector).R ESULTSWe tested classifiers using two data sets: one where thetweet had been stemmed using Porter stemming and onewithout. To assess the performance of different classifiers,we computed the accuracy of each. In every case, the accuracy of the classifier was on par or significantly better whenoperating on the unstemmed data.In our first classification attempts, we treated the wordsin a tweet as elements of the feature vector for each classifier.Bernoulli Naive Bayes performed the best out of all textclassification algorithms by achieving a day to day accuracyof 95.00% and an hour to hour accuracy of 76.23%.Fig. 3. Accuracy Using Tweet as Feature VectorIn our second classification attempts, we used the textprocessing.com API to calculate negativity, neutrality, andpositivity scores for each tweet. The API also returns a positive, neutral, or negative label. These labels were used as thefeature vectors for Naive Bayes (Bernoulli and Multinomial).The return scores were used as the feature vectors for theclassifiers. Logistic Regression performed the best using thisfeature vector achieving a day to day accuracy of 86.00%and an hour to hour accuracy of 98.58%.A confusion matrix along with the precision, recall, andF-Score were calculated for the most accurate hour to hourFig. 6. Confusion Matrix - Logistic Regression Hour-to-HourThe precision matrix for day-to-day results has a precision of 1, a recall of 0.92, an accuracy of 0.95 and an FScore of 0.96. The negative predicted value calculated to0.89, and the true negative rate calculated to 1. The precisionmatrix for hour-to-hour results has a precision of 0.99, arecall of 0.98, an accuracy of 0.986 and an F-Score of 0.99.The negative predicted value calculated to 0.98, and the truenegative rate calculated to 0.99.7E RROR A NALYSISOur initial accuracy for predicting the hour to hour signchange of Bitcoin using the Bernoulli Naive Bayes classifierwas 59.0%. In order to determine the possible error locations within the machine learning pipeline, we thoroughlyinspected inputs at each step. During one of the data processing steps, we noticed many near duplicate posts thatdiffered based on numerical ID values within the tweets’text. In order to remove these automated postings, weadjusted the data cleaning procedure by removing all nonalphabetic characters before removing duplicate tweets. Inorder to ensure these automated postings were removed,we computed the Levenshtein distance from each tweetto every other tweet. The Levenshtein distance is the editdistance between two strings. This value can be leveragedto prove that any pair of tweets is dissimilar by at leastsome threshold value. After cleaning, the new data setwas roughly 50% smaller, but yielded a significantly betterclassification accuracy of 76.23%.8F UTURE W ORKIn order to further improve the accuracy of the learningalgorithms, additional research can be performed in the areaof error analysis. An improvement that can be exploredfor text classification algorithms involves accounting for

5negation as outlined by Jurafsky et al [3]. According toJurafsky, an efficient method of accounting for negation intext analysis is to prepend the prefix, not , after a negatedword. An additional modification that can be made tothe training set is to ensure that the training set has anequal number of words associated with each classification.Although our sets are relatively equal (8061 words in theprice decrease set and 8852 in the price increase set), creatinga training set that is completely unskewed could result inlower classification error. In addition, we can formulate aset of words where each element has a high correlation withcryptocurrency market movement and use this as a basis fortraining the learning algorithms. This adjustment will resultin sparser feature vectors for text classification and possiblymore accurate predictions.R EFERENCES[1] Bollen, Johan, and Huina Mao. Twitter Mood Predicts the StockMarket. http://arxiv.org/pdf/1010.3003\&. 14 Oct. 2010. Web. 12Nov. 2015.[2] Go, Alec, Lei Huang, and Richa Bhayani. Twitter sentiment analysis.Entropy 17 (2009).[3] Jurafsky, Daniel. Classification: Naive Bayes, Logistics Regression, Sentiment8, 2015. Web. 12 Dec. 2015.[4] Madan, Isaac, Saluja, Shaurya, and Aojia Zhao, Automated BitcoinTrading via Machine Learning Algorithms, Department of ComputerScience, Stanford University.[5] Natural Language Toolkit. Natural Language Toolkit NLTK 3.0Documentation. 2015. Web. 11 Dec. 2015[6] Online Bitcoin Wallet. Cryptonator. 2014. Web. 11 Dec. 2015.[7] Scikit-learn. : Machine Learning in Python 0.17 Documentation.Web. 11 Dec. 2015.[8] Shah, Devavrat and Kang Zhang Bayesian Regression and Bitcoin.http://arxiv.org/pdf/1410.1231v1.pdf. 6 Oct. 2014. Web. 12 Nov.2015.[9] Text-processing.com. API Documentation for Text-processing.comText-processing.com API 1.0 Documentation. Web. 11 Dec. 2015.[10] Tweepy. Tweepy. Web. 11 Dec. 2015.

Algorithmic Trading of Cryptocurrency Based on Twitter Sentiment Analysis Stuart Colianni, Stephanie Rosales, and Michael Signorotti F . Python library for accessing the Twitter API [10]. The keyword,bitcoin, is searched in real

Related Documents:

Algo trading TOTAL TRADING ALGORITHMIC TRADING HIGH FREQUENCY TRADING . Algorithmic trading: In simple words an algorithmic trading strategy is a step-by-step instruction for trading actions taken by computers (au

Algorithmic Trading Table: Proportions of trading volume contributed by di erent category of algorithmic and non-algorithmic traders in the NSE spot and equity derivatives segment (for the period Jan-Dec 2015) Custodian Proprietary NCNP Total Spot Market Algo 21.34% 13.18% 7.76% 42.28% Non-

Introduction: Algorithmic trading Developing an automated trading decision engine – Identify a successful trading rule – Extend trading rule set – Automate trading rule selection Implementing MATLAB int

the algorithmic trading strategy’s design; typically, broker algorithmic trading systems seek to minimize the cost of trading by optimizing the execution strategy—that is, minimize market impact cost or time to execution, optimize the price, and so on—whereas proprietary algo - rithmic

trading is not inherently harmful to market integrity or quality – in fact algorithmic trading plays an important role in developing liquidity. Equally, algorithmic trading is not, by definition, inherently good for market quality and integrity. Significant order f

Algorithmic trading (automated trading, black-box trading, or simply algo-trading) is the process of using computers programmed to follow a defined set of instructions for placing a trade in order to generate

Algorithmic trading is any software which follow a predefined algorithm to place trading instructions High-frequency trading is algorithmic trading characterized with very

The Effect of Algorithmic Trading on Liquidity in the Options Market Abstract Algorithmic trading consistently reduces the bid-ask spread in options markets, regardless of firm size, option strike price, call or put option, or volatility in the markets. Howeve

Algorithmic Trading System in question (see Good Practice Statement 3 for more detail); sufficiently granular oversight of the financial and non-financial risks relating to Algorithmic Trading (which, depending on the size of the firm, may include establishing regional, product or as

Jan 07, 2016 · to resume trading after an event —there may be scope for firms to wind down their operations instead. Market making strategy MiFID II imposes obligations on algorithmic traders when they pursue a market making strategy. A person engaged in algorithmic trading will be consid

of algorithmic trading over the last two decades. The fi rst is the fact that the fi nan-of algorithmic trading over the last two decades. The fi rst is the fact that the fi nan-cial system is becoming more complex over time, not less. Greater complexity is a consequence of general economic growth and globalization in which the number of

ADVANCED ALGORITHMIC TRADING STRATEGIES IN PYTHON Learn to find alpha in financial markets using artificial intelligence and quantitative techniques. Get trained by experts such as Dr. Ernest P. Chan, with decades of trading experience. Learn to code and backtest your own trading strategy in Python

Any strategy for algorithmic trading requires an identified opportunity that is profitable in terms of improved earnings or cost reduction. In this paper, the study focuses on evaluating few trading strategies and trading . we used a Quantopian platform (Algorithm IDE), which is a Python

Market Microstructure and Algorithmic Trading PIMS Summer School 2016 University of Alberta, Edmonton Lecture 2: July 4, 2016. Edmonton mini-course, July 2016 Exchanges Decide trading rules: Trading hours Match alg

High-frequency trading (“HFT”), or high-speed trading1 (“HST”), a type of algorithmic (or “algo”) trading, is now a well-known feature of the global market landscape. In many markets, a small number of firms may account for a large proportion of trading volume. Although it has

when they sell the same cryptocurrency into fiat currency later on. Taxation of Cryptocurrency Block Rewards: Comparative Summary . The Law Library of Congress 3 . The income tax treatment of mining is

Understanding Cryptocurrency (updated May 2018) Ari Paul. CIO, Managing Partner. BlockTower Capital. Cryptocurrency is at the intersection of game theory, cryptography, computer science, economics, venture capital, and public markets. Don’t be scared. These

Apr 09, 2020 · of blockchain technology, cryptocurrency systems protect their public ledgers of accounts against manipulation, so that users can only send cryptocurrency to which they have access, thus allowing users to make val

This paper provides a concise yet comprehensive analysis of the cryptocurrency industry using the PESTLE model with a focus on Bitcoin and its investment. 1.6 Research Methods This paper is based on a descriptive study focuses on secondary data, the majority of information comes from journal articles, news, opinions from cryptocurrency .

AngularJS is an extensible and exciting new JavaScript MVC framework developed by Google for building well-designed, structured and interactive single-page applications (SPA). It lays strong emphasis on Testing and Development best practices such as templating and declarative bi-directional data binding. This cheat sheet co-authored by Ravi Kiran and Suprotim Agarwal, aims at providing a quick .