forked from jaNGOB/twittermoney
-
Notifications
You must be signed in to change notification settings - Fork 0
/
4_2_sentiment_indices.R
186 lines (153 loc) · 7.07 KB
/
4_2_sentiment_indices.R
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
# Programming Project #14
# Ivana Pallister, Ricardo Cosenza, Alec Bernasconi, Jan Gobeli
# 26.12.2020
#
# Code to gauge sentiment of individual tweets and create a dataframe containing daily positive or negative
# average of twitter sentiment.
#
library(sentimentr)
library(ggplot2)
library(PerformanceAnalytics)
library(dplyr)
library(stringr)
library(tidyquant)
# Import and convert data used to create a sentiment index.
price <- read.csv("Data/stock_prices.csv", row.names = "Index")
price <- xts(price, order.by = as.Date(row.names(price)))
daily_sent <- read.csv('Data/daily_sentiment.csv', row.names = 'Index')
daily_sent <- xts(daily_sent, order.by = as.Date(row.names(daily_sent)))
# convert stock prices into daily logarithmic returns.
pct_returns <- price
for (n in 1:length(colnames(price))){
new <- dailyReturn(price[,n], type = "log")
pct_returns[,n] <- new
}
pct_returns[is.na(pct_returns)] <- 0
pct_returns[is.infinite(pct_returns)] <- 0
# Create two quarterly weighted portfolios of stocks having positive or negative sentiment on average.
fquarter <- xts(t(sapply(daily_sent['2020-01-01'], mean)), order.by = as.Date('2020-01-01'))
squarter <- xts(t(sapply(daily_sent['2020-01-02/2020-03'], mean)), order.by = as.Date('2020-04-02'))
tquarter <- xts(t(sapply(daily_sent['2020-04/2020-06'], mean)), order.by = as.Date('2020-07-01'))
lquarter <- xts(t(sapply(daily_sent['2020-07/2020-09'], mean)), order.by = as.Date('2020-10-01'))
quarterly <- rbind.xts(fquarter,squarter,tquarter,lquarter)
quarterly[is.na(quarterly)] <- 0
QuarterlyIndex<- function(w) {
# Function to create a xts frame containing the time-series of a weighted
#
# :input w: quarterly weights
# :output: xts
Index1 <- xts(pct_returns["2020/2020-03-31"] %*% t(w[1,]), order.by = as.Date(index(pct_returns["2020/2020-03-31"])))
Index2 <- xts(pct_returns["2020-04-01/2020-06-30"] %*% t(w[2,]), order.by = as.Date(index(pct_returns["2020-04-01/2020-06-30"])))
Index3 <- xts(pct_returns["2020-07-01/2020-09-30"] %*% t(w[3,]), order.by = as.Date(index(pct_returns["2020-07-01/2020-09-30"])))
Index4 <- xts(pct_returns["2020-10-01/2020-11-30"] %*% t(w[4,]), order.by = as.Date(index(pct_returns["2020-10-01/2020-11-30"])))
Index <- rbind.xts(Index1,Index2,Index3,Index4)
return(Index)
}
# Initiate an empty matrix which will be filled by "pos" if the average quarterly sentiment is positive
# or "neg" if it is negative.
quarterly_ <- matrix(NA, nrow = length(quarterly[,1]), ncol = length(quarterly[1,]))
for(n in 1:length(quarterly[1,])) {
for(q in 1:length(quarterly[,1])) {
pos_sent <- quarterly[q,n] > 0
if(pos_sent == TRUE) {
quarterly_[q,n] <- "pos"
} else {
quarterly_[q,n] <- "neg"
}
}
}
# Initiate two empty matrices to fill them with equal weight compared to how many other stocks have a
# positive/negative average sentiment in each quarter.
negativeQrt <- matrix(NA, nrow = length(quarterly[,1]), ncol = length(quarterly[1,]))
positiveQrt <- matrix(NA, nrow = length(quarterly[,1]), ncol = length(quarterly[1,]))
for(g in 1:length(quarterly[1,])) {
for(h in 1:length(quarterly[,1])) {
TotalPositive <- sum(quarterly_[h,] == "pos")
TotalNegative<- sum(quarterly_[h,] == "neg")
isNegative <- quarterly_[h,g] == "neg"
if(isNegative == TRUE) {
negativeQrt[h,g] <- (1/TotalNegative)
positiveQrt[h,g] <- 0
} else {
positiveQrt[h,g] <- (1/TotalPositive)
negativeQrt[h,g] <- 0
}
}
}
# Replace the colnames so they are easily identifiable again and convert it to an xts.
colnames(negativeQrt) <- colnames(quarterly)
colnames(positiveQrt) <- colnames(quarterly)
positiveQrt <- xts(positiveQrt, order.by = as.Date(c("2020-01-01", "2020-04-01", "2020-07-01", "2020-10-01")))
negativeQrt <- xts(negativeQrt, order.by = as.Date(c("2020-01-01", "2020-04-01", "2020-07-01", "2020-10-01")))
# Create quarterly indices using the function stated above called "QuarterlyIndex".
posIndexQrt <- QuarterlyIndex(positiveQrt)
negIndexQrt <- QuarterlyIndex(negativeQrt)
# Download the data of the Symbol "IRX" to get the Riskfree for the creation of annualized returns / st-dev and sharpe.
getSymbols("^IRX", from ="2019-12-31", to = "2020-11-30", src = "yahoo", auto.assign = T)
rf <-mean(IRX$IRX.Adjusted['2020']/100, na.rm=T)
table.AnnualizedReturns(posIndexQrt, Rf =rf/length(pct_returns$AMZN["2020"]), geometric = F)
table.AnnualizedReturns(negIndexQrt, Rf =rf/length(pct_returns$AMZN["2020"]), geometric = F)
# Plot the two Indices just created.
QuarterlyIndices <- merge(posIndexQrt, negIndexQrt)
colnames(QuarterlyIndices) <- c('Positive Index', 'Negative Index')
charts.PerformanceSummary(QuarterlyIndices, wealth.index = T, geometric = F, plot.engine = "ggplot2")
# Create two weekly weighted portfolios of stocks having positive or negative sentiment on average.
weekly <- apply.weekly(daily_sent, mean)
weekly_ <- matrix(NA, nrow = length(weekly[,1]), ncol = length(weekly[1,]))
for(n in 1:length(weekly[1,])) {
for(q in 1:length(weekly[,1])) {
pos_sent <- weekly[q,n] > 0
if(pos_sent == TRUE) {
weekly_[q,n] <- "pos"
} else {
weekly_[q,n] <- "neg"
}
}
}
colnames(weekly_) <- colnames(weekly)
negative <- matrix(NA, nrow = length(weekly[,1]), ncol = length(weekly[1,]))
positive <- matrix(NA, nrow = length(weekly[,1]), ncol = length(weekly[1,]))
for(g in 1:length(weekly[1,])) {
for(h in 1:length(weekly[,1])) {
TotalPositive <- sum(weekly_[h,] == "pos")
TotalNegative<- sum(weekly_[h,] == "neg")
isNegative <- weekly_[h,g] == "neg"
if(isNegative == TRUE) {
negative[h,g] <- (1/TotalNegative)
positive[h,g] <- 0
} else {
positive[h,g] <- (1/TotalPositive)
negative[h,g] <- 0
}
}
}
colnames(negative) <- colnames(weekly)
colnames(positive) <- colnames(weekly)
row.names(negative) <- row.names(weekly)
row.names(positive) <- row.names(weekly)
WeeklyIndex <- function(w) {
# Function to create a xts frame containing the time-series of a weighted
#
# :input w: weekly weights
# :output: xts
index <- xts(pct_returns["2020/2020-01-06"] %*% t(w[1,]), order.by = as.Date(index(pct_returns["2020/2020-01-06"])))
for (n in 2:length(index(w))){
date_range <- paste(index(weekly)[n-1], index(weekly)[n], sep = '/')
temp_index <- xts(pct_returns[date_range] %*% t(w[n,]), order.by = as.Date(index(pct_returns[date_range])))
index <- rbind.xts(index, temp_index)
}
return(index)
}
positive <- xts(positive, order.by = as.Date(index(weekly)))
negative <- xts(negative, order.by = as.Date(index(weekly)))
posIndex <- WeeklyIndex(positive)
negIndex <- WeeklyIndex(negative)
table.AnnualizedReturns(posIndex, Rf =rf/length(pct_returns$AMZN["2020"]), geometric = F)
table.AnnualizedReturns(negIndex, Rf =rf/length(pct_returns$AMZN["2020"]), geometric = F)
EqualIndexNormReturn <- merge(100*(1+cumsum(posIndex)), 100*(1+cumsum(negIndex)))
colnames(EqualIndexNormReturn) <- c("Positive Index", "Negative Index")
dygraph(EqualIndexNormReturn) %>%
dyLegend(width = 600) %>%
dyShading(from = "2020-02-19", to = "2020-04-01", col = "#FFE6E6" ) %>%
dyOptions(fillGraph = TRUE) %>%
dyRangeSelector(height = 40)