Financial Modeling Using Excel And VBA - WordPress

Transcription

ffirs.qxd1/5/0412:57 PMPage iiiFinancial ModelingUsing Excel and VBACHANDAN SENGUPTAJohn Wiley & Sons, Inc.

ffirs.qxd1/5/0412:57 PMPage vi

ffirs.qxd1/5/0412:57 PMPage iFinancial ModelingUsing Excel and VBA

ffirs.qxd1/5/0412:57 PMPage iiFounded in 1807, John Wiley & Sons is the oldest independent publishing company inthe United States. With offices in North America, Europe, Australia, and Asia, Wiley is globally committed to developing and marketing print and electronic products and services forour customers’ professional and personal knowledge and understanding.The Wiley Trading series features books by traders who have survived the market’s everchanging temperament and have prospered—some by reinventing systems, others by gettingback to basics. Whether a novice trader, professional, or somewhere in-between, thesebooks will provide the advice and strategies needed to prosper today and well into thefuture.For a list of available titles, visit our Web site at www.WileyFinance.com.

ffirs.qxd1/5/0412:57 PMPage iiiFinancial ModelingUsing Excel and VBACHANDAN SENGUPTAJohn Wiley & Sons, Inc.

ffirs.qxd1/5/0412:57 PMPage ivCopyright 2004 by Chandan Sengupta. All rights reserved.Published by John Wiley & Sons, Inc., Hoboken, New Jersey.Published simultaneously in Canada.No part of this publication may be reproduced, stored in a retrieval system, or transmitted in anyform or by any means, electronic, mechanical, photocopying, recording, scanning, or otherwise,except as permitted under Section 107 or 108 of the 1976 United States Copyright Act, withouteither the prior written permission of the Publisher, or authorization through payment of the appropriate per-copy fee to the Copyright Clearance Center, Inc., 222 Rosewood Drive, Danvers, MA01923, 978-750-8400, fax 978-750-4470, or on the web at www.copyright.com. Requests to thePublisher for permission should be addressed to the Permissions Department, John Wiley & Sons,Inc., 111 River Street, Hoboken, NJ 07030, 201-748-6011, fax 201-748-6008, e-mail: permcoordinator@wiley.com.Limit of Liability/Disclaimer of Warranty: While the publisher and author have used their bestefforts 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 warrantiesof merchantability or fitness for a particular purpose. No warranty may be created or extended bysales representatives or written sales materials. The advice and strategies contained herein may notbe suitable for your situation. You should consult with a professional where appropriate. Neitherthe publisher nor author shall be liable for any loss of profit or any other commercial damages,including but not limited to special, incidental, consequential, or other damages.For general information on our other products and services, or technical support, please contactour Customer Care Department within the United States at 800-762-2974, outside the UnitedStates at 317-572-3993 or fax 317-572-4002.Wiley also publishes its books in a variety of electronic formats. Some content that appears in printmay not be available in electronic books.For more information about Wiley products, visit our web site at www.wiley.com.ISBN 0-471-26768-6Printed in the United States of America.10 9 8 7 6 5 4 3 2 1

ffirs.qxd1/5/0412:57 PMPage vFor Preety

ffirs.qxd1/5/0412:57 PMPage vi

ftoc.qxd1/5/041:00 PMPage viiContentsAbout This BookxiCHAPTER 1 Introduction to Financial Modeling1Part One: Excel for Financial ModelingCHAPTER 2 Excel Basics13Improving Your Excel SkillsThe Basic Excel Features1420CHAPTER 3 Advanced Excel Features29CHAPTER 4 Excel’s Built-In Functions and Analysis ToolsFinancial FunctionsLogical FunctionsStatistical FunctionsMathematical and Trigonometric FunctionsLookup and Reference FunctionsDate and Time FunctionsText FunctionsInformation FunctionsThe Analysis ToolPak7173868697101107110112113Part Two: Financial Modeling Using ExcelCHAPTER 5 How to Build Good Excel Models119Attributes of Good Excel ModelsDocumenting Excel ModelsDebugging Excel ModelsUsing Formula Auditing Tools for DebuggingLearning Modeling Using Excel119122124127128vii

