Using R 4/10/2012 Geoff Black Matthew Goglia. What is R? R is a free program for statistical analysis and graphical display of data. R uses code; these.

Slides:



Advertisements
Similar presentations
Slides 2c: Using Spreadsheets for Modeling - Excel Concepts (Updated 1/19/2005) There are several reasons for the popularity of spreadsheets: –Data are.
Advertisements

Chapter 2 Matrices Finite Mathematics & Its Applications, 11/e by Goldstein/Schneider/Siegel Copyright © 2014 Pearson Education, Inc.
Nonlinear and multiple regression analysis Just a straightforward extension of linear regression analysis.
Goldstein/Schnieder/Lay: Finite Math & Its Applications, 9e 1 of 86 Chapter 2 Matrices.
Efficient Portfolios with no short-sale restriction MGT 4850 Spring 2008 University of Lethbridge.
FINANCIAL TRADING AND MARKET MICRO-STRUCTURE MGT 4850 Spring 2011 University of Lethbridge.
Mathematics of Cryptography Part I: Modular Arithmetic, Congruence,
Efficient Portfolios with no short-sale restriction MGT 4850 Spring 2009 University of Lethbridge.
Finite Mathematics & Its Applications, 10/e by Goldstein/Schneider/SiegelCopyright © 2010 Pearson Education, Inc. 1 of 86 Chapter 2 Matrices.
Arithmetic Operations on Matrices. 1. Definition of Matrix 2. Column, Row and Square Matrix 3. Addition and Subtraction of Matrices 4. Multiplying Row.
CE 311 K - Introduction to Computer Methods Daene C. McKinney
Introduction to R Statistical Software Anthony (Tony) R. Olsen USEPA ORD NHEERL Western Ecology Division Corvallis, OR (541)
Efficient Portfolios without short sales MGT 4850 Spring 2007 University of Lethbridge.
Lecture 4 Advanced Topics. OVERVIEW Importing Data Data Analysis Add-In Solver Macros.
Applied Bioinformatics Introduction to Linux and R Bing Zhang Department of Biomedical Informatics Vanderbilt University
Matrix Equations Step 1: Write the system as a matrix equation. A three-equation system is shown below.
Portfolio Statistics  Portfolio Expected Return: E(r p ) = w T r  Portfolio Variance:  2 p = w T  w  Sum of portfolio weights: = w T 1 –where w is.
© Paradigm Publishing, Inc. 5-1 Chapter 5 Application Software Chapter 5 Application Software.
Barnett/Ziegler/Byleen Finite Mathematics 11e1 Review for Chapter 4 Important Terms, Symbols, Concepts 4.1. Systems of Linear Equations in Two Variables.
Matrices. Given below is a record of all the types of books kept in a class library. TypeFictionGeneral Malay2547 Chinese4072 English8085.
Objectives Understand what MATLAB is and why it is widely used in engineering and science Start the MATLAB program and solve simple problems in the command.
1 Lab of COMP 406 Teaching Assistant: Pei-Yuan Zhou Contact: Lab 1: 12 Sep., 2014 Introduction of Matlab (I)
Engineering Fundamentals Decision Matrix Spreadsheet Tutorial 1.
Using Matrices to Solve Systems of Equations Matrix Equations l We have solved systems using graphing, but now we learn how to do it using matrices.
Determinants and Multiplicative Inverses of Matrices
The inverse of a Square Matrix 2.1 Day 1 (Out of Pre-Calc book 8.3) We are reloading for another chapter.
Matrices NamingCalculatorApplication. Making & Naming a Matrix Matrix A.
Introduction to Matlab T.E. Ochsner Getting Started with Matlab etting-started-with-matlab.html
Chapter 1: Getting Started with MATLAB MATLAB for Scientist and Engineers Using Symbolic Toolbox.
Vectors and Matrices In MATLAB a vector can be defined as row vector or as a column vector. A vector of length n can be visualized as matrix of size 1xn.
1 Appendix 10 A: A Linear-Programming Approach to Portfolio- Analysis Models (Related to ) By Cheng Few Lee Joseph Finnerty John Lee Alice C Lee.
Class Opener:. Identifying Matrices Student Check:
Unit 5 Spreadsheets 5.09 Sorting & Filtering. Introduction How many times have you had to sort words in alphabetic order or you needed to find certain.
4.5 Matrices, Determinants, Inverseres -Identity matrices -Inverse matrix (intro) -An application -Finding inverse matrices (by hand) -Finding inverse.
Introduction to Matlab  Matlab is a software package for technical computation.  Matlab allows you to solve many numerical problems including - arrays.
8.2 Operations With Matrices
2.1 – Linear and Quadratic Equations Linear Equations.
 A basic equation is made of three parts, coefficients, variables, and the constants.  The coefficient is the number before the variable  The variable.
