You are on page 1of 38

2016/5/13

The Finance and Financial Planning HDR Research Methodology Workshops


Place: N50 0.32 Griffith University
Time: 10:00-11:00am; 13th May 2016

Liang C. Zhang

in Finance
Introduction to R and Its Applications in Finance
Slides of this presentation: https://goo.gl/4oPIja
R script for this presentation: https://goo.gl/2YKQpq
0.0
-0.2
Drawdowns

-0.4

CBA.AX.Adjusted
-0.6

ANZ.AX.Adjusted

1 Jan/2000 Jan/2001 Jan/2002 Jan/2003 Jan/2004 Jan/2005 Jan/2006 Jan/2007 Jan/2008 Jan/2009 Jan/2010 Jan/2011 Jan/2012 Jan/2013 Jan/2014 Jan/2015 Jan/2016

1
2
Road Map of R in Finance

2
2016/5/13
2016/5/13

Disclaimer
This workshop contains R tools for Technical trading &
Performance analysis that might assist investment decisions.
All analysis are used for demonstrating R only.
In other words,
You are responsible for your own investment decisions if you
use these tools to manage your assets.

3 in Finance
@LiangCZhang

3
2016/5/13

Welcome to the Era of Open-source language/software


2015 Top 10 Popular Programming
Languages What is open-source
Its source code is available
Source: IEEE (the world's largest technical professional organization)
http://spectrum.ieee.org/computing/software/the-2015-top-ten-programming-languages

Top nine languages are open-source


for modification or
enhancement by anyone
Access to examining the
code
Developed in a collaborative
public manner
Free of charge

4 in Finance
@LiangCZhang

4
2016/5/13

What is R
Open-source programming language and software
A platform to build their own functions/packages/products
The source code is open for inspection
Free of charge
History
1993: A research project initiated by
Prof. Ross Ihaka and Robert Gentleman
2000: After the hard work of computer
scientists and statisticians R version
1.0.0
Number of packages (Add-ins) grows
exponentially
Source: https://gist.github.com/daroczig/3cf06d6db4be2bbe3368

5 in Finance
@LiangCZhang

5
2016/5/13

Why R in Finance?
Trend over the last decade.
Are you
following or
falling behind
the trend?
Data: Google
trends over the
past 10 years
It measures how
often people
search for the
given term.
Source: Google Trend, http://goo.gl/vO6LhA
6 in Finance
@LiangCZhang

6
2016/5/13

Why R in Finance?
Credit risk analysis Reporting
Popular in industry

….more could be found here http://www.revolutionanalytics.com/companies-using-r


Popular in Ivy league universities: Stanford, UCLA, Princeton…
Princeton even provides docs for helping students and staff switch to R
Directly load financial data into R from the web: Data mining/big data
Producing beautiful plots: Today’s FOCUS!
A all-in-one statistical software and programming language
You don’t have to switch to other software. R can satisfy most your needs if you
know how to search for the packages and have basic programming skills.

7 in Finance
@LiangCZhang

7
2016/5/13

Use R!
Setting up R working environment
Install R – Source code Install RStudio – Interface
https://www.r-project.org/ https://www.rstudio.com/products/RStudio/

Other alternative interfaces, see http://goo.gl/yh3Z7G

Click and download!

in Finance
@LiangCZhang

8
2016/5/13

Use R!
Setting up R working environment (cont.)
Put all files (data, script…)
in the same folder
Always start with opening
the script: EX: Open R in
Finance.R
For setting up working
directory
See whether all files in the
tab of the bottom right pane
Install packages for this
event
Need internet connection
Select the lines of code and
press Ctrl+Enter

in Finance
@LiangCZhang

9
2016/5/13

Use R!
What is an R function?
Recall
You plug any value in x
and you get the results y
An R function follows
exactly the same
mathematical structure.
But 1

Results could be statistics, S
!"
data sets, plots, table…
x is called arguments in R

10 in Finance
@LiangCZhang

10
2016/5/13

Use R!
Functions & R Structure
Build-in Functions Functions from packages R Structure

These functions These functions


have to be installed
are ready to use


and loaded first
whenever you install.packages("quantmod")
library(quantmod)
open R


Know how to use these
functions
Know how to use Download manual of the
package
a function EX, quantmod
?functionName, EX https://cran.r-
project.org/web/packages/quantmod/index.
html

?install.packages

11 in Finance
@LiangCZhang

11
2016/5/13

Use R!
R in Finance at a Glance

Beginner Expert

12Full R Finance package list https://cran.r-project.org/web/views/Finance.html in Finance


@LiangCZhang

12
2016/5/13

Examples of using R in Finance


Use your finance
knowledge to help youself
learn R
What you will learn
Techniques that let you
use R and its packages
Using three packages to
deal with different tasks
Manipulating data using R
build-in functions
What you will not learn
The interpretation of the
results
You should be familiar
with these materials

13 in Finance
@LiangCZhang

13
2016/5/13

Financial Data Mining


Data mining: A fancy word for data downloading but automate the process
Using R to connect financial data servers
Data Servers R Packages Free Access Available on CRAN Package/Data URL
Yahoo, FRED, Oanda, Google quantmod Yes Yes http://www.quantmod.com/
https://cran.r-
ECB, EIA, Eurostat … pdfetch Yes Yes
project.org/web/packages/pdfetch/index.html
Quandl Quandl Yes Yes http://www.quandl.com/help/packages/r

TrueFX TFX Yes Yes http://rpubs.com/gsee/TFX


Bloomberg Rbbg No No http://findata.org/rbloomberg/
Interactive Broker IBrokers No Yes https://www.interactivebrokers.com/en/main.php
Datastream rdatastream No No https://github.com/fcocquemas/rdatastream
Penn World Table pwt Yes Yes https://pwt.sas.upenn.edu/
Yahoo, FRED, Oanda fImport Yes Yes http://www.rmetrics.org/
ThinkNum Thinknum Yes Yes http://thinknum.com/

Source: Adapted from (The R Trader, 2013)

14 in Finance
@LiangCZhang

14
2016/5/13

Data for today’s demonstration


Stock prices of two banks, Commonwealth and ANZ
Stock prices are most assessable and varied data (more variance)
Most of you might use bank data
Period: 1 Jan 2000 to 31 Mar 2016
Short term data used in technical trading
Last recent quarter (subsetting)
1 Jan 2016 to 31 Mar 2016
Long term data used in performance analysis
Whole data set but convert it to monthly returns (data transformation)
1 Jan 2000 to 31 Mar 2016

15 in Finance
@LiangCZhang

15
2016/5/13

Loading data from Yahoo Finance


Now, consider you need to use these two assets for your studies
Commonwealth Bank of Australia ANZ
Company name (ticker/stock symbol)

16 in Finance
@LiangCZhang

16
2016/5/13

Data Subsetting for xts object


Code Results

Find out the difference between them


17 in Finance
@LiangCZhang

17
2016/5/13

Loading data from Yahoo Finance


Take a look at what you have downloaded with R
Commonwealth Bank of Australia ANZ

18 in Finance
@LiangCZhang

18
2016/5/13

Data cleansing
Missing values
Plotting
dimensions
Weird statistics
No zero prices: no zero for the minimum

19 in Finance
@LiangCZhang

19
2016/5/13

Data cleansing
Look for missing values by plotting
A plot without missing values Man-made missing values
CBA.AX$CBA.AX.Adjusted CBA.AX$CBA.AX.Adjusted[-20:-30]
82

82
R code for this figure
> plot(S.CBA.AX$CBA.AX.Adjusted)
80

80
78

78
76

76
74

72 74
72
70

70
Jan 01 2016 Jan 25 2016 Feb 15 2016 Mar 07 2016 Mar 28 2016 Jan 01 2016 Jan 25 2016 Feb 15 2016 Mar 07 2016 Mar 28 2016

Unequal space between


the dash lines

20 in Finance
@LiangCZhang

20
2016/5/13

S.CBA.AX [2016-01-01/2016-03-31]

Last 74.92

Technical trading
85

Candelstick chart 80

Recall

Source: Probe-meteo.com
75

70

R code 80 Volume (100,000s):


3,039,100

chartSeries(S.CBA.AX, theme = 60

chartTheme("white",up.col = 40

"green",dn.col = "red")) 20

Now, change the value for the 0

arguments: Jan 01 2016 Jan 25 2016 Feb 15 2016 Mar 07 2016 Mar 28 2016

21 in Finance
@LiangCZhang

21
2016/5/13

Now, it is your turn


Changing the values for the arguments
A quick way to do it is to EX
copy the line of code and Change the data set
Replace S.CBA.AX with
paste it in the script pane S.ANZ.AX
Create a new scrip for the Change the theme
following practice background
Change the value for the Replace “white” with “black”
argument Change the dn.col
Replace “red” with “pink”

22 in Finance
@LiangCZhang

22
2016/5/13

S.CBA.AX [2016-01-01/2016-03-31]

Last 74.92

Technical trading Bollinger Bands (20,2) [Upper/Lower]: 78.302/73.511


85

Candelstick chart 80

Add Bollinger bands to the chart


Arguments 75

n = number of moving average


periods
sd = number of standard 70

deviations 80 Volume (100,000s):


3,039,100
maType = type of moving 60

average to be used 40

R code 20

addBBands(n = 20, sd = 2, maType = "SMA") 0

20-day moving average with 2 sd error bands


Jan 01 2016 Jan 25 2016 Feb 15 2016 Mar 07 2016 Mar 28 2016

23 in Finance
@LiangCZhang

23
2016/5/13

S.CBA.AX [2016-01-01/2016-03-31]

Last 74.92

Technical trading
85
Bollinger Bands (20,2) [Upper/Lower]: 78.302/73.511

Candelstick chart 80

Add simple moving


average to the chart 75

Arguments
n = periods to average 70

over 80 Volume (100,000s):


3,039,100

col = colour of moving 60

average line 40

20

R code 0

addSMA(n=10,col = "blue") Jan 01 2016 Jan 25 2016 Feb 15 2016 Mar 07 2016 Mar 28 2016

24 in Finance
@LiangCZhang

24
2016/5/13

S.CBA.AX [2016-01-01/2016-03-31]

Last 74.92
Bollinger Bands (20,2) [Upper/Low er]: 78.302/73.511 85

Technical trading
80

Candelstick chart
Add Moving Average
Convergence Divergence line 75

to the chart
Arguments 70

fast=fast period 80
Volume (100,000s):
3,039,100

slow=slow period 60

40

signal=signal period 20

type =type of MA to use. 0


3
Moving Average Convergence Divergence (12,26,9):
2 MACD: -0.315

R code 1
Signal: 0.037

addMACD(fast = 12, slow = 26, signal = 9, 0

type = "EMA") MACD Line: 12-day EMA - 26-day EMA -1

Signal Line: 9-day EMA of MACD Line -2


MACD Histogram: MACD Line - Signal Line
-3

25 in Finance
Jan 01 2016 Jan 18 2016 Feb 01 2016 Feb 15 2016 Feb 29 2016 @LiangCZhang
Mar 14 2016 Mar 28 2016

25
2016/5/13

Technical trading
Candelstick chart
Still want to add more
lines to the chart?
Look for any function
starting with add in the
quantmod manual

26 in Finance
@LiangCZhang

26
2016/5/13

Data Transformation
Change frequency R code
M.CBA.AX <- to.period(CBA.AX,period = "months")
Daily to monthly M.ANZ.AX <- to.period(ANZ.AX,period = "months")

From now on, we use full


data set

them
difference between
Find out the
27 in Finance
@LiangCZhang

27
2016/5/13

Data Transformation
Convert prices to returns R code
price.CBA.AX <- M.CBA.AX[,6]
Adjusted closing price
Return.CBA.AX <-
incorporates the effects of diff(log(price.CBA.AX))[-1]
dividends price.ANZ.AX <- M.ANZ.AX[,6]
Log returns (Yt) Return.ANZ.AX <-
diff(log(price.ANZ.AX))[-1]

28 in Finance
@LiangCZhang

28
2016/5/13

Performance Analysis
Downside risk measures Manual
Be care of the default values
EX: Value at Risk (VaR)
This could be easily got by running
this
VaR(Return.CBA.AX)
But
Significance level or confidence level?
Which method to calculate this
measure?
It turns out that you are using modified
method which might not be what you
want

29 in Finance
@LiangCZhang

29
2016/5/13

Performance Analysis
Density plot CBA.AX.Adjusted

95% VaR
95 % ModVaR
15
Arguments
method = add what line to
the plot

10
break = a single number

Density
giving the number of cells
for the histogram

5
R code
chart.Histogram(Return.CBA.AX, breaks =
50,method=(c("add.rug","add.normal","ad
d.risk","add.density")))
rug(Return.CBA.AX,col = "red")
0
#change rugs' color -0.15 -0.10 -0.05 0.00 0.05 0.10 0.15

Returns

30 in Finance
@LiangCZhang

30
2016/5/13

Performance Analysis R code


chart.TimeSeries(
Time Series Plot cbind(Return.CBA.AX,Return.ANZ.AX),
legend.loc="topleft",
date.format ="%b-%Y",
las = 2,
ylab = "Returns",
main = "Time Series Plot",
period.areas = c("2007-01-31::2008-12-31"),
Time Series Plot period.color = c("gray"))

CBA.AX.Adjusted
0.15 ANZ.AX.Adjusted

0.10

0.05
Returns

0.00

-0.05

-0.10

-0.15

Global financial crisis


Feb-2000

Jan-2001

Jan-2002

Jan-2003

Jan-2004

Jan-2005

Jan-2006

Jan-2007

Jan-2008

Jan-2009

Jan-2010

Jan-2011

Jan-2012

Jan-2013

Jan-2014

Jan-2015

Jan-2016
Mar-2016
31 in Finance
@LiangCZhang

31
2016/5/13

Performance Analysis
Drawdown Plot
Drawdown
summary Drawdown Plot

0.0
Measuring loss in percentage between the peak and the trough

-0.1

-0.2
Drawdowns

chart.Drawdown(
cbind(Return.CBA.AX,Return.ANZ.AX),
-0.3 legend.loc="bottomleft",
ylab="Drawdowns",
date.format= "%b/%Y",
-0.4
main ="Drawdown Plot",
las = 2,
period.areas = c("2007-01-31::2008-12-
-0.5 31","2015-01-31::2016-03-31"),
CBA.AX.Adjusted
ANZ.AX.Adjusted period.color = c("gray"))
Feb/2000

Jan/2001

Jan/2002

Jan/2003

Jan/2004

Jan/2005

Jan/2006

Jan/2007

Jan/2008

Jan/2009

Jan/2010

Jan/2011

Jan/2012

Jan/2013

Jan/2014

Jan/2015

Jan/2016
Mar/2016
32 in Finance
@LiangCZhang

32
2016/5/13

Extensions of using R in Finance


Big Data
Suppose we have
the assess to the
intra-day stock
prices
The size of whole
data set becomes
bigger and bigger
as D and I increases
Speed up the data
process
See Zou & Zhang
(2014)

33 in Finance
@LiangCZhang

33
2016/5/13

Extensions of using R in Finance


Demonstrate your financial models/products on the web using
R Shiny
EX: Invent a algorithm to predict when to sell or buy the stocks
http://www.showmeshiny.com

Source:http://52.2.13.97:3838/fama_french/
34 in Finance
@LiangCZhang

34
2016/5/13

Conclusion:
Where to find the future of finance: Data

35 in Finance
@LiangCZhang

35
2016/5/13

Conclusion:
Embrace innovation, embrace challenge, and embrace R
Software Your field of knowledge
How to learn R by yourself: Always start with something your are familiar with
Excel: Finance
R Through Excel (Heiberger & Analyzing financial data and
Neuwirth, 2009) implementing financial
SAS and SPSS: models using R (Ang, 2015)
R for SAS and SPSS Users An introduction to analysis of
(Muenchen, 2011)
financial data with R (Tsay,
STATA: 2014)
R for Stata Users (Muenchen & Financial risk forecasting
Hilbe, 2010)
(Daníelsson, 2011)
MATLAB:
Computational finance
R and MATLAB (Hiebeler, 2015) (Arratia, 2014)
36 in Finance
@LiangCZhang

36
2016/5/13

References
Ang, C. S. (2015). Analyzing financial data and implementing financial models using R. New York, NY: Springer.
Arratia, A. (2014). Computational finance: An introductory course with R. New York, NY: Springer
Daníelsson, J. (2011). Financial risk forecasting: The theory and practice of forecasting market risk with implementation in R and Matlab. Hoboken, NJ:
John Wiley & Sons.
Muenchen, R. A., & Hilbe, J. (2010). R for Stata users. New York, NY: Springer.
Muenchen, R. A. (2011). R for SAS and SPSS users. New York, NY: Springer.
Hiebeler, D. E. (2015). R and MATLAB: CRC Press.
Heiberger, R. M., & Neuwirth, E. (2009). R through Excel: A spreadsheet interface for statistics, data analysis, and graphics. New York, NY: Springer.
Ryan, J. A., & Ulrich, J. M. (2014). xts: eXtensible Time Series. Retrieved from https://cran.r-project.org/web/packages/xts/index.html
Peterson, B. G., & Carl, P. (2014). PerformanceAnalytics: Econometric tools for performance and risk analysis. Retrieved from http://CRAN.R-
project.org/package=PerformanceAnalytics
The R Trader. (2013). Financial data accessible from R –Part III. Retrieved from http://www.thertrader.com/2013/11/08/financial-data-accessible-
from-r-part-iii/
Tsay, R. S. (2014). An introduction to analysis of financial data with R. New York, NY: John Wiley & Sons.
Ryan, J. A., Ulrich, J. M., & Thielen, W. (2015). quantmod: Quantitative financial modelling framework. R package version 0.3-5. URL http://www.
quantmod. com URL http://r-forge. r-project. org/projects/quantmod. Retrieved from https://cran.r-project.org/web/packages/quantmod/index.html
Zou, J., & Zhang, H. (2014, 27-30 Oct. 2014). High-frequency financial statistics with parallel R and Intel Xeon Phi coprocessor. Paper presented at the
Big Data (Big Data), 2014 IEEE International Conference.
Note: Some references are not here since they are shown with the web links.

37 in Finance
@LiangCZhang

37
2016/5/13

Thanks for your attention!


Liang C. Zhang (良丞 張)
W: liangchengzhang.weebly.com
E: scure1026@gmail.com
@LiangCZhang

in Finance
@LiangCZhang

38

You might also like