advanced financial modeling - archive · 2016. 6. 22. · © edupristine macros building user...

Post on 16-Aug-2021

2 Views

Category:

Documents

0 Downloads

Preview:

Click to see full reader

TRANSCRIPT

© EduPristine – www.edupristine.com/ca

Advanced Financial ModelingMacros

© EduPristine Macros

Agenda

2

Introduction to Macros & Advanced Application Building in Excel• Introduction and context

Key Concepts in Macros Macros as recorded Robots! Designing application to gather user data

• Implementing user forms in Excel Macros• Linking forms to excel cells• Building flexible Charts in Excel

Understanding VBA• Understanding the relevant language constructs• Example: Write your First Macro

Debugging VBA code• Errors in VBA• Step into VBA

Writing more VBA Codes• Random Number Generator: Use of Loop, Excel Functions• Message Box, Input Box

Advanced Financial Applications• Breaking circular loops• Monte Carlo Simulation

© EduPristine Macros

Agenda

3

Introduction to Macros & Advanced Application Building in Excel• Introduction and context

Key Concepts in Macros Macros as recorded Robots! Designing application to gather user data

• Implementing user forms in Excel Macros• Linking forms to excel cells• Building flexible Charts in Excel

Understanding VBA• Understanding the relevant language constructs• Example: Write your First Macro

Debugging VBA code• Errors in VBA• Step into VBA

Writing more VBA Codes• Random Number Generator: Use of Loop, Excel Functions• Message Box, Input Box

Advanced Financial Applications• Breaking circular loops• Monte Carlo Simulation

© EduPristine Macros

Building user applications in excel requires knowledge of advanced functions

Excel is one of the most widely used tools in financial industry• Easy to use• High reach & access to software across geographies• Flexibility• Robustness• Inbuilt features (Most people would not even be using 95% of the features) & Extendibility• Modular and Object Oriented Architecture

Applications, typically requiring back end calculations can be built using simple Excel• Poor user interaction• Not that flexible• Cannot run for “multiple instances”

Applications building in Excel require understanding of advanced features and functions• To collect user inputs in a nice fashion, Graphical User Interface (GUI) can be built• To perform any repeated task excel provides Macro Recording• To generate complex functions, you can use excel functions• To perform complex calculations and operations, Excel VBA (Macros) can be used

4

© EduPristine Macros

Useful, if we are trying to build a complex user application …

Great User Interface

Advanced Calculations

5

© EduPristine Macros

Applications with good user control require advanced features

Excel sheets and applications requiring inputs from users need to have a good user interface Excel provides form controls and active x controls to help create a GUI

Controlling User Inputs

6

© EduPristine Macros

Showing results to users again require creation of dashboards and charts. Building flexibility requires advanced excel features

Macros can also be used to build flexibility in the output format as well

Flexibility in showing results

Dashboards

7

© EduPristine Macros

Automation of repetitive tasks in applications

Most applications would require the task to be done for multiple iterations• For example formatting charts, etc.• For simple routine tasks, Macros can be recorded and used

Training a Robot

Using a Robot

8

© EduPristine Macros

… Automation of repetitive tasks in applications

Most applications would require the task to be done for multiple iterations• VBE can be used to programmatically perform routine tasks repetitively for complex calculations

Programmatically performing routine tasks in applications

9

© EduPristine Macros

Agenda

10

Introduction to Macros & Advanced Application Building in Excel• Introduction and context

Key Concepts in Macros Macros as recorded Robots! Designing application to gather user data

• Implementing user forms in Excel Macros• Linking forms to excel cells• Building flexible Charts in Excel

Understanding VBA• Understanding the relevant language constructs• Example: Write your First Macro

Debugging VBA code• Errors in VBA• Step into VBA

Writing more VBA Codes• Random Number Generator: Use of Loop, Excel Functions• Message Box, Input Box

Advanced Financial Applications• Breaking circular loops• Monte Carlo Simulation

© EduPristine Macros

What are Macros?

A macro is a set of computer instructions• A mini‐computer program• Activated by an event• That tells the computer what to do

Macros are like Robots!!

Create Graphical User Interface (GUI)

