Presentation is loading. Please wait.

Presentation is loading. Please wait.

2016 Mexican Stata Users Group Meeting May 17, 2016 Carlos Alberto Dorantes Dosamantes Accounting and Finance Department Monterrey Tech, Querétaro Campus.

Similar presentations


Presentation on theme: "2016 Mexican Stata Users Group Meeting May 17, 2016 Carlos Alberto Dorantes Dosamantes Accounting and Finance Department Monterrey Tech, Querétaro Campus."— Presentation transcript:

1 2016 Mexican Stata Users Group Meeting May 17, 2016 Carlos Alberto Dorantes Dosamantes Accounting and Finance Department Monterrey Tech, Querétaro Campus Programming Financial Models with Stata and Excel

2 Introduction Stata is a robust alternative for quantitative financial analysts who have little or no experience in programming Although Stata does not offer a great variety of user commands for quantitative financial analysis, it offers a great variety of econometric models that can be applied to any financial model. Interfaces between Stata and Excel are easy to build. Most students and professionals are familiar with Excel, so it is convinient to use Excel as the front-end of a programming application, and Stata as the back-end A method to learn programming for financial models is presented: SPROFIN. This method was designed for an undergraduate course called Financial Programming (http://fz3030.egaderzc.net) Commands for Financial data management and Portfolio Optimization 2

3 SPROFIN method SPROFIN is a method to program/simulate financial models SPROFIN divides a program in the following: 1.Configuration commands 2.Script or commands for input data processing. Can be from Excel and/or online databases 3.Script for data management 4.Script for processing financial model(s) 5.Commands to display and/or save results of the models. The output can be sent to the same Excel file, another file, and/or to the screen Each script is a do-file, and each do-file is composed of Stata commands and also personal commands Commands for Financial data management and Portfolio Optimization 3

4 Teaching how to write an r-class Stata command Writing your own Stata command provides you structure, flexibility and re-usability in your programming The sections of an r-class ado command are the following: – The program statement – The syntax statement (includes parameters and if statement) – Definition of local macros and/or the touse macro (optional) – Program body – Return statements – Commands to display and/or send results – End statement Commands for Financial data management and Portfolio Optimization 4

5 Stata command Example 1 Commands for Financial data management and Portfolio Optimization 5 * This command receives 1 variable and gets the LAST non-missing value of the variable capture program drop traeultimo // drops the command from memory program define traeultimo, rclass // 1. Program statement syntax varlist(max=1 numeric) [if] // 2. Syntax statement marksample touse // 3. Definition of variables preserve // 4. Program body keep if `touse'==1 local i=_N while missing(`varlist'[`i']) { local i=`i'-1 } return scalar last=`varlist'[`i'] // 5. Return statement return scalar numelem=`i‘ // 5. Return statement display "The last element is " `varlist'[`i'] //6. Display command display "The last nonmissing element is in the row `i'“ // 6. Display command restore End // 7. The end command

6 Stata command Example 2 Commands for Financial data management and Portfolio Optimization 6 * This command receives 1 variable and gets the FIRST non-missing value of the variable capture program drop traeprimero // drops the command from memory program define traeprimero, rclass // 1. Program statement syntax varlist(max=1 numeric) [if] // 2. Syntax statement marksample touse // 3. Definition of variables preserve // 4. Program body keep if `touse'==1 local i=1 while missing(`varlist'[`i']) { local i=`i‘+1 } return scalar last=`varlist'[`i'] // 5. Return statement return scalar firstelem=`i‘ // 5. Return statement display "The first element is `varlist' is " `varlist'[`i'] //6. Display command display "The first nonmissing element is in the row `i'“ // 6. Display command restore end // 7. The end command

7 Stata command Example 3 – Reusing code Commands for Financial data management and Portfolio Optimization 7 * This command receives 1 variable and gets the Holing Simple Return of a Price variable capture program drop holdingret program define holdingret, rclass syntax varlist(max=1 numeric) [if] quietly traeprimero `varlist' `if' scalar primero=r(first) scalar posprimero=r(numelem) quietly traeultimo `varlist' `if' scalar ultimo=r(last) scalar posultimo=r(numelem) scalar hr=ultimo/primero - 1 scalar n = posultimo - posprimero + 1 display "The holding period return of the variable `varlist' is " hr display "The number of periods used for the holding return was " n return scalar holdingret=hr return scalar numelem=n end

8 Example 1 – SPROFIN Commands for Financial data management and Portfolio Optimization 8 *1) CONFIGURATION COMMANDS: cd "C:\Users\Alberto\Dropbox\201611\FZ3030\WSolutions\W6" clear *2) COMMAND(S) TO GET THE DATA (Online data from Yahoo Finance!) returnsyh ALPEKA.MX ICA.MX BIMBOA.MX GRUMAB.MX, /// fm(1) fd(1) fy(2005) lm(5) ld(31) ly(2016) frequency(m) price(adjclose) *3) COMMANDS TO MANIPULATE DATA drop vol* * 4) SCRIPT FOR THE CORE PROCESSING OF FINANCIAL MODEL: discard holdingret p_adjclose_ALPEKA_MX * 5) COMMANDS TO DISPLAY THE RESULT: display "The holding return of ALPEKA is: " r(holdngret) display "The number of periods used for ALPEKA HPR was:" r(numelem)

