lecture 22 - purdue · pdf filelecture 22 xiaoguang wang stat 598w april 14, ... cell...

37
Lecture 22 Xiaoguang Wang STAT 598W April 14, 2014 (STAT 598W) Lecture 22 1 / 37

Upload: duongcong

Post on 29-Mar-2018

212 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Lecture 22 - Purdue · PDF fileLecture 22 Xiaoguang Wang STAT 598W April 14, ... Cell addresses ... ("data"), Range("A1:B20")). (STAT 598W) Lecture 22 20 / 37. Objects belong to a

Lecture 22

Xiaoguang Wang

STAT 598W

April 14, 2014

(STAT 598W) Lecture 22 1 / 37

Page 2: Lecture 22 - Purdue · PDF fileLecture 22 Xiaoguang Wang STAT 598W April 14, ... Cell addresses ... ("data"), Range("A1:B20")). (STAT 598W) Lecture 22 20 / 37. Objects belong to a

Outline

1 Excel review

2 VBA: Introduction

3 VBA: Subroutines

(STAT 598W) Lecture 22 2 / 37

Page 3: Lecture 22 - Purdue · PDF fileLecture 22 Xiaoguang Wang STAT 598W April 14, ... Cell addresses ... ("data"), Range("A1:B20")). (STAT 598W) Lecture 22 20 / 37. Objects belong to a

Outline

1 Excel review

2 VBA: Introduction

3 VBA: Subroutines

(STAT 598W) Lecture 22 3 / 37

Page 4: Lecture 22 - Purdue · PDF fileLecture 22 Xiaoguang Wang STAT 598W April 14, ... Cell addresses ... ("data"), Range("A1:B20")). (STAT 598W) Lecture 22 20 / 37. Objects belong to a

Some Assumptions

In this course I will assume you know:

Basic Excel functions: Mathematical and Trigonometrical, Statistical.

Look-up functions: vlookup, hlookup, match and index.

If function.

Basic Excel plotting.

If you have more questions, please let me know...

(STAT 598W) Lecture 22 4 / 37

Page 5: Lecture 22 - Purdue · PDF fileLecture 22 Xiaoguang Wang STAT 598W April 14, ... Cell addresses ... ("data"), Range("A1:B20")). (STAT 598W) Lecture 22 20 / 37. Objects belong to a

Matrix manipulation

Main source: Jackson and Staunton (2001)

Range names.

Transpose.

Multiplication.

Inversion.

(STAT 598W) Lecture 22 5 / 37

Page 6: Lecture 22 - Purdue · PDF fileLecture 22 Xiaoguang Wang STAT 598W April 14, ... Cell addresses ... ("data"), Range("A1:B20")). (STAT 598W) Lecture 22 20 / 37. Objects belong to a

Regression tools

INTERCEPT(), SLOPE(), RSQ(), STEYX()

LINEST()

Regression in Analysis ToolPak. (Location:Data -> Data Analysis)

Example: S&P500 vs NVIDIA stock. (10/8/10-1/7/11)

(STAT 598W) Lecture 22 6 / 37

Page 7: Lecture 22 - Purdue · PDF fileLecture 22 Xiaoguang Wang STAT 598W April 14, ... Cell addresses ... ("data"), Range("A1:B20")). (STAT 598W) Lecture 22 20 / 37. Objects belong to a

Goal Seek

Suppose we have an European Call Option with the following information:

Stock Price: 100

Exercise Price: 95

Interest rate: 8% per year

Dividend yield: 3% per year

Maturity: 1/2 year

Volatility: 20% per year.

Option’s market value: 10.43

What is the required volatility such that the BS price is equal to the marketvalue? (Using Goal Seek: Location: Data -> What-If Analysis)

(STAT 598W) Lecture 22 7 / 37

Page 8: Lecture 22 - Purdue · PDF fileLecture 22 Xiaoguang Wang STAT 598W April 14, ... Cell addresses ... ("data"), Range("A1:B20")). (STAT 598W) Lecture 22 20 / 37. Objects belong to a

Goal Seek

Recall the BS Call Option formula with dividends:

C (S ,T ) = e−rT (F · N(d1)− K · N(d2))

where:

F = S · e(r−q)T

d1 =ln (F/K ) + (σ2/2)T

σ√T

d2 = d1 − σ√T

(STAT 598W) Lecture 22 8 / 37