ftoc.qxd1/5/041:00 PMPage viiiviiiCONTENTSCHAPTER 6 Financial Statements Forecasting131Review of Theory and ConceptsModeling Examples131141CHAPTER 7 Time Value of Money185Review of Theory and ConceptsModeling Examples185199CHAPTER 8 Financial Planning and Investments223Review of Theory and ConceptsModeling Examples223230CHAPTER 9 Analyzing Market History247Review of Theory and ConceptsModeling Examples247252CHAPTER 10 Bond Pricing and Duration267Review of Theory and ConceptsModeling Examples267274CHAPTER 11 Simulating Stock Prices285Review of Theory and ConceptsModeling Examples285295CHAPTER 12 Options and Option Portfolios307Review of Theory and ConceptsModeling Examples307317CHAPTER 13 Binomial Option Pricing345Review of Theory and ConceptsModeling Examples345349Part Three: VBA for Financial ModelingCHAPTER 14 Introduction to VBA363Example of a VBA ModelRecording MacrosUsing VBA’s HelpThe Strategy to Learn VBA Efficiently368378382384CHAPTER 15 VBA Essentials385The Visual Basic EditorSome BasicsVariables, Constants, and ArraysObjects, Properties, and Methods386390401413

ftoc.qxd1/5/041:00 PMPage ixixContentsBranchingLoopingUsing Built-In Functions417423430CHAPTER 16 Sub and Function Procedures433Sub ProceduresFunctions Procedures433438CHAPTER 17 Debugging VBA Models445Part Four: Financial Modeling Using VBACHAPTER 18 How to Build Good VBA Models453Attributes of Good VBA ModelsDocumenting VBA ModelsLearning Modeling Using VBA453457459CHAPTER 19 Time Value of Money463Review of Theory and ConceptsModeling Examples463467CHAPTER 20 Financial Planning and Investments519Modeling Examples519CHAPTER 21 Analyzing Market History549Modeling Examples549CHAPTER 22 Simulating Stock Prices575Modeling Examples575CHAPTER 23 Options and Option Portfolios583Modeling Examples583CHAPTER 24 Binomial Option Pricing599Modeling Examples599Appendix A Keyboard Shortcuts for Excel613Appendix B VBA Quick Reference615Appendix C Excel and VBA Built-In Functions617Index635About the CD-ROM655

ftoc.qxd1/5/041:00 PMPage x

flast.qxd 1/8/04 11:49 AM Page xiAbout This BookHow do you get to Carnegie Hall? You practice, practice, practice.The same is true of financial modeling. The only way you can learn todevelop good financial models is by practicing a lot. Fortunately if you learn andpractice modeling the right way, you will not have to practice even one-tenth ashard as a performer does to get to Carnegie Hall.The primary objectives of this book are to show you how to learn and practice financial modeling the right way and to provide you with a wide range ofreal-world financial models—over 75 of them—to imitate and use for practice sothat you can be on your way to financial modeling’s Carnegie Hall. Financialmodeling is an essential skill for finance professionals and students, and Exceland its built-in programming language, Visual Basic for Applications (VBA), arethe preferred tools for the job. However, modeling using Excel and VBA is rarelypresented as an integrated subject in books or classrooms. The result is that bothpractitioners and students follow time-consuming trial and error approaches tomodeling and end up with models that are not sufficiently flexible and powerful.This book, designed for self-study, classroom use, and reference, presents acomprehensive approach for developing simple to sophisticated financial modelsin all major areas of finance using both Excel and VBA. The approach is basedon my long experience in the business world developing a wide variety of financial models and in the classroom teaching an MBA course in financial modelingthat students find very useful not just in their other course work but in their subsequent professional careers as well.Developing good financial models requires combining knowledge of finance,mathematics, and Excel and VBA using modeling skill. In each of these areas, the following is what I assume you already know and what you will learn from this book.In finance and mathematics, I assume that you have the necessary basicknowledge. Nonetheless, in each chapter I have included a review of the theoryand concepts you will find useful for working on the models within that chapter.Because I cover a wide range of topics in the book, I think some of this materialwill be new to you. By immediately applying the newly acquired knowledge toxi