9 Stata command Example 4 – Backtest command Commands for Financial data management and Portfolio Optimization 9 program define backtest, rclass syntax varlist(min=2 numeric) [if], Weights(string) local numvariables: word count `varlist' matrix HRS=J(`numvariables',1,0) local i=0 foreach var of varlist `varlist' { quietly holdingret `var' `if' local i=`i' + 1 matrix HRS[`i',1]=r(holdingret) } matrix HRPORT=w'*HRS display "The holding return of the portfolio is " HRPORT[1,1] display "The holding return of each asset were:" matrix list HRS display "The weights used were: " matrix list `weights' return scalar retport=HRPORT[1,1] end

10 Example 2 – SPROFIN – Using the backtest command Commands for Financial data management and Portfolio Optimization 10 *1) CONFIGURATION COMMANDS: cd "C:\Users\Alberto\Dropbox\201611\FZ3030\WSolutions\W6" clear *2) COMMAND(S) TO GET THE DATA (Online data from Yahoo Finance!) returnsyh ALPEKA.MX BIMBOA.MX GRUMAB.MX, /// fm(1) fd(1) fy(2012) lm(12) ld(31) ly(2016) frequency(m) price(adjclose) *3) COMMANDS TO MANIPULATE DATA drop vol* matrix W1=(0.3\0.3\0.4) * 4) SCRIPT FOR THE CORE PROCESSING OF FINANCIAL MODEL: discard backtest p_*, w(W1) * 5) COMMANDS TO DISPLAY THE RESULT: display "The holding return of the portfolio is : " r(retport)

11 Example 3 – SPROFIN – Portfolio strategy based on CAPM alpha Commands for Financial data management and Portfolio Optimization 11 local dire="C:\Users\Alberto\Dropbox\201611\FZ3030\WSolutions\W8" local excel="templateW8.xlsx" cd "`dire'“ do getdata1 "`excel'" 1 "datos_stocks.dta" local back_month=tm(2014m12) do calculate_capms.do `back_month' putexcel B1=matrix(RES,names) using templatew8, sheet("tickers") modify do select_stocks.do "`excel'" "tickers" 1 cmline r_* if period<=`back_month', maxweight(0.20) rfrate(0.0020) noshort matrix w=r(wop) backtest p_adjclose_* if period>`back_month' & period<=tm(2015m12), weights(w) display "The holding period return of my portfolio during 2015 was: " `R_port'

12 getdata1.do – Script to read online data based on an Excel file Commands for Financial data management and Portfolio Optimization 12 clear set more off import excel using "`1'", sheet("parameters") firstrow clear local nn=`2' local fm=fm[`nn'] local fd=fd[`nn'] local fy=fy[`nn'] local lm=lm[`nn'] local ld=ld[`nn'] local ly=ly[`nn'] local freq=freq[`nn'] local pri=pri[`nn'] local sheet=sheet[`nn'] import excel using `1', sheet("`sheet'") firstrow clear levelsof ticker, local(lista) clean local numw: word count `lista' import excel using `1', sheet("rf") firstrow clear levelsof Rf, local(rf)clean returnsyh `lista', fm(`fm') fd(`fd') fy(`fy') lm(`lm') ld(`ld') ly(`ly') frequency(`freq') price(`pri')

13 Commands from mvport v2 are useful for Portfolio optimization Commands for Financial data management and Portfolio Optimization 13 returnsyh - gets prices and calculate returns of one or more tickers from Yahoo Finance meanrets - estimates the expected return of different stocks/instruments varrets - estimates the expected variance-covariance matrix of returns gmvport - calculates the global minimum variance portfolio mvport - estimates the minimum variance given a specific required return ovport - estimates the optimal/tangency portfolio variance given a specific risk-free rate efrontier - estimates a list of portfolios that lie on the efficient frontier cmline - estimates the capital market line, that is the efficient frontier after adding a risk-free rate to a portfolio. simport - simulates random feasible portfolios The meanrets and the varrets commands can do the traditional estimation according to Portfolio Theory or use the Exponential Weighted Moving Average (EWMA) model to estimate expected return and variance-covariance matrix The optimization commands have the following functionalities: Restrictions for minimum and/or maximum weights for each instrument are allowed EWMA model for expected returns and variance-covariance matrix is allowed. Customized vector and/or variance-covariance matrix can also be used. The following commands were added to the package: holdingret - estimates the buy-and-hold return of an instrument over a period backtest - backtest portfolio returns over a period

14 SPROFIN – Other financial models used Commands for Financial data management and Portfolio Optimization 14 Valuating an Call and a Put option using a Multiperiod Binomial Model and Monte Carlo simulation Valuating an Call and a Put option using Black-Scholes model Fundamental analysis

15 Wrap-up SPROFIN has been useful to teach business student how to program financial models SPROFIN has been useful to teach how to write Stata commands Teaching method based on Workshops and real online data has been very useful to teach how to program Details of the course can be found at: http://fz3030.egaderzc.net http://fz3030.egaderzc.net Commands for Financial data management and Portfolio Optimization 15

16 Thanks! You can reach me at: cdorante@itesm.mx Alberto Dorantes Dosamantes Professor at Monterrey Tech, Accounting and Finance Department, Querétaro Campus Commands for Financial data management and Portfolio Optimization 16


Download ppt "2016 Mexican Stata Users Group Meeting May 17, 2016 Carlos Alberto Dorantes Dosamantes Accounting and Finance Department Monterrey Tech, Querétaro Campus."

Similar presentations


Ads by Google