Tuesday, July 22, 2014

Return and volatility distribution, FTSE 100

This is what the daily logistic returns on the index FTSE 100 has looked like since 2004.

 
 
And here is the volatility.
 
 

Friday, July 18, 2014

Google Trends and stock indexes


In order to use Google Trends data in financial analysis and forecasting, it is necessary to understand how to manipulate the data in the right way. Here, I demonstrate that there is a big difference between the average search pattern of index constituents and for the index itself. I.e. averageing search data for companies in FTSE 100 index gives a very different pattern than the querry for "FTSE 100".
Individual companies can have a high degree of correlation with the search data for the index, as is shown in the table at the bottom. On the whole there does not seem to be a direct relationship between the two.

I have collected a data set consisting of the daily searches for stocks on FTSE 100 since 2004.This is what daily search activity for the querry "FTSE 100" looks like:

Out of the 100 companies on FTSE 100, there is Google Trends data for 36 of them with somewhat complete data for the entire time period. First, lets take a look at what the average search activity has looked like:


From the graph it is clear that the simple average SVI for the index constituents is quite different from querries for the index itself. An OLS regression between the two confirms the point:
But how much of the variance in the index search querry can be explained with the searches for the constituents? Using a multiple regression where the search querry for "FTSE 100" is the dependent variable, and the 36 companies I have data for are the independent variables, I get the following result:


The upper graph is the result when the constituent data has been weighted by their coefficient from the regression analysis. The lower graph is the normal data. The adjusted R^2 for the regression is 48.8%, which is quite low if we assume that the search querries for the index is determined by its constituents. Based on these graphs we can conclude that the combined search querries for index constituents have a very different pattern from the index itself.

In the following post I will compare how the averaged data compares to the index querry when it comes to explaining volatility and volume on an index level.



Estimate Std. Error t value Pr
(Intercept) -45.9945 10.70911 -4.295 1.84E-05 ***
antofagasta -0.08598 0.10204 -0.843 0.399576
barclays -0.79759 0.13393 -5.955 3.11E-09 ***
bg.group 0.07388 0.04555 1.622 0.104973
bhp.billiton 0.25362 0.04331 5.856 5.63E-09 ***
bp 0.27475 0.07597 3.617 0.000307 ***
british.american.tobacco -0.02044 0.06471 -0.316 0.75208
bt.group 0.07351 0.0421 1.746 0.080954 .
bunzl -0.0606 0.04473 -1.355 0.175677
capita 0.19081 0.0597 3.196 0.001418 **
carnival -0.33172 0.08659 -3.831 0.000132 ***
centrica 0.00176 0.03652 0.048 0.961554
coca.cola 0.12069 0.05971 2.021 0.043406 *
compass.group -0.05013 0.04275 -1.173 0.241132
crh -0.05094 0.02877 -1.771 0.076751 .
diageo -0.07566 0.0308 -2.456 0.014131 *
easyjet -0.35516 0.09915 -3.582 0.00035 ***
experian 0.84559 0.12022 7.034 2.85E-12 ***
fresnillo -0.09778 0.05871 -1.666 0.095972 .
g4s 0.09061 0.06033 1.502 0.133294
gkn 0.04686 0.04956 0.946 0.344499
glaxosmithkline 0.09202 0.06327 1.454 0.146051
hargreaves.lansdown 0.1098 0.02244 4.894 1.08E-06 ***
imi 0.53225 0.16463 3.233 0.001247 **
johnson.matthey 0.10219 0.03344 3.056 0.002276 **
kingfisher -0.08054 0.09647 -0.835 0.403947
mondi -0.31752 0.06463 -4.913 9.77E-07 ***
pearson -1.06295 0.14024 -7.58 5.51E-14 ***
persimmon 0.23234 0.2629 0.884 0.37694
prudential 8.29241 0.45481 18.233 <2 .00e-16="" td=""> ***
rexam -0.18421 0.06884 -2.676 0.007523 **
rio.tinto 0.05902 0.03556 1.66 0.09716 .
royal.dutch.shell -0.32336 0.06729 -4.806 1.67E-06 ***
royal.mail 0.09751 0.03783 2.578 0.010026 *
schroders 0.13236 0.08896 1.488 0.136951