Page 9: Lecture 22 - Purdue · PDF fileLecture 22 Xiaoguang Wang STAT 598W April 14, ... Cell addresses ... ("data"), Range("A1:B20")). (STAT 598W) Lecture 22 20 / 37. Objects belong to a

Solver

Portfolio Optimization Problem.

Markowitz optimization problem: to find mean-variance efficientportfolios. (highest expected return for a given level of risk)

Suppose we have n assets then we can compute:

Portfolio return:

E (rp) =n∑

i=1

wiE (ri )

Portfolio risk:

σp =

√√√√ n∑i=1

n∑j=1

wiwjcov(ri , rj)

E (ri ): expected return asset i , wi : capital allocation on asset i .

(STAT 598W) Lecture 22 9 / 37

Page 10: Lecture 22 - Purdue · PDF fileLecture 22 Xiaoguang Wang STAT 598W April 14, ... Cell addresses ... ("data"), Range("A1:B20")). (STAT 598W) Lecture 22 20 / 37. Objects belong to a

Solver

Consider three asset classes in US (TBills, Bonds and Shares) between1926 and 1992. The average returns and covariance matrix are shown inexe1.xls.

Consider the weights: 40%, 50% and 10%. Compute the portfolioexpected return and standard deviation.

Solve the following problem: (Using Solver. Location:Data -> Solver)

minwσp

with the constraints:∑

i wi = 1 and E (rp) >= 7%.

(STAT 598W) Lecture 22 10 / 37

Page 11: Lecture 22 - Purdue · PDF fileLecture 22 Xiaoguang Wang STAT 598W April 14, ... Cell addresses ... ("data"), Range("A1:B20")). (STAT 598W) Lecture 22 20 / 37. Objects belong to a

Outline

1 Excel review

2 VBA: Introduction

3 VBA: Subroutines

(STAT 598W) Lecture 22 11 / 37

Page 12: Lecture 22 - Purdue · PDF fileLecture 22 Xiaoguang Wang STAT 598W April 14, ... Cell addresses ... ("data"), Range("A1:B20")). (STAT 598W) Lecture 22 20 / 37. Objects belong to a

What is VBA?

Visual Basic for Applications (VBA) is an implementation ofMicrosoft’s event-driven programming language Visual Basic 6 and itsassociated integrated development environment (IDE), which are builtinto most Microsoft Office applications.

Visual Basic for Applications enables building user defined functions,automating processes and accessing Windows API and other low-levelfunctionality through dynamic-link libraries (DLLs).

It can be used to control many aspects of the host application,including manipulating user interface features, such as menus andtoolbars, and working with custom user forms or dialog boxes.

(STAT 598W) Lecture 22 12 / 37

Page 13: Lecture 22 - Purdue · PDF fileLecture 22 Xiaoguang Wang STAT 598W April 14, ... Cell addresses ... ("data"), Range("A1:B20")). (STAT 598W) Lecture 22 20 / 37. Objects belong to a

What is VBA?

VBA is closely related to Visual Basic and uses the Visual BasicRuntime Library, but can normally only run code within a hostapplication rather than as a standalone program. It can, however, beused to control one application from another via OLE Automation.For example, it is used to automatically create a Word report fromExcel data, which is in turn automatically collected by Excel frompolled observation sensors.

Code written in VBA is compiled to a proprietary intermediatelanguage called P-code (packed code), which the hosting applications(Access, Excel, Word, Outlook, and PowerPoint) store as a separatestream in COM Structured Storage files (e.g., .doc or .xls)independent of the document streams. The intermediate code is thenexecuted by a virtual machine (hosted by the hosting application).

(STAT 598W) Lecture 22 13 / 37

Page 14: Lecture 22 - Purdue · PDF fileLecture 22 Xiaoguang Wang STAT 598W April 14, ... Cell addresses ... ("data"), Range("A1:B20")). (STAT 598W) Lecture 22 20 / 37. Objects belong to a

Excel Macros

Main idea: Repeat tasks efficiently on the Excel Worksheet.

Location: View -> Macros.

(STAT 598W) Lecture 22 14 / 37

Page 15: Lecture 22 - Purdue · PDF fileLecture 22 Xiaoguang Wang STAT 598W April 14, ... Cell addresses ... ("data"), Range("A1:B20")). (STAT 598W) Lecture 22 20 / 37. Objects belong to a

Excel Macros

Using the data in Worksheet #1 of exe2.xls, compute:

Five number summary.95% confidence interval of the sample mean.

Construct an Excel macro with the previous tasks.