Automate Routine Tasks by Recording

Automate Routine Tasks by Programming

11

© EduPristine Macros

Steps in Using Macros

Typically the first level of Macro can be created by Recording the macro A little bit of understanding of VB can help improve the usability multi‐fold

Train the Robot Use the Robot Retrain Reuse

The Robot is as good as you have trained it!

12

© EduPristine Macros 13

The VB Editor

Right click on any existing ribbon tab and choose customize the ribbon. Check the developer tab box and click OK.

Right click on existing tab and choose 

customize the ribbon

Check the developer tab 

box.

Click OK.Now developer tab is in the menu bar.

1

2

3

4

© EduPristine Macros 14

Click on the developer tab on the ribbon and then Go to Visual Basic.

You can select the Visual Basic option under the developer tab or by using shortcut Alt+F11.

The VB Editor

© EduPristine Macros 15

The Visual Basic window is open.

The VB Editor

© EduPristine Macros 16

Click on the first button on the VB editor toolbar. It takes back to the excel. Switching between VB Editor and Excel is also done by using keyboard shortcuts Alt+F11. 

Click on the button for switching back to Excel from VB Editor 

toolbar.

Switching From the VB Editor to Excel

© EduPristine Macros

Introducing the VBA Environment

Code Window

Project Explorer

Run and Control Commands

Use Alt + F11 to get the window

17

© EduPristine Macros 18

For Project Explorer window, go to View>Project Explorer or use shortcut Ctrl+R.

For Properties Window, go to View>Properties window or use shortcut F4.

Go to Project explorer under the View tab for open the Project Explorer Window or use Ctrl+R 

shortcut.

Go to Properties window under the View tab for open the Project  Properties Window or use F4 

shortcut.

12

A Tour of the VB Editor Screen

© EduPristine Macros 19

The Side panel is moving to any other place by simply drag it from original place and drop it down to new place.

Move the panel from left side to right side

Moving the VB Editor Windows

© EduPristine Macros 20

There are different ways to create a module. One is right click on any where inside the Project window>Go to Insert>Module.

The Module is inserted under the Module Folder.

Right click on Modules

1

Go to Insert 2

Select Module

3 A new Module is added under Modules Folder 

4

Creating Modules

© EduPristine Macros 21

The Second way is go to insert in the menu bar and click on the Module.

The Another way is  Go to Insert Tab

1

Select Module

2

A new Module is added under Modules Folder 

4

Creating Modules

© EduPristine Macros 22

For deleting the Module, Right click on Module and click on Remove Module. Click on ‘NO’. The module is deleted.

Right click on Module3

1

Select “Remove Module3”

2

Module3 is deleted

4

Click “NO”

3

Removing Modules

© EduPristine Macros 23

To rename the modules, first select the modules then go to Properties Window and rename it.

The name of modules follow some rules that you can’t use spaces between the name of the modules. You can use the underscore character in place of space.

Select the Module which you want to rename. Go to  Properties 

window, and rename it

1

2

Name of the module is changed

Space between the name is not allowed

1

2

Error showing that module name is not 

legal

Renaming Modules

© EduPristine Macros 24

For editing the setting of VB Editor Fonts, Go to Tools Tab in menu bar and then click on Options.

For editing the setting, Go to Tools menu

1

Select Options

2

Go to Editor Format tab. Now you can change the setting of VB Editor.  

2

Setting Up the VB Editor Fonts

© EduPristine Macros25

Macro security can be changed by “Macro Security” option under the developer menu tab or  “Options” 

under the File Menu. 

Macros are dangerous snippets of code and can be built with malicious intent

Macros need to be enabled for the application to run properly

Setting the Right Macro Security Levels

© EduPristine Macros26

Go to Trust Center

Select Trust Center Settings

1

22

1

Changing Macro Security Levels

© EduPristine Macros27

Select the Macro Settings

After Changing the setting, Click 

OK

1

2

Changing Macro Security Levels

© EduPristine Macros 28

File Name

Save your file as Excel Macro‐Enabled Workbook format

1

2

Saving Workbook Containing Code

© EduPristine Macros

Agenda