Correlation between Google Trends and stock market volatility

Andersen (1996) writes that "price movements are caused primarely by the arrival of new information and the process that incoprates this information into market prices". This underlying information process affects stock market volatility and trade volumes. If Google Trends data represents the general flow of information then we should see a correlation between Google Trends data, volatility and volume.

The data set consists of daily Google Trends observations for the querry "FTSE 100" and daily returns, volatility and volume for FTSE 100. The correlation matrix shows that there is a high correlation between volatility and Google Trends data for the FTSE 100 data set.The correlation between the Google Trends data and volatility is surprisingly low, as is the correlation between volume and volatility.



Close Trends Return Volatility Volume
Close 1.00 -0.28 0.04 -0.24 -0.10
Trends 1.00 -0.06 0.48 -0.01
Return 1.00 0.03 -0.04
Volatility 1.00 0.16
Volume 1.00
Correlation matrix, FTSE 100





 A univariate OLS regression where volatility is the dependent variable and Google Trends is the independent variable gives a significant slope on a 0.1% level and an R^2 of 23,51%.
 



Estimate Std. Error  T value Pr(>|t|)
(Intercept) 0.00 0.00 -7.59 0.00 ***
Trends 0.00 0.00 27.28 2e-16***

Thursday, July 17, 2014

Indexing daily Google Trends data using R

If you want to us daily Google Trends data for statistical analysis, you will most likely want to go beyond the 90 day limitation Google has set on the data. How would you do that? You might start by simply piecing together the data Google gives you.

I've downloaded the csv file each month between 2004-2013 for the querry "FTSE 100". This is what you get:
Not very pretty is it. If you compare it to the weekly Google Trends data for the same querry, you can see that they look quite different from each other.


 Ideally, we would like to get the increased accuracy of daily data, while keeping the indexing intact. The way I've solved this problem is by reindexing the data back to the weekly index. Each weekly observation provides a reindexing point. Then you get this:

Looks a lot better, right? Here's two more examples, BP and Experian.


How much does Google Trends data change over time?


 Will Google Trends data change depending on when it is downloaded? To answer the question, I downloaded data for the UK stock index FTSE 100 with two months in between.
Since Google Trends create an index from the search querries, the result may change over time. To test how much this change might be, I've downloaded the querry for "FTSE 100" twice, once in May and once in July. As can be seen from the image, the results differ slightly
The R^2 for a linear regression with the two time series is 96,6%. On a short time horizon, there is only minor changes in the data.

Monday, May 19, 2014

Google Trends mass import using R

I was looking for a tool for mass download of daily Google Trends data for my thesis and couldn't find anything that worked for my needs. The tool was built to download Google Trends data in monthly snippets for  a given search word and given year or years.

I thought I would share my work here in case someone else has stumbled on the same issues. The file can be found here on github: https://gist.github.com/321k/823cce9769e58bc14214.

Make sure you have the quantmod library installed before you run it.

Getting the data

Since the code works by downloading the file thorugh the browser, it is not affected by changes to Google's authentication policy. Simply make sure that you are signed in to your Google account. This does however mean that the data download is slow. I recommend using Firefox with a tab manager to close the tabs after a download has been completed. Tab mix plus 0.4.1.3.1 works great for me. You will also need to check the box in the download prompt that lets Firefox download without prompting you. Finally, you need to specify the download directory as an empty folder.

There are four functions; downloadGT, importGT, formatGT, and mergeGT. downloadGT takes two imputs, the years you want to download, and the search querry you want to get. To run for multiple querries, simply add a loop:
querries=c("MSFT", "AAPL")
years=c("2012", "2013")
for(i in 1:length(querries) {downloadGT(years, querries[i])}

 Formating the data

Once we have downloaded the files, we need to import it to R and put it in a useable format. importGT gets the data, formatGT extracts the time series data, and mergeGT put the individual months into complete time series by company.
path="C:/data"
rawData=importGT(path)
formatedData=formatGT(rawData)
mergedData=mergeGT(formatedData)
And there you have it. I'm currently in the process of downloading the Google Trends data for FTSE 100 between 2004 and 2013. Google's quota limit allows me to download about ten companies per day, or 1200 files. Feel free to leave a comment or suggestion
.

Tuesday, May 06, 2014

Daily Google Trends data using R

This blog post is a work in progress and has been updated several times. Last update 11.5.2016.

For an explanation of how to combine weekly and daily Google Trends data to create long daily time series with Search Volume Data, please refer to this blog post. You can find a working example in R here.

This R script weaves daily Google Trends data together into a continuous time series. For a look at how daily Google Trends data differs from the weekly data, take a look at this blog post. The graph below illustrated the daily search  data for "FTSE 100".


Since I had a lot of problems with authentication in the available tools for downloading Google Trends data, I decided to circumvent the whole authentication issue by downloading the files through the browser. The file downloads are automated using R. To execute the example below, you will need to add these functions from my Github account to R.
Make sure that you are signed in before you run the script. Since you will download 120 individual csv files, it will take several minutes to complete the run.

The function URL_GT creates the URL for the Google Trends file export. The function readGT downloads the file through the browser and returns the time series data. When the functions are available to R, running the code below shoud return a time series that looks like the one above. Let me know in the comments if it isn't working.


library(Rmisc)
library(ggplot2)
library(dplyr)

# The Google Trends formating functions -----------------------------------

#This script automates the downloading of Google Trends.
#It works best with firefox in combination with the Tab Mix Plus add-on that is used to automate tab closing.
#Ask firefox not to prompt for new downloads and this script should run automatically.
#Google Trends restricts the number of download to roughly 400 at a time.

URL_GT=function(keyword="", country=NA, region=NA, year=NA, month=1, length=3){
  
  start="http://www.google.com/trends/trendsReport?hl=en-US&q="
  end="&cmpt=q&content=1&export=1"
  geo=""
  date=""
  
  #Geographic restrictions
  if(!is.na(country)) {
    geo="&geo="
    geo=paste(geo, country, sep="")
    if(!is.na(region)) geo=paste(geo, "-", region, sep="")
  }
  
  queries=keyword[1]
  if(length(keyword)>1) {
    for(i in 2:length(keyword)){
      queries=paste(queries, "%2C ", keyword[i], sep="")
    }
  }
  
  #Dates
  if(!is.na(year)){
    date="&date="
    date=paste(date, month, "%2F", year, "%20", length, "m", sep="")
  }
  
  URL=paste(start, queries, geo, date, end, sep="")
  URL <- gsub(" ", "%20", URL)
  return(URL)
}

downloadGT=function(URL, downloadDir){
  
  #Determine if download has been completed by comparing the number of files in the download directory to the starting number
  startingFiles=list.files(downloadDir)
  browseURL(URL)
  endingFiles=list.files(downloadDir)
  
  while(length(setdiff(endingFiles,startingFiles))==0) {
    Sys.sleep(3)
    endingFiles=list.files(downloadDir)
  }
  filePath=setdiff(endingFiles,startingFiles)
  return(filePath)
}


readGT=function(filePath){
  rawFiles=list()
  
  for(i in 1:length(filePath)){
    if(length(filePath)==1) rawFiles[[1]]=read.csv(filePath, header=F, blank.lines.skip=F)
    if(length(filePath)>1) rawFiles[[i]]=read.csv(filePath[i], header=F, blank.lines.skip=F)
  }
  
  output=data.frame()
  name=vector()
  
  for(i in 1:length(rawFiles)){
    data=rawFiles[[i]]
    name=as.character(t(data[5,-1]))
    
    #Select the time series
    start=which(data[,1]=="")[1]+3
    stop=which(data[,1]=="")[2]-2
    
    #Skip to next if file is empty
    if(ncol(data)<2) next
    if(is.na(which(data[,1]=="")[2]-2)) next
    
    data=data[start:stop,]
    data[,1]=as.character(data[,1])
    
    #Convert all columns except date column into numeric
    for(j in 2:ncol(data)) data[,j]=as.numeric(as.character(data[,j]))
    
    #FORMAT DATE
    len=nchar(data[1,1])
    
    #Monthly data
    if(len==7) {
      data[,1]=as.Date(paste(data[,1], "-1", sep=""), "%Y-%m-%d")
      data[,1]=sapply(data[,1], seq, length=2, by="1 month")[2,]-1
      data[,1]=as.Date(data[,1], "%Y-%m-%d", origin="1970-01-01")
    }
    
    #Weekly data
    if(len==23){
      data[,1]=sapply(data[,1], substr, start=14, stop=30)
      data[,1]=as.Date(data[,1], "%Y-%m-%d")
    }
    
    #Daily data
    if(len==10) data[,1]=as.Date(data[,1], "%Y-%m-%d")
    
    #Structure into panel data format
    panelData=data[1:2]
    panelData[3]=name[1]
    names(panelData)=c("Date", "SVI", "Keyword")
    if(ncol(data)>2) {
      
      for(j in 3:ncol(data)) {
        appendData=data[c(1,j)]
        appendData[3]=name[j-1]
        names(appendData)=c("Date", "SVI", "Keyword")
        panelData=rbind(panelData, appendData)
      }
    }
    
    #Add file name  
    panelData[ncol(panelData)+1]=filePath[i]
    
    #Add path to filename
    names(panelData)[4]="Path"
    
    #Merge several several files into one
    if(i==1) output=panelData
    if(i>1) output=rbind(output, panelData)
  }
  return(output)
}

readGeoGT=function(filePath){
  output=data.frame()
  rawFiles=list()
  for(i in 1:length(filePath)){
    if(length(filePath)==1) rawFiles[[1]]=read.csv(filePath, header=F, blank.lines.skip=F)
    if(length(filePath)>1) rawFiles[[i]]=read.csv(filePath[i], header=F, blank.lines.skip=F)
  }
  
  for(i in 1:length(rawFiles)){
    data=rawFiles[[i]]
    start=which(data[,1]=="")[3]+3
    stop=which(data[,1]=="")[4]-1
    names=data[start-1,]
    
    for(j in 1:ncol(names)) names(data)[j]=as.character(names[1,j])
    data=data[start:stop,]
    data[,1]=as.character(data[,1])
    data[,-1]=as.numeric(as.character(data[,-1]))
    data[ncol(data)+1]=filePath[i]
    
    output=rbind(output, data)
  }
  return(output)
}


# Downloading the data ----------------------------------------------------


search_terms = c("bull market", "bear market", "recession")

years = c(2005,2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013, 2014, 2015, 2016)
months = c(1,4,7,10)
res.daily=list()
counter=1
for(year in years){
  for(month in months){
    url=URL_GT(search_terms, year=year, month=month)
    GT_dir = downloadGT(url, downloadDir)
    GT_dir = paste(downloadDir, GT_dir, sep='/')
    res.daily[[counter]] = readGT(GT_dir)
    counter=counter+1
  }
}

df.daily <- do.call("rbind", res.daily)

url = URL_GT(search_terms)
GT_dir = downloadGT(url, downloadDir)
GT_dir = paste(downloadDir, GT_dir, sep='/')
df.weekly = readGT(GT_dir)


# Formating the data ------------------------------------------------------


df.merged = merge(df.daily, df.weekly, by=c('Date', 'Keyword'), all.x=T)
df.merged$adjustment_factor = df.merged$SVI.y /df.merged$SVI.x

for(i in search_terms){
  r=which(df.merged$Keyword==i)
  for(j in 2:length(r)){
    if(!is.finite(df.merged$adjustment_factor[r][j])){
      df.merged$adjustment_factor[r][j] = df.merged$adjustment_factor[r][j-1]
    }
  }
}
df.merged$daily = df.merged$adjustment_factor * df.merged$SVI.x
df.merged$weekly = df.merged$SVI.y
for(i in search_terms){
  r=which(df.merged$Keyword==i)
  for(j in 2:length(r)){
    if(is.na(df.merged$weekly[r][j])){
      df.merged$weekly[r][j] = df.merged$weekly[r][j-1]
    }
  }
}


# Plotting the data -------------------------------------------------------

df.merged$daily[which(is.infinite(df.merged$daily))] = NA

p1 = df.merged %>%
  ggplot(aes(Date, daily, color=Keyword))+geom_line()

p2 = df.merged %>%
  ggplot(aes(Date, weekly, color=Keyword))+geom_line()

multiplot(p1,p2)


# Saving the data ---------------------------------------------------------


write.csv(df.merged,'df.merged.csv')
Entertaining Blogs - BlogCatalog Blog Directory
Bloggtoppen.se