flast.qxd 1/8/04 11:49 AM Page xiixiiABOUT THIS BOOK“real world” problems, you will expand your knowledge of finance in some areasin which you may have been interested for some time.In Excel, I assume you know the basics, and I cover the advanced features ofExcel that you need for modeling in detail. You may be amazed to find out howmuch those whiz kids from Redmond have squeezed into Excel that many of usdo not even know about.VBA will be one of the most important things you learn from this book. Iassume that you know nothing about it. VBA is a powerful and very useful toolthat people who have Excel already have sitting inside their computers. Unfortunately, very few people use it because they are afraid of learning “programming.”I will teach you VBA and modeling with VBA using a simple class-testedapproach. The key is to learn VBA as a language the same way you learned yourmother tongue—by imitating how to say things you want to say, without worrying about learning all the rules of grammar or trying to acquire a large vocabulary that you do not need. You will be surprised to find out how little you haveto learn to be able to develop models with VBA that are often more useful, powerful, and flexible than Excel models.Finally, I assume that you are new to modeling. Even if you have some experience, you will quickly find yourself challenged as you build on your skills. Youwill learn by imitating and practicing on numerous models from all areas offinance, and you will be able to challenge yourself further by developing extensions to these models.I have not tried to cover every type of financial model that you may need todevelop over the years, nor have I tried to cover modeling in depth for one or twoparticular areas of finance (such as derivatives). The reality—and my assumption—is that once you develop your financial modeling skill and learn to useExcel and VBA well, you will be able to develop models for any problem as longas you know the financial theory and mathematics needed to solve it conceptually. I have therefore focused on helping you develop the skill of financial modeling, and the best way to develop that skill is to work on a broad range ofmodels instead of narrowly focusing on any one area of finance.The CD that accompanies this book includes complete working versions ofall the models in the book. In the text I provide the modeling strategy for eachproblem, detailed instructions on how to build each model, and thorough analysis of all the VBA codes for the models. I also explain how you can cover thematerial following different learning tracks depending on your background, howmuch time you have, and how good you want to become in financial modeling.The book and the CD also include several special tools (for example, a VBAQuick Reference and a selected list of the most useful Excel and VBA built-infunctions) that you can personalize, add to over time, and keep easily accessibleon your computer’s hard disk.Financial modeling is finance in action. It is challenging and it is a lot of fun.I hope this book will show you how to have fun with it and benefit from it at thesame time.

flast.qxd 1/8/04 11:49 AM Page xiiiFinancial ModelingUsing Excel and VBA

flast.qxd 1/8/04 11:49 AM Page xiv

01 chap sengupta.qxd 12/31/03 12:07 PM Page 1CHAPTER1Introduction to Financial Modelinghat is a financial model? What is the difference between a financial modeland the spreadsheet solutions you create or VBA programs you write all thetime to answer financial questions or solve financial problems?A simple, practical answer is that a financial model is designed to representin mathematical terms the relationships among the variables of a financial problem so that it can be used to answer “what if” questions or make projections.Some of the spreadsheet solutions that people create capture some of these relationships as well and, therefore, can answer “what if” questions to some extent.But because they are not primarily designed with these objectives in mind, theydo not try to capture as many of these interdependencies as possible, and theirstructures often make it cumbersome to answer “what if” questions or make projections with them.This may sound a little abstract. So let us look at a simple, concrete example. Suppose you are using a spreadsheet to calculate, based on your taxableincome, what your after-tax income was last year. Income tax rates vary in steps(brackets) for different income levels. So you cannot simply calculate your taxesby multiplying your taxable income by one tax rate (30%, for example) and subtracting it from your taxable income to get the after-tax income.Consider two approaches to setting up a spreadsheet to calculate the aftertax income. In the first approach, you can enter your taxable income in a cell,calculate the tax on the income (using a hand calculator and the tax rates for thedifferent tax brackets), and enter it in the cell below. Then you can write an equation in another cell to calculate your after-tax income by subtracting the tax inthe second cell from the taxable income in the first cell.This spreadsheet solution will give you the answer to your immediate question, but it is not a useful financial model. Why? Because it does not capture thekey mathematical relationship between taxable income and taxes. The result isthat if you now try to answer the “what if” question, What would my after-taxincome have been if my taxable income were 10,000 higher?, you will have togo back to doing the calculations by hand.W1