29

Introduction to Macros & Advanced Application Building in Excel• Introduction and context

Key Concepts in Macros Macros as recorded Robots! Designing application to gather user data

• Implementing user forms in Excel Macros• Linking forms to excel cells• Building flexible Charts in Excel

Understanding VBA• Understanding the relevant language constructs• Example: Write your First Macro

Debugging VBA code• Errors in VBA• Step into VBA

Writing more VBA Codes• Random Number Generator: Use of Loop, Excel Functions• Message Box, Input Box

Advanced Financial Applications• Breaking circular loops• Monte Carlo Simulation

© EduPristine Macros

Training the Robot – Recording a Macro

Name the macro Shortcut key ‐ fill in a letter in the available space

• Allows you to run the macro by holding down the CTRL key and pressing the chosen letter on the keyboard

Description • Description of the macro

Remember to Stop the recording!

30

© EduPristine Macros

Using the Robot – Using Macros

Use the Run Macro or shortcut key assigned to run the macro

Use Par_01_CopyMe‐MacroRecording

31

© EduPristine Macros

Your first Recorded Macro

32

1

2

3

4

5

6

© EduPristine Macros

So what’s inside the Macro?

Use Alt + F11 to see what Excel writes inside

33

© EduPristine Macros

If we had used relative references?

Relative Referencing works like cell referencing without “$”

34

1

2

34

5

© EduPristine Macros

So what’s in the code now?

Internally uses the offset function

35

© EduPristine Macros

Simple Example ‐ Automatically format charts in Excel

Unformatted “default” chart in Excel• Format it once and record for further use Use Par_02_Chart‐Recording‐Macro

36

© EduPristine Macros

Create a New Macro – Format Chart

Create a new macro• Record the steps performed to update the chart as per the standards required

37

© EduPristine Macros

Record all steps in the macro

Record all steps performed to change the formatting and stop the recording

38

1 2

3

© EduPristine Macros

Select the new chart to be formatted and run

Select the new chart that has to be formatted• Run the macro

39

© EduPristine Macros

The macro would automatically make the formatting consistent

With a single keystroke you can format your charts• For example B, CTRL + q is the key

40

© EduPristine Macros

Automatically generated Macros are not very robust

Even small changes in the expected step would cause the macro to throw errors• Need to understand the code• Slight modifications in the code can make the macros 

much more robust

41

© EduPristine Macros

Agenda

42

Introduction to Macros & Advanced Application Building in Excel• Introduction and context

Key Concepts in Macros Macros as recorded Robots! Designing application to gather user data

• Implementing user forms in Excel Macros• Linking forms to excel cells• Building flexible Charts in Excel

Understanding VBA• Understanding the relevant language constructs• Example: Write your First Macro

Debugging VBA code• Errors in VBA• Step into VBA

Writing more VBA Codes• Random Number Generator: Use of Loop, Excel Functions• Message Box, Input Box

Advanced Financial Applications• Breaking circular loops• Monte Carlo Simulation

© EduPristine Macros

Form Controls and Active X controls

ActiveX Controls Form ControlsToolbar Control Toolbox Forms

Macro code storage In the code module for the Sheet In any standard VBA module

Macro nameCorresponds to the control name (e.g., CommandButton1_Click)

Any name you specify.

Correspond to... UserForm controls Dialog Sheet controls

Customization Extensive, using the Properties box Minimal

Respond to events Yes Click or Change events only

Inserting Design Mode Normal

Assigning Macros No Arbitrary Macro Can be assigned Macros can be assigned

43

© EduPristine Macros

Creating a Model for CAPM

To Select: Right Click!

Using Form Controls

Limitation: A +ve #

To Covert to %age

To Link to a cell

Use Par_03_CAPM‐GUI

44

1 2

3

45

6

© EduPristine Macros

Playing with the changes

A Linear Transformation to generate desired output

Different Controls can be used for different user inputs

Link to the cell

Custom Format

45

© EduPristine Macros

Formatting the Scroll Bars

Select all scroll bars by click and ctrl key

46

© EduPristine Macros

Linking the Model

Based on the User Inputs, Generate the return Expectation