(STAT 598W) Lecture 22 15 / 37

Page 16: Lecture 22 - Purdue · PDF fileLecture 22 Xiaoguang Wang STAT 598W April 14, ... Cell addresses ... ("data"), Range("A1:B20")). (STAT 598W) Lecture 22 20 / 37. Objects belong to a

Cell addresses

VBA can interpret cell addresses in two different ways:

“A1“ mode.”R1C1” mode.

Please take a look of “=ADDRESS()” Excel function and the website:http://www.lytebyte.com/2008/04/29/what-are-a1-and-r1c1-reference-style-in-excel/

This will help you to understand how the Macro recorder works.

(STAT 598W) Lecture 22 16 / 37

Page 17: Lecture 22 - Purdue · PDF fileLecture 22 Xiaoguang Wang STAT 598W April 14, ... Cell addresses ... ("data"), Range("A1:B20")). (STAT 598W) Lecture 22 20 / 37. Objects belong to a

VBA Editor

Location: Developer->Visual Basic Most important components:

Project Window: shows the components of all open projects.

Properties Window: shows the properties of a selected object.

Code Window: contains VBA code for procedures.

Object Browser: checking the objects, methods and propertiesavailable in VBA.

(STAT 598W) Lecture 22 17 / 37

Page 18: Lecture 22 - Purdue · PDF fileLecture 22 Xiaoguang Wang STAT 598W April 14, ... Cell addresses ... ("data"), Range("A1:B20")). (STAT 598W) Lecture 22 20 / 37. Objects belong to a

VBA

Visual Basic for Applications

Part of the Visual Basic family.

VBA runs within a host environment. (In our case: Microsoft Excel)

VBA is an interpreted language (like MATLAB, R), it doesn’t compileyour files (or create an executable file).

Microsoft Office provides VBA for all its applications.

VBA is an objected-oriented language. (like C++, but R andMATLAB are module-oriented languages)

(STAT 598W) Lecture 22 18 / 37

Page 19: Lecture 22 - Purdue · PDF fileLecture 22 Xiaoguang Wang STAT 598W April 14, ... Cell addresses ... ("data"), Range("A1:B20")). (STAT 598W) Lecture 22 20 / 37. Objects belong to a

VBA: Object-Oriented language

What is an object?

Any component in the Excel environment: Workbooks, worksheets,ranges, charts, Excel itself.

The VBA objects can be described as follows:

Objects come in collections.

Objects belong to a hierarchy.

Objects have properties.

Objects have methods.

(STAT 598W) Lecture 22 19 / 37

Page 20: Lecture 22 - Purdue · PDF fileLecture 22 Xiaoguang Wang STAT 598W April 14, ... Cell addresses ... ("data"), Range("A1:B20")). (STAT 598W) Lecture 22 20 / 37. Objects belong to a

Objects in collections

The objects can be labeled or counted in collections:

Workbooks: collection containing several workbooks. For example:Workbooks(1)

Worksheets

Charts

some collections are singular:

Application: collection consisting of Excel application.

Range: collection of adjacent Worksheet cells.

The objects can be referenced by indexing by number (Workbooks(1)) orby name (Range("data"), Range("A1:B20")).

(STAT 598W) Lecture 22 20 / 37

Page 21: Lecture 22 - Purdue · PDF fileLecture 22 Xiaoguang Wang STAT 598W April 14, ... Cell addresses ... ("data"), Range("A1:B20")). (STAT 598W) Lecture 22 20 / 37. Objects belong to a

Objects belong to a hierarchy

We can move from one level to another by using dot operator.Example:Application.Workbooks("Model.xls").Sheets("inputs").Range("data")

In VBA we can use the “Active” object to reference any other siblingobject. For example:ActiveWorkbook.Sheets("inputs").Range("data") refers to the“input” sheet, range “data” on the active workbook.

(STAT 598W) Lecture 22 21 / 37

Page 22: Lecture 22 - Purdue · PDF fileLecture 22 Xiaoguang Wang STAT 598W April 14, ... Cell addresses ... ("data"), Range("A1:B20")). (STAT 598W) Lecture 22 20 / 37. Objects belong to a

Objects have properties

Properties: attributes of an object. Syntax: Object.Property

Example: Application.ScreenUpdating = FalseRange has several properties: Range("B23").Name="month2",Range("B23").Value=4000.

You can assign a property’s value to any variable:valpp=Range("B23").Value.

