Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.

R in finance: Introduction to R and Its Applications in Finance

29,148 views

Published on

This presentation is designed for experts in Finance but not familiar with R. I use some Finance applications (data mining, technical trading, and performance analysis) that you are probably most familiar with. In this short one-hour event, I focus on the "using R" rather than the Finance examples. Therefore, few interpretations of these examples will be provided. Instead, I would like you to use your field of knowledge to help yourself and hope that you can extend what you learn to other finance R packages.

Published in: Business

R in finance: Introduction to R and Its Applications in Finance

  1. 1. 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 Time:10:00-11:00am;13thMay2016 Place:N500.32GriffithUniversity 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.20.0 CBA.AX.Adjusted ANZ.AX.Adjusted Drawdowns
  2. 2. 2016/5/13 2 2 RoadMapofRinFinance
  3. 3. 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.
  4. 4. 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://spectrum.ieee.org/computing/software/the-2015-top-ten-programming-languages Source:IEEE(theworld'slargesttechnicalprofessionalorganization) Topninelanguagesareopen-source
  5. 5. 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
  6. 6. 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: GoogleTrend, http://goo.gl/vO6LhA
  7. 7. 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
  8. 8. 2016/5/13 8 @LiangCZhang i n F i n a n c e Use R! Setting up R working environment Install 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
  9. 9. 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
  10. 10. 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 ∑ !"
  11. 11. 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
  12. 12. 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
  13. 13. 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 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
  14. 14. 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 servers Data 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 Yes https://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)
  15. 15. 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
  16. 16. 2016/5/13 16 @LiangCZhang i n F i n a n c e Loading data from Yahoo Finance Now, consider you need to use these two assets for your studies Commonwealth Bank of Australia ANZ 16 Company name (ticker/stock symbol)
  17. 17. 2016/5/13 17 @LiangCZhang i n F i n a n c e Data Subsetting for xts object Code Results 17 Findoutthedifferencebetweenthem
  18. 18. 2016/5/13 18 @LiangCZhang i n F i n a n c e Loading data from Yahoo Finance Take a look at what you have downloaded with R Commonwealth Bank of Australia ANZ 18
  19. 19. 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
  20. 20. 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 70727476788082 CBA.AX$CBA.AX.Adjusted Jan 01 2016 Jan 25 2016 Feb 15 2016 Mar 07 2016 Mar 28 2016 70727476788082 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)
  21. 21. 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 Source:Probe-meteo.com
  22. 22. 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
  23. 23. 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
  24. 24. 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
  25. 25. 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
  26. 26. 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
  27. 27. 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") Findoutthe differencebetween them
  28. 28. 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]
  29. 29. 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
  30. 30. 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","ad d.risk","add.density"))) rug(Return.CBA.AX,col = "red") #change rugs' color CBA.AX.Adjusted Returns Density -0.15 -0.10 -0.05 0.00 0.05 0.10 0.15 051015 95%ModVaR 95%VaR
  31. 31. 2016/5/13 31 @LiangCZhang i n F i n a n c e Performance Analysis Time Series Plot 31 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 -0.15 -0.10 -0.05 0.00 0.05 0.10 0.15 CBA.AX.Adjusted ANZ.AX.Adjusted Returns 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
  32. 32. 2016/5/13 32 @LiangCZhang i n F i n a n c e Performance Analysis Drawdown Plot 32 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 -0.5 -0.4 -0.3 -0.2 -0.1 0.0 CBA.AX.Adjusted ANZ.AX.Adjusted Drawdowns 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
  33. 33. 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)
  34. 34. 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:http://52.2.13.97:3838/fama_french/
  35. 35. 2016/5/13 35 @LiangCZhang i n F i n a n c e Conclusion: Where to find the future of finance: Data 35
  36. 36. 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
  37. 37. 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.
  38. 38. 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 E: scure1026@gmail.com @LiangCZhang

×