Basic R for Finance
Total Page:16
File Type:pdf, Size:1020Kb
Owner: DAWSON FRANCE ([email protected]) @ 109.2.242.246 Basic R for Finance Diethelm Würtz Longhow Lam Andrew Ellis Yohan Chalabi Rmetrics Association & Finance Online Owner: DAWSON FRANCE ([email protected]) @ 109.2.242.246 R/Rmetrics eBook Series R/Rmetrics eBooks is a series of electronic books and user guides aimed at students and practitioner who use R/Rmetrics to analyze financial markets. A Discussion of Time Series Objects for R in Finance (2009) Diethelm Würtz, Yohan Chalabi, Andrew Ellis Portfolio Optimization with R/Rmetrics (2010), Diethelm Würtz, William Chen, Yohan Chalabi, Andrew Ellis Basic R for Finance (2010), Diethelm Würtz, Yohan Chalabi, Longhow Lam, Andrew Ellis Early Bird Edition Financial Market Data for R/Rmetrics (2010) Diethelm Würtz, Andrew Ellis, Yohan Chalabi Early Bird Edition Indian Financial Market Data for R/Rmetrics (2010) Diethelm Würtz, Mahendra Mehta, Andrew Ellis, Yohan Chalabi R/Rmetrics Workshop Singapore 2010 (2010) Diethelm Würtz, Mahendra Mehta, David Scott, Juri Hinz Owner: DAWSON FRANCE ([email protected]) @ 109.2.242.246 BASIC R FOR FINANCE DIETHELM WÜRTZ LONGHOW LAM ANDREW ELLIS YOHAN CHALABI RMETRICS ASSOCIATION &FINANCE ONLINE Owner: DAWSON FRANCE ([email protected]) @ 109.2.242.246 Series Editors: PD Dr. Diethelm Würtz Dr. Martin Hanf Institute of Theoretical Physics and Finance Online GmbH Curriculum for Computational Science Weinbergstrasse 41 Swiss Federal Institute of Technology 8006 Zurich Hönggerberg, HIT K 32.2 8093 Zurich Publisher: Contact Address: Finance Online GmbH Rmetrics Association Swiss Information Technologies Weinbergstrasse 41 Weinbergstrasse 41 8006 Zurich 8006 Zurich [email protected] Authors: Cover Design & Photography: Yohan Chalabi, ETH Zurich Chris Eckert Andrew Ellis, Rmetrics Association Leaf dtp production Longhow Lam, ABN AMRO Diethelm Würtz, ETH Zurich ISBN: eISBN: DOI: © 2009-2010, Finance Online GmbH, Zurich All rights reserved. This work may not be translated or copied in whole or in part without the written permission of the publisher (Finance Online GmbH) except for brief excerpts in con- nection with reviews or scholarly analysis. Use in connection with any form of information storage and retrieval, electronic adaptation, computer software, or by similar or dissimilar methodology now known or hereafter developed is forbidden. Limit of Liability/Disclaimer of Warranty: While the publisher and authors have used their best efforts in preparing this book, they make no representations or warranties with respect to the accuracy or completeness of the contents of this book and specifically disclaim any implied warranties of merchantability or fitness for a particular purpose. No warranty may be created or extended by sales representatives or written sales materials. The advice and strategies contained herein may not be suitable for your situation. You should consult with a professional where appropriate. Neither the publisher nor authors shall be liable for any loss of profit or any other commercial damages, including but not limited to special, incidental, consequential, or other damages. Trademark notice: Product or corporate names may be trademarks or registered trademarks, and are used only for identification and explanation, without intent to infringe. Owner: DAWSON FRANCE ([email protected]) @ 109.2.242.246 DEDICATION This book is dedicated to all those who have helped make Rmetrics what it is today: The leading open source software environment in computational finance and financial engineering. Owner: DAWSON FRANCE ([email protected]) @ 109.2.242.246 Owner: DAWSON FRANCE ([email protected]) @ 109.2.242.246 PREFACE R und Rmetrics are the talk of the town. The statistical software package R is one of the most promising tools for rapid prototyping of financial applications. The userR conferences and Rmetrics Meielisalp workshops reflect the growing interest in R und Rmetrics. Have ever thought of giving R a try, using one of the many packages, or even writing your own functions and learning the programming language? If only the initial learning curve weren’t so steep. This is where "Basic R for Finance" can help you: You will learn the basics of programming in R, and how to implement your models and applications. You will not only create graphics, you will also learn how to customize them them to suit your needs. You will learn how to write your own programs, how to write efficient and optimized code. Furthermore, you will be assisted by a multi- tude of very detailed case studies, ranging from computing skewness and kurtosis statistics to designing and optimizing portfolios of assets. This book is divided into two several thematically distinct parts: the first four parts give an introduction to R, and focus on the following topics: computions, programming, plotting and statistics and inference. Parts five, six, svem and eight contain a collection of case studies from topics such as utility functions, asset management, option valuation, and portfo- lio design. We hope you enjoy this book! Diethelm Würtz Zurich, July 2010 vii Owner: DAWSON FRANCE ([email protected]) @ 109.2.242.246 Owner: DAWSON FRANCE ([email protected]) @ 109.2.242.246 CONTENTS DEDICATION V PREFACE VII CONTENTS IX LISTOF FIGURES XV LISTOF TABLES XVII I Computations 1 1 DATA STRUCTURES 3 1.1 Vectors ...................................... 3 1.2 Matrices ..................................... 6 1.3 Arrays ....................................... 9 1.4 Data Frames .................................. 10 1.5 Time Series ................................... 12 1.6 Lists ........................................ 14 1.7 Printing the Object Structure ....................... 18 2 DATA MANIPULATION 19 2.1 Manipulating Vectors ............................ 19 2.2 Manipulating Matrices ........................... 24 2.3 Manipulating Data Frames ....................... 28 2.4 Working with Attributes .......................... 34 2.5 Manipulating Character Strings .................... 36 2.6 Creating Factors from Continuous Data . 40 3 IMPORTING AND EXPORTING DATA 43 3.1 Writing to Text Files ............................. 43 3.2 Reading from a Text File with scan() . 44 3.3 Reading from a Text File with readLines() . 45 ix Owner: DAWSON FRANCE ([email protected]) @ 109.2.242.246 X CONTENTS 3.4 Reading from a Text File with read.table() . 46 3.5 Importing Example Data Files ..................... 49 3.6 Importing Historical Data Sets from the Internet . 50 4 OBJECT TYPES 51 4.1 Characterization of Objects ........................ 51 4.2 Double ...................................... 52 4.3 Integers ...................................... 57 4.4 Complex ..................................... 60 4.5 Logical ...................................... 61 4.6 Missing Data .................................. 62 4.7 Character .................................... 63 4.8 NULL ....................................... 63 II Programming 65 5 WRITING FUNCTIONS 67 5.1 Writing your first function ........................ 67 5.2 Arguments and Variables ......................... 69 5.3 Scoping rules .................................. 72 5.4 Lazy evaluation ................................ 73 5.5 Flow control .................................. 74 6 DEBUGGING YOUR R FUNCTIONS 79 6.1 The traceback() function ........................ 79 6.2 The function warning() and stop() . 80 6.3 Stepping Through a Function ...................... 81 6.4 The function browser() .......................... 82 7 EFFICIENT CALCULATIONS 83 7.1 Vectorized Computations ......................... 83 7.2 The Family of apply() Functions ................... 86 7.3 The function by() .............................. 88 7.4 The Function outer() ........................... 89 8 USING S3 AND S4 CLASSES 91 8.1 S3 Class Model Basics ............................ 91 8.2 S4 Class Model Basics ............................ 96 9 R PACKAGES 97 9.1 Base R packages ................................ 97 9.2 Contributed R Packages from CRAN . 98 9.3 R Packages under Development from R-forge . 98 9.4 R Package Usage ............................... 98 Owner: DAWSON FRANCE ([email protected]) @ 109.2.242.246 CONTENTS XI 9.5 Package Management Functions .................... 99 III Plotting 101 10 HIGH LEVEL PLOTS 103 10.1 Scatter Plots ...................................103 10.2 Line Plots .....................................104 10.3 More about the plot() Function . 106 10.4 Distribution Plots ...............................107 10.5 Pie and Bar Plots ...............................110 10.6 Stars- and Segments Plots . 112 10.7 Bi- and Multivariate Plots . 114 11 CUSTOMIZING PLOTS 117 11.1 More About Plot Function Arguments . 117 11.2 Graphical Parameters ............................120 11.3 Margins, Plot and Figure Regions . 123 11.4 More About Colours .............................126 11.5 Adding Graphical Elements to an Existing Plot . 128 11.6 Controlling the Axes .............................132 12 GRAPHICAL DEVICES 135 12.1 Available Devices ...............................135 12.2 Device Management under Windows . 135 12.3 List of device functions . 137 IV Statistics and Inference 139 13 BASIC STATISTICAL FUNCTIONS 141 13.1 Statistical Summaries ............................141 13.2 Distribution Functions . 143 13.3 Random Numbers ..............................145 13.4 Hypothesis Testing ..............................146 13.5 Parameter Estimation . 148 13.6 Distribution tails and quantiles . 149 14 LINEAR TIME SERIES ANALYSIS 151 14.1 Overview of Functions