47

© EduPristine Macros

Creating Flexible Charts

Create the Chart Based on the Data

Use Par_04_FlexiChart

48

© EduPristine Macros

Create Decision controls and link to cells

49

1

2

3

4

© EduPristine Macros

Linking Data to decision 

If the appropriate series is selected, show the ratio, else hide

Change linkage to new block

50

© EduPristine Macros

Agenda

51

Introduction to Macros & Advanced Application Building in Excel• Introduction and context

Key Concepts in Macros Macros as recorded Robots! Designing application to gather user data

• Implementing user forms in Excel Macros• Linking forms to excel cells• Building flexible Charts in Excel

Understanding VBA• Understanding the relevant language constructs• Example: Write your First Macro

Debugging VBA code• Errors in VBA• Step into VBA

Writing more VBA Codes• Random Number Generator: Use of Loop, Excel Functions• Message Box, Input Box

Advanced Financial Applications• Breaking circular loops• Monte Carlo Simulation

© EduPristine Macros

Basics of VBA – Introduction to Sub and Function 

VBA procedure • Set of instructions given to the “Robot” to execute• Perform tasks such as calculating equations, analyzing 

data, communicating with excel/ databases, etc.• Block structured as a Sub or Function

Constructed from statements• Declaration (Robot’s memory)• Assignment statements (What is put in that memory)• Execution (What actions to perform)

Procedures are typed and stored in a Module/ worksheet Functions/ Sub are run line by line from beginning to end VBA has two types of procedures

• Sub (A subroutine, which performs a small task for you!)• Function procedures (It performs some tasks and returns 

a value to you)

52

© EduPristine Macros

Basics of VBA – Introduction to Variables

Variables are like buckets• Hold content for you• The contents of the variables can change• Actually variables are areas allocated by the

computer memory to hold data• Each variable has a Name Type

In VBA to Declare a new variable (Dim is the keyword)• Dim myPassword As String• Dim firstNum As Integer• Dim aLargeNumber As Double

Variables can be used to store data• myPassword = “whatever”• firstNum = 10• etc

53

© EduPristine Macros 54

Write a macro which will add a new worksheet, then it will populate the content as shown in below figure:

Use Par_05_MyFirstMacro

Example: Write your First Macro

© EduPristine Macros 55

Right click on Modules

Go to Insert

1

2

Select Module

3

A new Module is added under Modules Folder 

4

Creating a new Module 

© EduPristine Macros 56

Neat Code

Laying Out Your Code Neatly 

© EduPristine Macros 57

Beginning a new subroutine

Comments

Basic syntax of VBA instructions

Assigning a value to a cell

Text as inputUsing Functions to calculate values

Selecting a cell

Changing Font Color

Changing Background color, to select a color: write rgb and press Ctrl + Spacebar, it will give you many options to choose

Code for the example

© EduPristine Macros 58

Run the Code

Running Code from the VB Editor

© EduPristine Macros 59

Data in Excel Sheet after running the code

Running Code from the VB Editor

© EduPristine Macros 60

Go to Macros under the 

developer tab

1

Run the Macro

Running Code from the VB Editor

2

© EduPristine Macros 61

After running the code, a new sheet is created containing the data.

Running Code from the VB Editor

© EduPristine Macros

Agenda

62

Introduction to Macros & Advanced Application Building in Excel• Introduction and context

Key Concepts in Macros Macros as recorded Robots! Designing application to gather user data

• Implementing user forms in Excel Macros• Linking forms to excel cells• Building flexible Charts in Excel

Understanding VBA• Understanding the relevant language constructs• Example: Write your First Macro

Debugging VBA code• Errors in VBA• Step into VBA

Writing more VBA Codes• Random Number Generator: Use of Loop, Excel Functions• Message Box, Input Box

Advanced Financial Applications• Breaking circular loops• Monte Carlo Simulation

© EduPristine Macros 63

If there is any mistake in the syntax , then a dialog box is pop up showing that there is error in code

It show the place where error occur

Red color show that there is some error in 

this line

The dialog box show that what type of error occur

12

3

Syntax Errors

© EduPristine Macros 64