01 chap sengupta.qxd 12/31/03 12:07 PM Page 22INTRODUCTION TO FINANCIAL MODELINGHowever, you can set up your spreadsheet to calculate the taxes on any taxableincome (using the different tax brackets and tax rates) and use the computed taxnumber to calculate your after-tax income. You will then have a financial model,because it will capture the relationship between taxable income and taxes. You alsowill be able to use this model to answer the “what if” question I posed before.In creating financial models, you always have to keep in mind that you wantto capture as many of the interdependencies among the variables of the model aspossible. In addition, you want to structure your models in such a way that it iseasy to ask “what if” questions, that is, change the values of the independentvariables and observe how they affect the values of the key dependent variables.You also should recognize that some of the relationships, as in the case of taxes,are easy to establish and exact; but many others will be approximate or evenunknown. You will have to come up with them based on financial theory, analysis of data, and so on, and coming up with these relationships is one of themajor challenges of financial modeling. Generally, the more of these relationshipsyou can come up with and incorporate into your model, the more useful yourmodel will be.My Assumptions about You and the Users of Your ModelsIn this book I assume that you know the basics of finance and can solve by handmost of the problems for which you will be creating models. I also assume thatyou are familiar with the basics of Excel and have experience creating spreadsheet solutions to at least simple problems. You do not need to have knowledgeof Excel’s advanced features or of modeling; I will cover both in detail. You alsodo not need to have any knowledge of VBA. A key objective of the book is toteach you VBA and modeling using VBA from scratch by way of an easy andeffective method.Another important assumption I am making is that you will be developingthe models primarily for your own use or for use by people who have some experience with Excel, but not necessarily with VBA. When you create models for useby people who have little or no familiarity with Excel, it requires adding specialuser interfaces to make the models easy to use. One must build into them special features to make them “bulletproof”—that is, to make sure that the modelswill not crash or produce wrong results if someone enters inappropriate inputs.I will discuss some design methods and Excel features that make models easier touse and more “bullet-resistant.” Most everyday modelers do not need to gobeyond this.Excel and VBA as Modeling ToolsEven in the mid- to late 1990s, Excel was not considered a powerful enough toolfor serious financial modeling, in part because the PCs available at the time had

01 chap sengupta.qxd 12/31/03 12:07 PM Page 3Introduction to Financial Modeling3speed and memory limitations. With advances in PCs and improvements in Excelitself, the table has now turned completely: Excel has become the preferred toolfor creating all but the largest and most computationally intensive financial models. The advantages of Excel for financial modeling are so obvious that it is notnecessary to go into them. However, for those who have not worked with otherprograms or programming languages for modeling, it is worthwhile to point outthat one of the important advantages of Excel is that with Excel you can createexcellent output with very little work. You should learn to take full advantage ofExcel’s power in this respect.If Excel is so good, then, why bother with VBA? VBA is a programming language, and if you do not know anything about programming languages, it will bedifficult for you to appreciate the advantages of VBA at this point. Let me touchon only a few key reasons here, and I will answer the question in greater detailwhen we discuss modeling with VBA.Despite its power, Excel has many limitations, and there are many financialmodels—some even relatively simple ones—that either cannot be created in Excelor will be overly complex or cumbersome to create in Excel. What’s more, whenyou create a highly complex model in Excel, it can be difficult to understand,debug, and maintain. VBA generally offers a significant edge in all these respects.The problem that most people have with VBA is that it is one more thing tolearn, and they are somehow afraid of trying to learn a programming language.The reality is that if you follow the right method, learning a programming language is not particularly difficult—especially if you selectively learn what you willreally use (as we will do in this book) and not let yourself get lost in all the otherthings you can do with VBA but probably never will. The truth is that you do notneed to learn all that much to be able to create very useful and powerful financial models with VBA. What you will need is a lot of practice, which you will getas you go through this book. VBA offers you the best of both worlds: you cantake advantage of all the powers of Excel including its ability to easily create excellent outputs, and supplement them with VBA’s additional tools and flexibility.Independent and Dependent VariablesWe can say that the purpose of a model is to calculate the values of certaindependent variables for the values provided for its independent variables. It istherefore important to understand the difference between independent and dependent variables.Independent variables are also called the input or external variables. Themodel’s user or creator inputs the values of these variables—they are not calculated by the model. These are the variables you change to ask “what if” questions.For example, in our simple model the taxable income is an independent variable.A model may also include a special type of input variable called a parameter.Parameters are independent variables in that their values are also provided by the