Algebra Matrix Operations. Definition Matrix-A rectangular arrangement of numbers in rows and columns Dimensions- number of rows then columns Entries-
Practical Kinetics Exercise 0: Getting Started Objectives: 1.Install Python and IPython Notebook 2.print “Hello World!”
Copyright ©2015 Pearson Education, Inc. All rights reserved.
BELL-WORK Solve the system of equations using matrices:
Notes Over 4.4 Finding the Inverse of 2 x 2 Matrix.
Copyright © 1999 by the McGraw-Hill Companies, Inc. Barnett/Ziegler/Byleen College Algebra, 6 th Edition Chapter Seven Matrices & Determinants.
Introduction to Financial Modeling MGT 4850 Spring 2008 University of Lethbridge.
Matrices. Variety of engineering problems lead to the need to solve systems of linear equations matrixcolumn vectors.
It’s a Spreadsheet What’s a Spreadsheet. A spreadsheet is: An interactive computer program that organizes and analyzes data.
Project 1 to 3. Project 1 (10 pts) (use the word document to enter results and answers – Save this file as Lname_BUA350_Cohort#_projects#.doc Go to Total.
MTH108 Business Math I Lecture 20.
Determinants.
Matrix Equations Step 1: Write the system as a matrix equation. A three-equation system is shown below. First matrix are the coefficients of all the.
Matrix Operations SpringSemester 2017.
Quadratic Inequalities
A quadratic equation is written in the Standard Form,
Determinants and Multiplicative Inverses of Matrices
Linear Equations in Linear Algebra
Chapter 4 Systems of Linear Equations; Matrices
Lial/Hungerford/Holcomb/Mullins: Mathematics with Applications 11e Finite Mathematics with Applications 11e Copyright ©2015 Pearson Education, Inc. All.
Microsoft Excel 101.
Unit 3: Matrices
Solving Quadratic Equations by Factoring
Capital Asset Pricing Model
3.8 Use Inverse Matrices to Solve Linear Systems
Vectors and Matrices In MATLAB a vector can be defined as row vector or as a column vector. A vector of length n can be visualized as matrix of size 1xn.
Python Lesson’S 1 & 2 Mr. Kalmes.
3.6 Multiply Matrices.
A square matrix is a matrix with the same number of columns as rows.
Chapter 4 Systems of Linear Equations; Matrices
Matrix Operations SpringSemester 2017.
Matrix Multiplication Sec. 4.2
Presentation transcript:

Using R 4/10/2012 Geoff Black Matthew Goglia

What is R? R is a free program for statistical analysis and graphical display of data. R uses code; these saved scripts can be easily used again to perform calculations on new data It is particularly strong at performing matrix calculations Gives us the ability to quickly pull various data in a usable format

Before Beginning R 1.Download R 2.Demonstration Basic Arithmetic Matrices Treasury Bill data

1) Importing Data and Calculating Returns

Before Beginning R 1.Create an Excel Spreadsheet Input all ETF symbols that you want data for into one column Save as a.CSV file, for example “symbols.csv” 2.Make sure your spreadsheet and R are in the same directory Create a new folder on your desktop and save your spreadsheet and a copy of R in it Set R to start in the same directory as your spreadsheet by editing “properties” for PC or “preferences” for Mac