The error is removed  by using 

the “)”

Syntax Errors

© EduPristine Macros 65

Whenever we have any syntax error, a dialog box is Pop Up to show that there is error in line.

Turning Off Syntax Error Messages

© EduPristine Macros 66

To turn off the syntax error message, Go to Tool in menu bar

1

Select Options

2

Uncheck The Auto syntax Check.

3

Click OK

4

Turning Off Syntax Error Messages

© EduPristine Macros 67

Now if you have any syntax error in line, then dialog box will not Pop Up. Only the Color of the line will change to red to show that there is error in line.

Turning Off Syntax Error Messages

© EduPristine Macros 68

But it doesn’t show error

In this line word “Range” is not spell correctly

Run the Code

1

3

2

Compile Errors

© EduPristine Macros 69

Error Message showing that there is error in code

1

It show that this word have error 

The dialog box show that the function is not defined 

2

3

Compile Errors

© EduPristine Macros 70

When we click on OK and fix the code, you will notice that first line of subroutine is highlighted in yellow indicated that the subroutine is in break mode.

Compile Errors

© EduPristine Macros 71

The best policy to run the subroutine again is to reset it. 

Go to Run

Select Reset

1

2

Compile Errors

© EduPristine Macros 72

Lets assume that we spell “Date” and “rgbPaleTurquoise” incorrectly. Then What happened?

Spell Incorrectly

Compile the code

Compile Errors

© EduPristine Macros 73

It doesn’t show any error message at the time of compile. And also run the code without showing error.

Compile Errors

© EduPristine Macros 74

The Background color change to black

Date is not shown

Output of the Code

12

Compile Errors

© EduPristine Macros 75

Option explicit is designed for working with variables

Option Explicit

© EduPristine Macros 76

Compile it again

Compile Errors

© EduPristine Macros 77

Show the error in “Date”

Show the error in “color”

Compile Errors

© EduPristine Macros 78

For adding Option Explicit automatically, select Tools

2

Select Options

1

Check the “Require Variable Declaration” box

3

Click Ok

4

Compile Errors

© EduPristine Macros 79

Now whenever you create a new module, the Option Explicit is added automatically as first line of your subroutine.

Compile Errors

© EduPristine Macros 80

Change the Range from B1 to ZZZ1

1

Compile the code. It doesn’t show error 

message.

2

Runtime Errors

© EduPristine Macros 81

But at runtime, error message is shown

Click on Debug

The highlighted show that this  line contain error

Runtime Errors

© EduPristine Macros 82

Output show that code is running just before the 

error

The cell B1, B2, B3 is empty. Because the code  could not run due to 

error

12

Runtime Errors

© EduPristine Macros 83

Go to Debug

Select Step Into

This will execute the code step by step

1

2

Stepping Through a Subroutine

© EduPristine Macros 84

This highlighting show that this line is not 

executed yet

Now press F8 to execute the code 

step by step

Stepping Through a Subroutine

© EduPristine Macros 85

Breakpoint

We can set it at any line by pressing F9. 

Setting Breakpoints

© EduPristine Macros 86

The code is executed till that 

point

The rest of the lines will executed by pressing F8 key

Setting Breakpoints

© EduPristine Macros

Agenda

87

Introduction to Macros & Advanced Application Building in Excel• Introduction and context

Key Concepts in Macros Macros as recorded Robots! Designing application to gather user data

• Implementing user forms in Excel Macros• Linking forms to excel cells• Building flexible Charts in Excel

Understanding VBA• Understanding the relevant language constructs• Example: Write your First Macro

Debugging VBA code• Errors in VBA• Step into VBA

Writing more VBA Codes• Random Number Generator: Use of Loop, Excel Functions• Message Box, Input Box

Advanced Financial Applications• Breaking circular loops• Monte Carlo Simulation

© EduPristine Macros

For repetitive work, VBA has looping functions

• Much more powerful than direct formulas

• For‐Next loop

Use Par_06_Function‐Randbetween

88

Random Number Generator – Looping functions in VBA 

© EduPristine Macros

Syntax

• Application.worksheetfunction.Whatever function