01 chap sengupta.qxd 12/31/03 12:07 PM Page 44INTRODUCTION TO FINANCIAL MODELINGcreator or user of the model. The difference is that their values are expected toremain constant or change infrequently within the context of the model. For example, the tax rates and the tax brackets in our simple model can be consideredparameters of the model because their values have to be provided for the modelto work, but these values are not expected to change frequently. As you create amodel, it is useful to keep the parameters together but separate from the otherindependent variables. They should still be easy to see and change, however.The variables whose values are calculated by the model are called the calculated or dependent variables. Some of them may be intermediate variables, calculated for use in other calculations. Others are of primary interest to the userand are the output variables of the models. Models are almost always created toobserve how the values of the output variables will change with changes in thevalues of one or more independent variables. Dependent variables are the oneswhose values we want to project or determine when we ask “what if” questions.It is possible to distinguish between intermediate dependent variables andoutput dependent variables; intermediate dependent variables are used in furthercalculations, whereas output dependent variables are not. This is generally not auseful distinction, however. It is better to look at the dependent variables of primary interest as the output variables of the model irrespective of whether they areused in further calculations. One must also recognize that, from time to time,some dependent variables that were previously not considered output variablesof a model can become so and vice versa.STEPS IN CREATING A MODELWhether you are creating a financial model using Excel or VBA, you must take asystematic approach. A systematic approach always involves planning ahead andthis takes some time. Most people do not like to plan and think they can savetime by starting to build a model right away without spending time on planning.However, for all but the simplest models, not taking the time upfront to do someplanning and not taking a systematic approach ends up being both frustratingand a waste of time.Here are the key steps you should follow in creating both Excel and VBAmodels. The details vary somewhat depending on whether you are working withExcel or VBA, and I will discuss them in later chapters. You should keep twoother things in mind. First, in practice, you do not have to follow the steps strictlyin this order, nor do you have to finish one completely before going onto the nextone. Most of the time you will have to go back and forth to some extent. It willdepend on the circumstances. Second, over time, you should try to create yourown variation on this basic approach and learn to adapt it to different situations.Excel and VBA are flexible tools and you can usually make changes almostat any stage without a great deal of difficulty. But this still will take more time

01 chap sengupta.qxd 12/31/03 12:07 PM Page 5Introduction to Financial Modeling5than if you do it right the first time, and making changes later increases thechances of missing some of the other changes that have to go with them.Step 1: Define and Structure the ProblemIn real life, problems rarely come neatly defined and structured. Unless you takethe time upfront to define and structure the problem and agree on them with theuser (your boss, for example), you may end up having to extensively changethe model you first create. When your boss asks you a question whose answerrequires developing a model, she often has only a vague idea of what she is reallyseeking. As a finance person and a modeler, you are responsible for putting it allin more concrete terms before proceeding.Start by discussing and defining why the model is needed and what decisions,if any, will be made based on its output—that is, what questions the model is supposed to answer. Then establish how accurate or realistic the outputs need to be.As we discussed, all models have to capture the relationships among their variables, and discovering and quantifying these can take a lot of time. How mucheffort you put into doing this should depend on how important the project is andhow accurate or realistic the outputs need to be.Step 2: Define the Input and Output Variables of the ModelMake a list of all the inputs the model will need and decide who will providethem or where they will come from. This is crucial. For example, if you are creating a model to do the business plan for your company, the inputs must comefrom the business managers. You cannot just guess what sales growth rates theywill be able to achieve, how much they will have to spend on plants and equipment to support those sales growths, and so forth. You may not need the actualnumbers upfront, but the list of inputs should be established based on your discussions with the business managers so that you can make them independentvariables in your model. Otherwise you may have go back later on and change alot of things in the model.Make a list of the tabular, graphical, and other outputs the model needs tocreate. To some extent, these should be driven by the decisions that will be madebased on them. One advantage of Excel is that a lot of the output can be justprintouts of your spreadsheets, provided the spreadsheets have been laid outproperly. If you plan ahead and lay out your spreadsheets with the outputs inmind, you will save yourself a lot of time later on.Step 3: Decide Who Will Use the Model and How OftenWho will use the model and how often it will be used make a lot of difference.In this book, I am assuming that you are developing the models either for your