(STAT 598W) Lecture 22 22 / 37

Page 23: Lecture 22 - Purdue · PDF fileLecture 22 Xiaoguang Wang STAT 598W April 14, ... Cell addresses ... ("data"), Range("A1:B20")). (STAT 598W) Lecture 22 20 / 37. Objects belong to a

Objects have methods

Methods: Predefined activities of an object. Syntax: Object.Method

Example:

Range("A1:B3").Select

Range("A1:B10").Copy

Range("storerange").PasteSpecial

Workbooks(Model.xls).Activate

(STAT 598W) Lecture 22 23 / 37

Page 24: Lecture 22 - Purdue · PDF fileLecture 22 Xiaoguang Wang STAT 598W April 14, ... Cell addresses ... ("data"), Range("A1:B20")). (STAT 598W) Lecture 22 20 / 37. Objects belong to a

VBA Procedures

Definition: block of code that performs specific actions.

Types:

Subroutines: doesn’t return a value.Functions: returns a value.

The Macro recorder only creates subroutines.

(STAT 598W) Lecture 22 24 / 37

Page 25: Lecture 22 - Purdue · PDF fileLecture 22 Xiaoguang Wang STAT 598W April 14, ... Cell addresses ... ("data"), Range("A1:B20")). (STAT 598W) Lecture 22 20 / 37. Objects belong to a

Outline

1 Excel review

2 VBA: Introduction

3 VBA: Subroutines

(STAT 598W) Lecture 22 25 / 37

Page 26: Lecture 22 - Purdue · PDF fileLecture 22 Xiaoguang Wang STAT 598W April 14, ... Cell addresses ... ("data"), Range("A1:B20")). (STAT 598W) Lecture 22 20 / 37. Objects belong to a

Subroutines

Syntax:

Sub Macro_name(arguments)

’comments

...

...

End Sub

Create a subroutine linking the contents in cell A5 to cell A8 in the“Example2” sheet.

Create a subroutine linking the contents in cell B1 to cell B3 in theactive sheet. Hint: use ActiveSheet.

(STAT 598W) Lecture 22 26 / 37

Page 27: Lecture 22 - Purdue · PDF fileLecture 22 Xiaoguang Wang STAT 598W April 14, ... Cell addresses ... ("data"), Range("A1:B20")). (STAT 598W) Lecture 22 20 / 37. Objects belong to a

Interaction (Output)

You can use the MsgBox to display a message box when a procedureis running.

What is this code doing?

Sub exercise3()

’MsgBox practice

vl=Range("B5").Value

Msgbox("Your value in B5 is "& vl)

End Sub

(STAT 598W) Lecture 22 27 / 37

Page 28: Lecture 22 - Purdue · PDF fileLecture 22 Xiaoguang Wang STAT 598W April 14, ... Cell addresses ... ("data"), Range("A1:B20")). (STAT 598W) Lecture 22 20 / 37. Objects belong to a

Interaction (Input)

Use the InputBox function to prompt for specific user input duringthe execution of a procedure.

Syntax:

Sub Factorial()

’calculates the factorial of a number

fac = 1

num = InputBox("Enter Number")

For i = 1 To num

fac = i * fac

Next i

MsgBox ("Factorial is" & fac)

End Sub

(STAT 598W) Lecture 22 28 / 37

Page 29: Lecture 22 - Purdue · PDF fileLecture 22 Xiaoguang Wang STAT 598W April 14, ... Cell addresses ... ("data"), Range("A1:B20")). (STAT 598W) Lecture 22 20 / 37. Objects belong to a

Excel Functions

By using the WorksheetFunction command we can call some ofpredefined Excel functions.

Example: Create a subroutine that computes n!.

Sub Factorial()

’calculates the factorial of a number

num = InputBox("Enter integer number ", "Calculate Factorial ")

fac = Application.Fact(num)

MsgBox "Factorial is "& fac

End Sub

(STAT 598W) Lecture 22 29 / 37

Page 30: Lecture 22 - Purdue · PDF fileLecture 22 Xiaoguang Wang STAT 598W April 14, ... Cell addresses ... ("data"), Range("A1:B20")). (STAT 598W) Lecture 22 20 / 37. Objects belong to a

Data Types

In VBA (and in any other language) it is important to define explicitlyall the variables used.

You can do this by declaring Option Explicit at the beggining ofthe module.

Syntax: Dim variable_name As Type.

(STAT 598W) Lecture 22 30 / 37