89

Calling Excel Functions in VBA 

© EduPristine Macros 90

Message Box 

© EduPristine Macros 91

Message Box – Result

1 2 3

456

7

© EduPristine Macros 92

Message Box – Storing the value of the Message Box 

© EduPristine Macros 93

If Yes

If No

Message Box – Storing the value of the Message Box – Result 

© EduPristine Macros 94

Input Box

© EduPristine Macros

Agenda

95

Introduction to Macros & Advanced Application Building in Excel• Introduction and context

Key Concepts in Macros Macros as recorded Robots! Designing application to gather user data

• Implementing user forms in Excel Macros• Linking forms to excel cells• Building flexible Charts in Excel

Understanding VBA• Understanding the relevant language constructs• Example: Write your First Macro

Debugging VBA code• Errors in VBA• Step into VBA

Writing more VBA Codes• Random Number Generator: Use of Loop, Excel Functions• Message Box, Input Box

Advanced Financial Applications• Breaking circular loops• Monte Carlo Simulation

© EduPristine Macros

IDC: Breaking Circular Loops

Because of circular dependencies, the sheet can enter into 

inconsistent state

Use Par_08_IDC

96

© EduPristine Macros

The Copy & Paste Special has to be repeated again and again. This can be 

achieved by Recording

97

IDC: Basic Algorithm

© EduPristine Macros

IDC: Recording the Macro

Has to be done “Intelligently” to be used later

98

© EduPristine Macros

IDC: Macro by Recording

The Macro is able to copy and paste special the values once

99

© EduPristine Macros

IDC: Editing (with for loop) for the desired results

For Loop to run it multiple times

100

© EduPristine Macros

IDC: Writing the code instead of Recording with Name Ranges

101

Name Ranges

© EduPristine Macros

Monte Carlo Simulation (MCS)

There is a fair amount of uncertainty and risk involved with estimating the future value of figures or amounts due to the wide variety of potential outcomes. • Monte Carlo simulation (MCS) is one technique that helps to reduce the uncertainty involved in estimating 

future outcomes.  MCS can be applied to complex, non‐linear models or used to evaluate the accuracy and performance of 

other models. • risk management, • portfolio management, • pricing derivatives, • strategic planning, • project planning, • cost modeling and other fields. 

Technique that converts uncertainties in input variables of a model into probability distributionsCombining the distributions and randomly selecting values from them, it recalculates the simulated model many 

times and brings out the probability of the output. 

102

© EduPristine Macros

MCS: Frequently Used Distributions for MC

Normal/Gaussian Distribution • where the mean and the standard deviation are given and the mean represents the most probable value of the 

variable. It is symmetrical around the mean and is not bounded Lognormal Distribution 

• Appropriate for a variable ranging from zero to infinity, with positive skewness and with normally distributed natural logarithm

Triangular Distribution • With fixed minimum and maximum values. It is bounded by the minimum and maximum values and can be 

either symmetrical (the most probable value = mean = median) or asymmetrical.  Uniform Distribution 

• Contrast to the triangular distribution, the likelihood of occurrence of the values between the minimum and maximum is the same. 

Exponential Distribution • Used to illustrate the time between independent occurrences, provided the rate of occurrences is known. 

103

© EduPristine Macros

MCS: Probabilistic Growth in Price and Volume 

Assumptions• Initial Price and Volume of Material Sold• Mean Growth and the Std Deviations

Generating the Probability Distribution of Price and Volume Growth• Rand() Generates Uniform Random• Normsinv() to generate in normal form

Use the probabilistic price and volume to project the revenues

Use Par_09_MCS

104

© EduPristine Macros

MCS: Implementing Monte Carlo Simulation

The process of projecting revenues is to be repeated “n” number of times. This can be achieved with the help of a Macro.

1. Variable Declaration 2. Emptying the Vars & Cells

3. For Loop to run the simulation ‘n’ times 4. Calculating Average

105

© EduPristine Macros

MCS: Interpreting the Output

The Progress Bar Implemented with “Rept()” formula

106

© EduPristine Macros

Thank you!

© EduPristine – www.edupristine.com/ca

top related