Upload
liang-cheng-zhang
View
12.136
Download
6
Embed Size (px)
Citation preview
2016/5/13
1
1
i n F i n a n c eIntroduction to R and Its Applications in Finance
Slides of this presentation: https://goo.gl/4oPIja
R script for this presentation: https://goo.gl/2YKQpq
The Finance and Financial Planning HDR Research Methodology Workshops
LiangC.Zhang
Tim
e:
10:0
0-1
1:0
0am
;1
3th
May
20
16
Pla
ce:
N5
00
.32
Griffith
Un
iversity
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
-0.6
-0.4
-0.2
0.0
CBA.AX.AdjustedANZ.AX.Adjusted
Dra
wd
ow
ns
2016/5/13
2
2
Ro
ad
Ma
p o
f R
in
Fin
an
ce
2016/5/13
3
@LiangCZhang i n F i n a n c e
Disclaimer
3
� 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.
2016/5/13
4
@LiangCZhang i n F i n a n c e
Welcome to the Era of Open-source language/software 2015 Top 10 Popular Programming
Languages What is open-source
4
� Its source code is available for modification or enhancement by anyone
� Access to examining the code
� Developed in a collaborative public manner
� Free of charge
http
://spectru
m.ieee.o
rg/com
putin
g/softw
are/the-2
015-to
p-ten
-pro
gramm
ing-lan
guages
Source: IE
EE (th
e world
's largest technical p
rofessio
nal o
rganizatio
n)
Top n
ine lan
guages are o
pen
-source
2016/5/13
5
@LiangCZhang i n F i n a n c e
What is R
5
� 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
2016/5/13
6
@LiangCZhang i n F i n a n c e
Why R in Finance?
Trend over the last decade.
6
� 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
2016/5/13
7
@LiangCZhang i n F i n a n c e
Why R in Finance?
7
� 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.
Credit risk analysis Reporting
2016/5/13
8
@LiangCZhang i n F i n a n c e
Use R!
Setting up R working environmentInstall R – Source code Install RStudio – Interface
Click and download!
https://www.r-project.org/ https://www.rstudio.com/products/RStudio/
Other alternative interfaces, see http://goo.gl/yh3Z7G
2016/5/13
9
@LiangCZhang i n F i n a n c e
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
2016/5/13
10
@LiangCZhang i n F i n a n c e
Use R!
What is an R function?
10
� Recall � � ��
� You plug any value in x and you get the results y
� An R function follows exactly the same mathematical structure. But
� Results could be statistics, data sets, plots, table…
� x is called arguments in R
S���������� �
1�∑ ��� � ������
!"
2016/5/13
11
@LiangCZhang i n F i n a n c e
Use R!
Functions & R Structure
Build-in Functions Functions from packages
11
� These functions
are ready to use
whenever you
open R
� Know how to use
a function� ?functionName, EX
� ?install.packages
� These functions have to be installed and loaded first � install.packages("quantmod")
� library(quantmod)
� Know how to use these functions
� Download manual of the package
� EX, quantmod
� https://cran.r-project.org/web/packages/quantmod/index.html
R Structure
�
�
��
2016/5/13
12
@LiangCZhang i n F i n a n c e
Use R!
R in Finance at a Glance
12Full R Finance package list https://cran.r-project.org/web/views/Finance.html
Beginner Expert
2016/5/13
13
@LiangCZhang i n F i n a n c e
Examples of using R in Finance
13
� Use your finance knowledge to help youselflearn 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
2016/5/13
14
@LiangCZhang i n F i n a n c e
Financial Data Mining
14
� Data mining: A fancy word for data downloading but automate the process
� Using R to connect financial data serversData Servers R Packages Free Access Available on CRAN Package/Data URL
Yahoo, FRED, Oanda, Google quantmod Yes Yes http://www.quantmod.com/
ECB, EIA, Eurostat … pdfetch Yes Yeshttps://cran.r-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)
2016/5/13
15
@LiangCZhang i n F i n a n c e
Data for today’s demonstration
15
� 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
2016/5/13
16
@LiangCZhang i n F i n a n c e
Loading data from Yahoo FinanceNow, consider you need to use these two assets for your studies
Commonwealth Bank of Australia ANZ
16
Company name (ticker/stock symbol)
2016/5/13
17
@LiangCZhang i n F i n a n c e
Data Subsetting for xts object
Code Results
17
Fin
d o
ut th
e d
iffere
nce b
etw
een
them
2016/5/13
18
@LiangCZhang i n F i n a n c e
Loading data from Yahoo FinanceTake a look at what you have downloaded with R
Commonwealth Bank of Australia ANZ
18
2016/5/13
19
@LiangCZhang i n F i n a n c e
Data cleansing
19
� Missing values
� Plotting
� dimensions
� Weird statistics
� No zero prices: no zero for the minimum
2016/5/13
20
@LiangCZhang i n F i n a n c e
Data cleansing
Look for missing values by plotting
A plot without missing values Man-made missing values
20
Jan 01 2016 Jan 25 2016 Feb 15 2016 Mar 07 2016 Mar 28 2016
70
72
74
76
78
80
82
CBA.AX$CBA.AX.Adjusted
Jan 01 2016 Jan 25 2016 Feb 15 2016 Mar 07 2016 Mar 28 2016
70
72
74
76
78
80
82
CBA.AX$CBA.AX.Adjusted[-20:-30]
Unequal space between the dash lines
R code for this figure
> plot(S.CBA.AX$CBA.AX.Adjusted)
2016/5/13
21
@LiangCZhang i n F i n a n c e
Technical trading
Candelstick chart
21
� Recall
� R code� chartSeries(S.CBA.AX, theme =
chartTheme("white",up.col = "green",dn.col = "red"))
� Now, change the value for the arguments:
70
75
80
85
S.CBA.AX [2016-01-01/2016-03-31]
Last 74.92
Volume (100,000s):
3,039,100
0
20
40
60
80
Jan 01 2016 Jan 25 2016 Feb 15 2016 Mar 07 2016 Mar 28 2016
Sourc
e: P
robe-
met
eo.c
om
2016/5/13
22
@LiangCZhang i n F i n a n c e
Now, it is your turn
Changing the values for the arguments
� A quick way to do it is to
copy the line of code and
paste it in the script pane
� Create a new scrip for the
following practice
� Change the value for the
argument
� EX
� Change the data set
� Replace S.CBA.AX with S.ANZ.AX
� Change the theme background
� Replace “white” with “black”
� Change the dn.col
� Replace “red” with “pink”
22
2016/5/13
23
@LiangCZhang i n F i n a n c e
Technical trading
Candelstick chart
23
� Add Bollinger bands to the chart
� Arguments� n = number of moving average
periods
� sd = number of standard deviations
� maType = type of moving average to be used
� R code� addBBands(n = 20, sd = 2, maType = "SMA")
� 20-day moving average with 2 sd error bands
70
75
80
85
S.CBA.AX [2016-01-01/2016-03-31]
Last 74.92
Bollinger Bands (20,2) [Upper/Lower]: 78.302/73.511
Volume (100,000s):
3,039,100
0
20
40
60
80
Jan 01 2016 Jan 25 2016 Feb 15 2016 Mar 07 2016 Mar 28 2016
2016/5/13
24
@LiangCZhang i n F i n a n c e
Technical trading
Candelstick chart
24
� Add simple moving average to the chart
� Arguments
� n = periods to average over
� col = colour of moving average line
� R code� addSMA(n=10,col = "blue")
70
75
80
85
S.CBA.AX [2016-01-01/2016-03-31]
Last 74.92
Bollinger Bands (20,2) [Upper/Lower]: 78.302/73.511
Volume (100,000s):
3,039,100
0
20
40
60
80
Jan 01 2016 Jan 25 2016 Feb 15 2016 Mar 07 2016 Mar 28 2016
2016/5/13
25
@LiangCZhang i n F i n a n c e
Technical trading
Candelstick chart
25
� Add Moving Average Convergence Divergence line to the chart
� Arguments
� fast=fast period
� slow=slow period
� signal=signal period
� type =type of MA to use.
� R code� addMACD(fast = 12, slow = 26, signal = 9,
type = "EMA")
70
75
80
85
S.CBA.AX [2016-01-01/2016-03-31]
Last 74.92
Bollinger Bands (20,2) [Upper/Low er]: 78.302/73.511
Volume (100,000s):
3,039,100
0
20
40
60
80
Moving Average Convergence Divergence (12,26,9):
MACD: -0.315
Signal: 0.037
-3
-2
-1
0
1
2
3
Jan 01 2016 Jan 18 2016 Feb 01 2016 Feb 15 2016 Feb 29 2016 Mar 14 2016 Mar 28 2016
MACD Line: 12-day EMA - 26-day EMA Signal Line: 9-day EMA of MACD Line MACD Histogram: MACD Line - Signal Line
2016/5/13
26
@LiangCZhang i n F i n a n c e
Technical trading
Candelstick chart
26
� Still want to add more
lines to the chart?
� Look for any function
starting with add in the
quantmod manual
2016/5/13
27
@LiangCZhang i n F i n a n c e
Data Transformation
Change frequency R code
27
� Daily to monthly
� From now on, we use full
data set
� M.CBA.AX <- to.period(CBA.AX,period = "months")
� M.ANZ.AX <- to.period(ANZ.AX,period = "months")
Fin
d o
ut th
e
diffe
ren
ce b
etw
een
th
em
2016/5/13
28
@LiangCZhang i n F i n a n c e
Data Transformation
Convert prices to returns R code
28
� Adjusted closing price
� incorporates the effects of
dividends
� Log returns (Yt)
� price.CBA.AX <- M.CBA.AX[,6]
� Return.CBA.AX <-
diff(log(price.CBA.AX))[-1]
� price.ANZ.AX <- M.ANZ.AX[,6]
� Return.ANZ.AX <-
diff(log(price.ANZ.AX))[-1]
2016/5/13
29
@LiangCZhang i n F i n a n c e
Performance Analysis
Downside risk measures
29
� 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
Manual
2016/5/13
30
@LiangCZhang i n F i n a n c e
Performance Analysis
Density plot
30
� Arguments� method = add what line to
the plot
� break = a single number giving the number of cells for the histogram
� R code� chart.Histogram(Return.CBA.AX, breaks =
50,method=(c("add.rug","add.normal","add.risk","add.density")))
� rug(Return.CBA.AX,col = "red") #change rugs' color
CBA.AX.Adjusted
ReturnsD
en
sity
-0.15 -0.10 -0.05 0.00 0.05 0.10 0.15
05
10
15
95 %
ModV
aR
95%
VaR
2016/5/13
31
@LiangCZhang i n F i n a n c e
Performance Analysis
Time Series Plot
31
Feb-2
000
Jan-2
001
Jan-2
002
Jan-2
003
Jan-2
004
Jan-2
005
Jan-2
006
Jan-2
007
Jan-2
008
Jan-2
009
Jan-2
010
Jan-2
011
Jan-2
012
Jan-2
013
Jan-2
014
Jan-2
015
Jan-2
016
Mar-
2016
-0.15
-0.10
-0.05
0.00
0.05
0.10
0.15CBA.AX.AdjustedANZ.AX.Adjusted
Re
turn
s
Time Series Plot
� R code
� chart.TimeSeries(
� 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"),
� period.color = c("gray"))
Global financial crisis
2016/5/13
32
@LiangCZhang i n F i n a n c e
Performance Analysis
Drawdown Plot
32
Feb/2
000
Jan/2
001
Jan/2
002
Jan/2
003
Jan/2
004
Jan/2
005
Jan/2
006
Jan/2
007
Jan/2
008
Jan/2
009
Jan/2
010
Jan/2
011
Jan/2
012
Jan/2
013
Jan/2
014
Jan/2
015
Jan/2
016
Mar/
2016
-0.5
-0.4
-0.3
-0.2
-0.1
0.0
CBA.AX.AdjustedANZ.AX.Adjusted
Dra
wd
ow
ns
Drawdown Plot
� chart.Drawdown(
� cbind(Return.CBA.AX,Return.ANZ.AX),
� legend.loc="bottomleft",
� ylab="Drawdowns",
� date.format= "%b/%Y",
� main ="Drawdown Plot",
� las = 2,
� period.areas = c("2007-01-31::2008-12-31","2015-01-31::2016-03-31"),
� period.color = c("gray"))
� Drawdown
summary Measuring loss in percentage between the peak and the trough
2016/5/13
33
@LiangCZhang i n F i n a n c e
Extensions of using R in Finance
33
� 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)
2016/5/13
34
@LiangCZhang i n F i n a n c e
Extensions of using R in Finance
34
� 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:h
ttp://5
2.2
.13.9
7:3
838/fam
a_fren
ch/
2016/5/13
35
@LiangCZhang i n F i n a n c e
Conclusion:
Where to find the future of finance: Data
35
2016/5/13
36
@LiangCZhang i n F i n a n c e
Conclusion: Embrace innovation, embrace challenge, and embrace R
Software Your field of knowledge
36
� Excel:
� R Through Excel (Heiberger & Neuwirth, 2009)
� SAS and SPSS: � R for SAS and SPSS Users
(Muenchen, 2011)
� STATA:
� R for Stata Users (Muenchen & Hilbe, 2010)
� MATLAB:
� R and MATLAB (Hiebeler, 2015)
� Finance� Analyzing financial data and
implementing financial models using R (Ang, 2015)
� An introduction to analysis of financial data with R (Tsay, 2014)
� Financial risk forecasting (Daníelsson, 2011)
� Computational finance (Arratia, 2014)
How to learn R by yourself: Always start with something your are familiar with
2016/5/13
37
@LiangCZhang i n F i n a n c e
References
37
� 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.
2016/5/13
38
@LiangCZhang i n F i n a n c e
Thanks for your attention!
Liang C. Zhang ((((良丞良丞良丞良丞 張張張張))))W: liangchengzhang.weebly.com
@LiangCZhang