Install and Load Yahoo Finance Package Open R and type in the following: >if (!require(fImport)) install.packages ('fImport’) >library("fImport") You are now able to import market data from Yahoo. (“>” is the command line in R; it is not part of the code.)

Pull Symbols from Excel Spreadsheet Type in the following: >symbols <- scan("symbols.csv",what=character(),sep = ",") “<-” gives a definition. Now R knows which ETFs to pull data for. Make sure to use the name of the spreadsheet that you created if you did not name it “symbols.csv”.

Load Yahoo Data for ETFs Type in the following: >stockdata <- yahooSeries(symbols,nDaysBack = 365*3) This code pulls the last 3 years of data for each ETF in your Excel spreadsheet. You can change the number of years by changing the last digit in the code.

Remove Unnecessary Data Type in the following: >c <- 1:(ncol(stockdata)/6)*6 >stockadj <- stockdata[,c] We only need the 6 th column of data that Yahoo gives us. The first code, “c” defines the columns we need and ignores the ones we don’t. The second line defines “stockadj” as the data to be extracted from the Yahoo data we received

Calculate Daily Returns Type in the following: >returns <- stockadj/lag(stockadj,k=1)-1 This code defines returns as: (price/previous day’s price)-1

Write to File Type in the following: >write.table(returns, "returns.csv", sep=",", col.names=NA) This code will produce an Excel spreadsheet in your working directory under the name “returns.csv”. You now have 3 years’ of daily returns for each ETF in your original spreadsheet.

Final Code if (!require(fImport)) install.packages('fImport') library("fImport") symbols <- scan("symbols.csv",what=character(),sep = ",") stockdata <- yahooSeries(symbols,nDaysBack = 365*3) c <- 1:(ncol(stockdata)/6)*6 stockadj <- stockdata[,c] returns <- stockadj/lag(stockadj,k=1)-1 write.table(returns, "returns.csv", sep=",", col.names=NA) Now that you know how to write the code, you can just copy and paste the above into R. You are now ready to use R to solve for GMVP.

2) Creating GMVP

A Review 1Make a Covariance Matrix of returns above the risk- free rate 2Make an Inverse Matrix 3Make a Vector of Ones 4Multiply the Inverse Matrix by the Vector of One

This is the basic equation we need to solve: Source: cran.r-project.org/web/packages/quadprog/quadprog.pdf

Install the Quadratic Programming Package >if (!require(quadprog)) install.packages('quadprog') >library("quadprog")

Definitions >n <- dim(returns)[1] >p <- dim(returns)[2] >ub <- rep(.1,p) >zeros <- numeric(p) >ones <- zeros +1 >dim(ub) <- c(p,1) >dim(ones) <- c(p,1) >dim(zeros) <- c(p,1) >dim(ub) <- c(p,1 ) Number of rows, number of columns, upper bounds, vectors

Construct the A-Matrix and B-Vector >Atmp <- rbind(t(ones),diag(p),-diag(p)) >Amat <- t(Atmp) >bvec <- rbind(1,zeros,-ub) Constraints: Ax >= b Sum of stock weights = 1 No shorts Weights must be below the upper bound

Build the Covariance Matrix >sigma<- cov(returns, use="pairwise") Pairwise means there must be two values. If there is only one value the covariance is not calculated.

Solve for GMVP and Write to Table >gmvp=solve.QP(sigma,zeros,Amat,bvec,meq=1) >gmvp$solution <- round(gmvp$solution,2) >soln<-matrix(cbind(symbols,gmvp$solution),nrow=p,ncol=2) >write.table(soln, "soln.csv”, sep=",",col.names=F,row.names=F) Meq = 1 means the first row of constraints is an equality

Final Code if (!require(quadprog)) install.packages('quadprog') library("quadprog") n <- dim(returns)[1] p <- dim(returns)[2] ub <- rep(.1,p) zeros <- numeric(p) ones <- zeros +1 dim(ub) <- c(p,1) dim(ones) <- c(p,1) dim(zeros) <- c(p,1) dim(ub) <- c(p,1) Atmp <- rbind(t(ones),diag(p),-diag(p)) Amat <- t(Atmp) bvec <- rbind(1,zeros,-ub) sigma<- cov(returns, use="pairwise”) gmvp=solve.QP(sigma,zeros,Amat,bvec,meq=1) #meq=1 means first row of contraints is an equality gmvp$solution <- round(gmvp$solution,2) soln<-matrix(cbind(symbols,gmvp$solution),nrow=p,ncol=2) write.table(soln, "soln.csv", sep=",",col.names=F,row.names=F) Now that you know how to write the code, you can just copy and paste the above into R to solve for GMVP.