Page 31: Lecture 22 - Purdue · PDF fileLecture 22 Xiaoguang Wang STAT 598W April 14, ... Cell addresses ... ("data"), Range("A1:B20")). (STAT 598W) Lecture 22 20 / 37. Objects belong to a

Data Types

VBA integers:

Data Type Bytes Range of Values

Byte 1 0 to 255Integer 2 -32,768 to 32,767Long 4 -2,147,483,648 to 2,147,483,647

(STAT 598W) Lecture 22 31 / 37

Page 32: Lecture 22 - Purdue · PDF fileLecture 22 Xiaoguang Wang STAT 598W April 14, ... Cell addresses ... ("data"), Range("A1:B20")). (STAT 598W) Lecture 22 20 / 37. Objects belong to a

Data Types

VBA Numeric values (positive and negative values):

Data Type Bytes Range of Values (absolute value)

Single 4 ≈ 1.410−45 to 3.4× 1038

Double 8 ≈ 4.9410−324 to 1.79× 10308

VBA Boolean data:

Dim test As Boolean

test=True

(STAT 598W) Lecture 22 32 / 37

Page 33: Lecture 22 - Purdue · PDF fileLecture 22 Xiaoguang Wang STAT 598W April 14, ... Cell addresses ... ("data"), Range("A1:B20")). (STAT 598W) Lecture 22 20 / 37. Objects belong to a

Data Types

VBA Object variable

Any object in Excel Application can be defined as an Object variable.

Examples:

Dim chrt As Chart

Dim sheet1 As Worksheet

Dim book1 As Workbook

Dim pv1 As PivotTable

VBA Date variable:

You have to use a slightly different notation:

Const Startdate As Date=#6/27/1981#

Range: 1/1/100 to 12/31/9999.

(STAT 598W) Lecture 22 33 / 37

Page 34: Lecture 22 - Purdue · PDF fileLecture 22 Xiaoguang Wang STAT 598W April 14, ... Cell addresses ... ("data"), Range("A1:B20")). (STAT 598W) Lecture 22 20 / 37. Objects belong to a

Data Types

VBA String variable

Store a sequence a characters.

Example:

Dim samplestring,samplestring2 As String

samplestring="Name"

samplestring2="Last Name"

VBA Variant variable

Default data type in VBA. It can contain any type of data.

Variant is expensive in terms of storage size. (16 and more bytes.)

(STAT 598W) Lecture 22 34 / 37

Page 35: Lecture 22 - Purdue · PDF fileLecture 22 Xiaoguang Wang STAT 598W April 14, ... Cell addresses ... ("data"), Range("A1:B20")). (STAT 598W) Lecture 22 20 / 37. Objects belong to a

Constants

Values that don’t change within your code.

You can modify their values only once.

Example: Const Temp as Double=68.23

(STAT 598W) Lecture 22 35 / 37

Page 36: Lecture 22 - Purdue · PDF fileLecture 22 Xiaoguang Wang STAT 598W April 14, ... Cell addresses ... ("data"), Range("A1:B20")). (STAT 598W) Lecture 22 20 / 37. Objects belong to a

VBA Arrays

Group of variables with the same name and data type.

By default the array’s lowest index starts always at 0. It is possible tochange this option by using: Option Base 1 at the start of themodule.

This example gives different results depending on the Option-Basevalue.

Option Base 1

Sub exercise5()

’gives b=20 if Option Base is 1; gives b=30

’in absence of Option Base statement

Dim avec, b

avec = Array(10,20,30)

b = avec(2)

MsgBox "b is" &b

End Sub

(STAT 598W) Lecture 22 36 / 37

Page 37: Lecture 22 - Purdue · PDF fileLecture 22 Xiaoguang Wang STAT 598W April 14, ... Cell addresses ... ("data"), Range("A1:B20")). (STAT 598W) Lecture 22 20 / 37. Objects belong to a

VBA Dynamic Arrays

You can create dynamic arrays in VBA by using:Dim array_name() As Type.

Use ReDim array_name(n) to re-define the array.

Example: First define the vector ”cvec” as dynamic array and thenredefine it according to the counts of the selected range ”dvec”

Sub SelectCount()

’re-Dim data array cvec

Dim n, cvec()

ActiveSheet.range("dvec").Select

n = Selection.Count

ReDim cvec(n)

MsgBox ("The length of the vector cvec is" & n)

End Sub

(STAT 598W) Lecture 22 37 / 37