ebook img

Python Guide to Accompany Introductory Econometrics for Finance PDF

175 Pages·2019·10.502 MB·English
Save to my drive
Quick download
Download
Most books are stored in the elastic cloud where traffic is expensive. For this reason, we have a limit on daily download.

Preview Python Guide to Accompany Introductory Econometrics for Finance

Electronic copy available at: https://ssrn.com/abstract=3475303 © RanTaoandChrisBrooks2019 TheICMACentre,HenleyBusinessSchool,UniversityofReading Allrightsreserved. This guide draws on material from ‘Introductory Econometrics for Finance’, published by Cam- bridge University Press, © Chris Brooks (2019). The Guide is intended to be used alongside the book,andpagenumbersfromthebookaregivenaftereachsectionandsubsectionheading. The authors accept no responsibility for the persistence or accuracy of URLs for external or third- party internet websites referred to in this work, and nor do we guarantee that any content on such websitesis,orwillremain,accurateorappropriate. i Electronic copy available at: https://ssrn.com/abstract=3475303 Contents 1 Gettingstarted 1 1.1 WhatisPython? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1 1.2 DifferentwaystorunPythoncode . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2 1.3 WhatdoesaJupyterNoteBooklooklike? . . . . . . . . . . . . . . . . . . . . . . . . . . 5 1.4 Gettinghelp . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11 2 DatamanagementinPython 12 2.1 Variablesandnamerules . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12 2.2 Whitespace . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15 2.3 Comments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15 2.4 Mathematicaloperations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16 2.5 Twolibraries: PandasandNumPy . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17 2.6 Datainputandsaving . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17 2.7 Datadescriptionandcalculation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18 2.8 Anexample: calculatingsummarystatisticsforhouseprices . . . . . . . . . . . . . . . 20 2.9 Plots . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23 2.10 Savingdataandresults . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25 3 Simplelinearregression-estimationofanoptimalhedgeratio 27 4 Hypothesistesting-Example1: hedgingrevisited 31 5 Estimationandhypothesistesting-Example2: theCAPM 33 6 Sampleoutputformultiplehypothesistests 39 7 MultipleregressionusinganAPT-stylemodel 41 7.1 Stepwiseregression . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45 8 Quantileregression 49 9 Calculatingprincipalcomponents 57 10 Diagnostictesting 60 10.1 Testingforheteroscedasticity . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 60 10.2 UsingWhite’smodifiedstandarderrorestimates . . . . . . . . . . . . . . . . . . . . . . 62 10.3 TheNewey-Westprocedureforestimatingstandarderrors . . . . . . . . . . . . . . . . 64 10.4 Autocorrelationanddynamicmodels . . . . . . . . . . . . . . . . . . . . . . . . . . . . 66 10.5 Testingfornon-normality . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 67 10.6 Dummyvariableconstructionanduse . . . . . . . . . . . . . . . . . . . . . . . . . . . . 69 10.7 Multicollinearity . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 73 10.8 TheRESETtestforfunctionalform . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 74 10.9 Stabilitytests . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 75 11 ConstructingARMAmodels 80 12 ForecastingusingARMAmodels 85 13 Estimatingexponentialsmoothingmodels 89 ii Electronic copy available at: https://ssrn.com/abstract=3475303 14 Simultaneousequationsmodelling 91 15 TheGeneralisedmethodofmomentsforinstrumentalvariables 94 16 VARestimation 97 17 Testingforunitroots 106 18 Cointegrationtestsandmodellingcointegratedsystems 109 19 Volatilitymodelling 121 19.1 Testingfor’ARCHeffects’inexchangeratereturns . . . . . . . . . . . . . . . . . . . . . 121 19.2 EstimatingGARCHmodels . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 123 19.3 GJRandEGARCHmodels . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 125 19.4 ForecastingfromGARCHmodels . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 129 20 Modellingseasonalityinfinancialdata 132 20.1 Dummyvariablesforseasonality . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 132 20.2 EstimatingMarkovswitchingmodels . . . . . . . . . . . . . . . . . . . . . . . . . . . . 134 21 Paneldatamodels 137 22 Limiteddependentvariablemodels 142 23 Simulationmethods 150 23.1 DerivingcriticalvaluesforaDickey-Fullertestusingsimulation . . . . . . . . . . . . . 150 23.2 PricingAsianoptions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 154 23.3 VaRestimationusingbootstrapping . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 157 24 TheFama-MacBethprocedure 160 25 UsingextremevaluetheoryforVaRcalculation 164 iii Electronic copy available at: https://ssrn.com/abstract=3475303 List of Figures 1 OpeningthePythonConsole . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2 2 RunningCodefromtheConsole . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2 3 OpeningtheAnacondaNavigator . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3 4 OpeningaJupyterNoteBook . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4 5 TheInterfaceofaJupyterNoteBook . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5 6 RenamingJupyterNoteBook . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5 7 FileMenuOptions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6 8 EditMenuOptions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7 9 ViewMenuOptions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8 10 CellMenuOptions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8 11 KernelMenuOptions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9 12 HelpMenuOptions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9 13 TheCellEditandCommandMode . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11 14 LineplotoftheAverageHousePriceSeries . . . . . . . . . . . . . . . . . . . . . . . . . 24 15 HistogramoftheAverageHousePriceSeries . . . . . . . . . . . . . . . . . . . . . . . . 25 16 Time-SeriesPlotofTwoSeries . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35 17 ScatterPlotoftwoSeries . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36 18 LinearRegressionforDifferentQuantiles . . . . . . . . . . . . . . . . . . . . . . . . . . 56 19 PercentageofEigenvaluesAttributabletoEachComponent . . . . . . . . . . . . . . . 59 20 Time-seriesPlotofResiduals . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 61 21 HistogramofResiduals . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 68 22 RegressionResidualsandFittedSeries . . . . . . . . . . . . . . . . . . . . . . . . . . . . 70 23 PlotoftheParameterStabilityTest . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 79 24 GraphComparingtheStaticForecastswiththeActualSeries . . . . . . . . . . . . . . . 87 25 GraphComparingtheDynamicForecastswiththeActualSeries . . . . . . . . . . . . . 87 26 In-sample,Out-of-sampleandSimpleExponentialSmoothing . . . . . . . . . . . . . . 90 27 ImpulseResponses . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 102 28 VarianceDecompositions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 103 29 VarianceDecompositionsforDifferentOrderings . . . . . . . . . . . . . . . . . . . . . 105 30 Actual,FittedandResidualPlot . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 110 31 GraphoftheSixUSTreasuryInterestRatesSeries . . . . . . . . . . . . . . . . . . . . . 114 32 DynamicandStaticForecasts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 131 33 SmoothedStateProbabilities . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 136 34 GraphoftheFittedValuesfromtheFailureProbitRegression . . . . . . . . . . . . . . 147 35 HistogramandtheProbabilityDensityFunctionoftheStandardNormalDistribution 165 36 HillPlot . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 167 iv Electronic copy available at: https://ssrn.com/abstract=3475303 List of Tables 1 GrangerCausalityWaldtests . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 101 2 SimulatedAsianOptionPriceValues . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 156 v Electronic copy available at: https://ssrn.com/abstract=3475303 1 Getting started 1.1 What is Python? Python is an open-source, high-level and interpreted programming language for various purposes. Several libraries it provides have proved particularly useful for both financial industry practitioners and academic researchers, and therefore the programming language has become increasingly popu- lar. Python has several strengths: first, it is user-friendly for programming beginners. Learners do not need to spend too much time on its syntax because the language is simple and very concise, meaningthatthecodeishighlyefficientandmuchcanbeachievedinjustafewlinescomparedwith otherlanguages. Second,itprovidesextensivesupportlibraries,webservicetools,stringoperations, panel data analysis, etc. Most frequently used programming tasks have already been scripted and users can easily import them for their own purposes. Finally, it is free of charge and thus open to everyone. UserscaneasilystepintostatisticalanalysisbyimplementingcodeinPython. Mostrelevantforourpurposes,Pythoncanalsoimplementmanydifferentstatisticalandecono- metric tests. StatsModels is a powerful Python library to conduct many statistical tests, and in this guideitwillbeusedfrequently. NotethatthisguideisbasedonPythonversion3.6. However,therearesignificantdifferencesbe- tweenversion2.7andversions3.5andabove. IfyouusetheearlierversionofPython(2.7),thesyntax aswellascertainmodulesitprovidesaredifferent. Moreover,asPythonisanopen-sourceprogram- ming language and has many libraries or packages updated frequently, some functions might no longerbesupportedormayhavemovedtoothermodulesinfutureversions. This section assumes that readers have successfully set up an environment and downloaded the Pythonsoftwareontoanavailablecomputer. ThereareanumberofwaystoimplementPythoncode. NotethatthisbookimplementsallexamplecodeinJupyterNoteBookviaAnaconda.1 Alternatively, youcanchoosePyCharm,Spyderandetc. dependentonyourownpreferences. Spyder,forexample, is also a popular Python environment that is available through Anaconda, but it is not interactive, meaning that you write the code and then run it with the output appearing in a different window. Therearenodifferencesbetweentheseenvironmentsintermsofthesyntaxitself,however. Agood wayof familiarisingyourself withPython isto learnabout itssyntax andgo throughthe examples given in this guide. There now follows a presentation of the fundamentals of the Python package, together with instructions on how to achieve standard tasks and sample output. All ex- ample code is given, with different colours highlighting different parts of the code. A number of comments and explanations along with this code will hopefully make it easier to understand. Ad- ditionally, it is noteworthy that Python has a strict rule for naming variables. For example, variable names must start with a letter or underscore, any phrase variable must be integrated by an under- score instead of adding blank in between, and it is also CASE-SENSITIVE. Thus, it is important to entercommandsexactlyastheexampleshowsinordertoavoidunnecessaryerrors. Finally,itisworthmentioningthattheaimofthisbookistohelpfinancestudentsandresearchers who are new to Python to quickly master the basic syntax and knowledge to enable them to imple- ment various applications of econometric tests. Since the core of Python is not a specialist econo- metricprogramminglanguagelikeRorSTATA,somestatisticaloutputlooksverypreliminaryanda number of econometric tests are not yet developed or tested in Python. To cover as many examples from Introductory Econometrics for Finance as possible, we attempt to design some functions to com- pletethesetests. Undoubtedly,thereisstillconsiderableroomtoimprovethecodeandnodoubtthe outcomescouldhavebeenachievedindifferentways. 1Jupyterisanopen-source,web-based,interactivetoolforimplementingthePythonlanguage. Youcaneitherdown- loadJupyterdirectlyoraccessitbyinstallingtheAnacondaplatform. 1 Electronic copy available at: https://ssrn.com/abstract=3475303 1.2 Different ways to run Python code Unlike other statistic software, there are a number of ways to run Python code. The simplest way to write and execute Python code is via the Python console. Assuming that the reader has installed Python on a Windows-based computer, to open the console/terminal, we click on Start and type ’cmd’inthesearchengine. ThenhittingENTERleadstheWindowssystemtolaunchanewinterface (Figure 1). Next, we type ’Python’ and press ENTER, in which case the Python console opens. We cannowdirectlywriteandexecutecodehere. Figure1: OpeningthePythonConsole Alternatively,youcanwriteyourcodeinaneditorandexecuteitfromtheconsole. Forexample,we can first open a Notepad++ file and write the command line print("Hello World"), saving the file as name of program.py. Then we repeat the procedure as stated above. Click Start, search for ’cmd’ and press ENTER. You need to navigate the Python console to where you have saved the file (in thiscase,wehavesavedthefileontheDesktop). Writethefollowinglinetoexecutetheprogramme (Figure2). Figure2: RunningCodefromtheConsole However, it is usually more convenient to implement Python code using an IDE (Integrated Devel- opment Environment). In this book, we use ’Anaconda’, which will first need to be downloaded.2 Oncethesoftwareisonthecomputer,clickonStart,searchfor’Anaconda’andopentheprogramme ’Anaconda Navigator’. As you can see in Figure 3, Anaconda is a collection of software packages. There are several applications that can be launched such as the Jupyter NoteBook, Spyder, etc. For 2Anacondacanbedownloadedfromhttps://www.anaconda.com/download/ 2 Electronic copy available at: https://ssrn.com/abstract=3475303 the purpose of better presenting code in this book, we choose the Jupyter NoteBook because it is designedasanopen-sourceWeb-based,interactivecomputingapplication.3 Figure3: OpeningtheAnacondaNavigator We now step into how to use Jupyter NoteBook. To launch this application, click the Launch button below the icon (highlighted by a red circle). Anaconda then takes a few seconds to open a web page (Figure 4). You can see a number of folders on the main screen. Choose a folder as the directory for the Python code. For instance, we can click on the folder Desktop and then create a new script by clicking the button New. In the drop-down menu, click Python 3. Jupyter then creates a new web pagewherethecodecanbewrittenandexecuted. ThedetailofhowtouseJupyterwillbepresented inthenextsection. 3NotethatreadersneedtodownloadAnacondawithcautionsince,asstatedabove,therearetwodifferentversions. OneisforPython2.7,andtheotherisforPython3.x. WewillmainlyfocusonthePython3.xversion. 3 Electronic copy available at: https://ssrn.com/abstract=3475303 Figure4: OpeningaJupyterNoteBook 4 Electronic copy available at: https://ssrn.com/abstract=3475303

See more

The list of books you might like

Most books are stored in the elastic cloud where traffic is expensive. For this reason, we have a limit on daily download.