01 chap sengupta.qxd 12/31/03 12:07 PM Page 66INTRODUCTION TO FINANCIAL MODELINGown use or for use by others who are familiar with Excel and understand themodel, at least to some extent. When you create models for others’ use, itinvolves much more work. You have to make sure that these people cannot enterdata that do not make sense, they cannot accidentally damage parts of the model,and they can get the necessary outputs automatically and so forth. These arecollectively called the user interface, and the more elegant, more easy to use, andmore robust you want to make a model, the more work it is. You also have toplan for many of these features ahead of time.How frequently a model will be used is another important issue. If a modelis going to be used only once in a while, then it does not matter if it takes a longtime to run or if it takes some extra work every time to create the outputs. Amodel that will be used frequently, however, should be designed differently.Step 4: Understand the Financial and Mathematical Aspectsof the ModelIt is important to remember that the computer cannot do any thinking; you haveto tell it exactly how all the calculations in the model will have to be done. Inmost situations, if you do not know how you would do the calculations by hand,you are not going to be able to write the necessary formulas or instructions forthe computer to do it. It does not pay to start building the model until you aresure you could solve the problem by hand.It usually takes beginners a lot of time to create a model and they often thinkthat it is their Excel or VBA skills that are slowing things down. This may bepartly true, but at least as often the problem is in their understanding of thefinance and mathematics of the model they are trying to create. You will save lotof time if you do not even sit down in front of the computer to create a modeluntil you are sure that you know how to solve the problem.Step 5: Design the ModelThere are two aspects to designing a model. One is to sketch the steps that Excelor VBA will have to follow to solve the problem. For simple models, you maywant to write down only the broad steps or perhaps even do it in your head. Formore complex problems, however, you should work on paper and use a degreeof detail that suits your level of experience and the complexity of the problem.The less experience you have, the more detailed the sketch should be. Once again,remember that this may seem like a waste of time, but ultimately it will save youtime compared to plunging into your spreadsheet or VBA program without sucha sketch of the model.The other aspect of design is planning how the model will be laid out in Excelor VBA. Are you going to do the entire model in one spreadsheet (or VBA module) or split it into several spreadsheets (or VBA modules or procedures)? Editingan Excel or VBA model is easy. So you do not have to decide every detail ahead

01 chap sengupta.qxd 12/31/03 12:07 PM Page 7Introduction to Financial Modeling7of time, but you need to have an overall design in mind or on paper dependingon the complexity of the problem and your level of experience.As I discussed before, you also need to think about the kind of user interfaceyou want to create and the reports you want the model to produce.Step 6: Create the Spreadsheets or Write the VBA CodesFor most models, this is the big step. Most of this book covers the details of thisstep, so there is no need to get into them here.Step 7: Test the ModelAlmost no model works correctly the first time it is used; you have to find theproblems (bugs) and fix them. The bugs that prevent the model from working atall or produce obviously wrong answers are generally easier to find and fix. However, models often include hidden bugs that create problems only for certain values or certain combinations of values for the input variables. To find them, youhave to test a model extensively with a wide range of input variables.You have to take somewhat different approaches to testing and debugging amodel dependin

modeling is an essential skill for finance professionals and students, and Excel and its built-in programming language, Visual Basic for Applications (VBA), are the preferred tools for the job. However, modeling using Excel and VBA is rarely presented as an integrate