Created
February 14, 2017 19:43
-
-
Save ngopal/317f94a65efd54c427c7be8a1c512da6 to your computer and use it in GitHub Desktop.
The beginnings of a stock twit dashboard.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
library(syuzhet) | |
library(igraph) | |
library(RCurl) | |
plotDashBoard <- function(ticker) { | |
twits <- getURL(paste("https://api.stocktwits.com/api/2/streams/symbol/",ticker,".json", sep="")) | |
twts.tab <- fromJSON(twits) | |
# Sentiment | |
twt.sent <- get_nrc_sentiment(twts.tab$messages$body) | |
# Network | |
stockAtHand <- paste('$',toupper(ticker),sep="") | |
stockEdgeList <- matrix(0, 2, 3) | |
stockFreq <- c(stockAtHand) | |
for (m in twts.tab$messages$body) { | |
tickerMatches <- gregexpr("\\$[a-zA-Z]+", m) | |
indices <- unlist(tickerMatches) | |
tlens <- attr(tickerMatches[[1]], "match.length") | |
for (i in 1:length(indices)) { | |
assocStock <- toupper(substr(m, indices[i], indices[i]+tlens[i]-1)) | |
# Edgelist Processing | |
if (stockAtHand == assocStock) { | |
# Do nothing | |
} | |
else if (!(assocStock %in% stockEdgeList[,2])) { | |
stockEdgeList <- rbind(stockEdgeList, | |
c(stockAtHand,assocStock,1)) | |
} | |
else if (assocStock %in% stockEdgeList[,2]) { | |
stockEdgeList[which(stockEdgeList[,2] == assocStock),3] = as.numeric(stockEdgeList[which(stockEdgeList[,2] == assocStock),3]) + 1 | |
} | |
# Freq List Processing | |
stockFreq <- append(stockFreq, assocStock) | |
} | |
stockFreq <- append(stockFreq, stockAtHand) | |
} | |
stockEdgeList <- stockEdgeList[which(stockEdgeList[,1] != 0),] | |
stockEdgeList | |
stockFreq <- as.data.frame(table(stockFreq)) | |
g <- graph.data.frame(stockEdgeList, directed=F, vertices=NULL) | |
vweights <- c() | |
for (v in names(V(g))) { | |
vweights <- append(vweights, stockFreq[which(stockFreq[,1] == v),2]) | |
} | |
dev.off() | |
par(mfrow=c(1,2)) | |
barplot(apply(twt.sent, MAR=2, sum), las=2) | |
plot(g, | |
vertex.size = vweights, | |
edge.width = (as.numeric(stockEdgeList[,3]) / max(as.numeric(stockEdgeList[,3])))*5 | |
) | |
} | |
plotDashBoard('tsla') | |
plotDashBoard('aapl') | |
plotDashBoard('goog') | |
plotDashBoard('bp') | |
plotDashBoard('indy') | |
plotDashBoard('fb') | |
plotDashBoard('jnj') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment