some statistical applications with R

I haven’t written a blog post in ages but I am finished my exams now and have more time to put my studies to work. I wanted to share how easy it is to get started with R and to produce some simple charts.

To do a simple regression and a chart with bollinger bands, install R and R studio. Paste the code into an R studio window and run.

This piece needs to be run once only:

install.packages(“Quandl”)
install.packages(“ggplot2”)
install.packages(“quantmod”)

then

require(Quandl)
mydata = Quandl(c(“CME/ESU2016”), start_date = “2016-01-01”);
attach(mydata)

require(ggplot2)
ggplot(mydata, aes(x=Date, y=Settle)) +
geom_point(shape=1) + # Use hollow circles
geom_smooth(method=lm) # Add linear regression line
# (by default includes 95% confidence region)

This produces a simple linear regression with confidence interval:

ES linear regression

The quantmod package is nice and it works simply:

require(quantmod)
getSymbols(c(“^GSPC”))
chartSeries(GSPC, subset=’last 3 months’)
addBBands(n = 20, sd = 2, ma = “SMA”, draw = ‘bands’, on = -1)

This should produce:

ES_BB

To make the regression focus period shorter you need to run the first 3 lines of the load data block to import the data before running the rest to draw the regression chart.

Here are some sources of info:
http://www.r-chart.com/2010/06/stock-analysis-using-r.html
http://www.cookbook-r.com/Graphs/Scatterplots_(ggplot2)/
http://www.quantmod.com/examples/charting/#chartseries

This book is great:

41bYuJNpEzL._SX330_BO1,204,203,200_

as is this resource on forecasting https://www.otexts.org/book/fpp

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s