Saturday, June 11, 2011

Using PROC IML to deploy EWMA model for market risk


Exponentially weighted moving average (EWMA) model, which is a straight-forward moving average method in market risk, could memorize the finite market movements and address the relationship among multiple asset prices. Comparing with other multivariate volatility solutions like OGARCH or DCC, it usually shows the strongest fluctuations during the time span [Ref.1].

Since EWMA would utilize the variance-covariance matrices, Proc IML in SAS is the best match. In his blog, Rick Wicklin introduced a Cov() function in SAS/IML to create the sample covariance matrix for a given matrix [Ref. 2]. Thus I implemented this IML function in an EWMA() macro below and analyzed the correlations of the daily market returns between Google and Apple since 2005. As the result, SAS/IML proves very efficient and robust. Interestingly, in this experiment, I found that if a matrix or a vector is declared with specified size before the computation step, the program’s efficiency would be significantly improved. It may suggest that declaring matrices explicitly could be a good habit for SAS/IML programming.

References:
1. Jon Danielsson. ‘Financial Risk Forecasting’. Wiley, 2011.
2. Rick Wicklin. ‘Computing Covariance and Correlation Matrices’. The Do Loop. 08DEC2010.

/*******************READ ME*********************************************
* - Using Proc IML to deploy EWMA model for market risk -
*
* SAS VERSION: 9.2.2
* DATE: 12jun2011
* AUTHOR: hchao8@gmail.com
*
****************END OF READ ME******************************************/

****************(1) MODULE-BUILDING STEP********************************;
%macro EWMA(squote1 =, squote2 =, slambda =, filepath = );
/****************************************************************
* MACRO: EWMA()
* GOAL: estimate correlations between two stocks
* according to market daily returns by EWMA
* PARAMETERS: squote1 = first stock share
* squote2 = second stock share
* slambda = weight coefficient
* filepath = file path to input data and output plot
*****************************************************************/
options mlogic mprint;
data &squote1;
infile "&filepath\&squote1..csv" delimiter = ',' missover dsd firstobs=2;
format date yymmdd10.; informat date yymmdd10.;
format r best32.; informat r best32.;
input date $ r;
run;
data &squote2;
infile "&filepath\&squote2..csv" delimiter = ',' missover dsd firstobs=2;
format date yymmdd10.; informat date yymmdd10.;
format r best32.; informat r best32.;
input date $ r;
run;
proc sql;
create table _tmp01 as
select a.date, a.r as r1, b.r as r2
from &squote1 as a, &squote2 as b
where a.date = b.date
;quit;

proc iml;
start Cov(A);
n = nrow(A);
C = A - A[:,];
return( (C` * C) / (n-1) );
finish;
use _tmp01;
read all var{date r1 r2};
N = nrow(r1);
y = r1 || r2;
lambda = &slambda;
EWMA=J(N, 3);
S = J(2, 2);
S = Cov(y);
EWMA[1, ] = S[1,1] || S[2,2] || S[1, 2];
do i = 2 to N;
S = lambda * S + (1-lambda) * t(y[i, ]) * y[i, ];
EWMA[i, ] = S[1,1] || S[2,2] || S[1, 2];
end;
create _tmp02 from EWMA ;
append from EWMA;
quit;

data _tmp03;
set _tmp02;
rho = col3 / sqrt(col1 * col2);
keep rho;
run;
data _tmp04;
set _tmp01;
set _tmp03;
run;

proc template;
define statgraph ewmaplot;
begingraph / designwidth=1000px designheight=800px;
layout lattice / columns=1 columndatarange=union rowweights=(0.3 0.3 0.4);
layout overlay / cycleattrs=true xaxisopts=(label="Returns of %upcase(&squote1)")
yaxisopts=(griddisplay=on label=" " display=(line) displaysecondary=all);
seriesplot x=date y=r1;
endlayout;
layout overlay / cycleattrs=true xaxisopts=(label="Returns of %upcase(&squote2)")
yaxisopts=(griddisplay=on label=" " display=(line) displaysecondary=all);
seriesplot x=date y=r2 ;
endlayout;
layout overlay / cycleattrs=true xaxisopts=(label="Correlation by EWMA")
yaxisopts=(griddisplay=on label=" " display=(line) displaysecondary=all);
seriesplot x=date y=rho;
endlayout;
endlayout;
endgraph;
end;
run;
ods html gpath = "&filepath" style = harvest;
proc sgrender data=_tmp04 template=ewmaplot;
run;
ods html close;
%mend EWMA;

****************(2) TESTING STEP****************************************;
%getr(startday = '01jan2005'd, squote = goog, filepath = c:\tmp,
rpath = c:\Program Files\R\R-2.13.0\bin);
%getr(startday = '01jan2005'd, squote = aapl, filepath = c:\tmp,
rpath = c:\Program Files\R\R-2.13.0\bin);
%ewma(squote1 = goog, squote2 = aapl, slambda = 0.94, filepath = c:\tmp);

****************END OF ALL CODING***************************************;

Wednesday, June 8, 2011

Bootstrap prediction models for probability of default

Not like consumer credit scoring, corporate default study is usually jeopardized by the low-n-low-p data sizes. In the fourth chapter of their book, Gunter and Peter, demonstrated an example about how to construct prediction models for IDR (invesment grade default rate) using VBA and therefore evaluate them by residual sum of squares [Ref. 1]. The only shortcoming is that the variables are limited and the observations are scarce (25 total, 22 valid), which makes me feel awkward to estimate the distribution. In this case, bootstrapping may be a good alternative, since it is a simple and straightforward method to increase predictability. Previously, Wensui showed the logit bootstrapping for credit risk by Proc LOGISTIC and Proc GENMOD [Ref. 2]. Data transformation was conducted by Data Step merge first raised by Liang Xie [Ref. 3].

The GLMSELECT procedure in SAS 9.2.2 harnesses the power of variable selection and bootstrapping together. In the example, the trend of IDR is hard to tell, even with a 3-year moving average chart. Thus, I chose 10000 times of resampling. As the result, 3 of the four predictors remained with their corresponding satisfying parameters.

References:
1. Gunter Loeffler and Peter Posch. ‘Credit Risk Modeling using Excel and VBA’. The 2nd edition. Wiley.
2. Wensui Liu. ‘Improving credit scoring by generalized additive model’. SAS Global 2007.
3. Liang Xie. http://www.sas-programming.com

/*******************READ ME*********************************************
* - Bootstrap prediction models for probability of default -
*
* SAS VERSION: 9.2.2
* DATE: 09jun2011
* AUTHOR: hchao8@gmail.com
****************END OF READ ME******************************************/

****************(1) DATA INTEGRATION/TRANSFORMATION STEP*****************;
data idr;
infile datalines delimiter = ',' missover dsd lrecl=32767;
format year idr prf age bbb spr best12.;
input year idr prf age bbb spr;
datalines;
1981,0,-7.340255411,,27.02456779,2.77
/*To buy Gunter and Peter's book will have the full data*/
2005,0.030637255,3.183410997,6.673717385,45.77112235,1.91
;;;
run;

data idr_t;
merge idr(keep=idr firstobs=2 )
idr(rename=(idr=_idrforward year=_yearforward));
year = _yearforward + 1;
label idr = 'invesment grade default rate'
prf = 'forecasted change in corporate profits'
age = 'fraction of new issuers'
bbb = 'fraction of bbb-rated issuers'
spr = 'spread on baa bonds';
run;

****************(2) MODULE-BUILDING STEP********************************;
%macro idrbs(data =, nsamp =, out =);
/*****************************************************************
* MACRO: idrbs()
* GOAL: build prediction model by variable selection and
* bootstrapping
* PARAMETERS: data = dataset to use
* nsamp = numbers of bootstrapping
* out = name of scored dataset
*****************************************************************/
proc sgplot data = &data;
title 'the invesment grade default rates by years';
series x = year y = idr;
yaxis grid;
run;

ods graphics on;
proc macontrol data = &data;
title 'three year moving average chart for invesment grade default rate';
machart idr*year / span = 3 odstitle = title;
run;
proc glmselect data = &data plots = all;
model idr = prf age bbb spr/selection = stepwise(select = press);
modelaverage nsamples = &nsamp subset(best = 1);
output out = &out(drop = _:) p = pred_idr;
run;
ods graphics off;
%mend idrbs;

%idrbs(data = idr_t, nsamp = 10000, out = idr_scored);

****************END OF ALL CODING***************************************;

Tuesday, June 7, 2011

Automate univariate volatility modeling by macros


GARCH (generalized autoregressive conditional heteroscedasticity) models are widely used in market risk industry to estimate and forecast the volatility of returns. GARCH, including many variants like A-GARCH, GJR-GARCH and E-GARCH, is especially suitable for predicting short and medium term volatility forecasts, since it is based on sound economic model and capable of capturing volatility clustering [Ref. 1].

Matlab and R dominate the skies of market risk [Ref. 2], while SAS is frequently mentioned in the area of credit risk. For univariate volatility modeling of market risk, I personally feel that SAS’s AUTOREG procedure performs better than either the fGarch package in R or the garchset() function in Matlab [Ref. 3], because in my experience it is more robust and code-efficient. The pitfall for SAS to analyze volatility is that it does not have functionality to download financial market data. Fortunately the tseries package from R provides a get.hist.quote() function which obtains data from YAHOO or OANDA [Ref. 4]. In the example below, I embedded the corresponding modules of R into a SAS’s macro getr(), and therefore downloaded and transformed the historical data of S&P 500 adjusted close prices. Then I implemented a GARCH(4,1) model in another univol() macro to estimate and forecast the volatilities until the end of this year. The results suggest that the combination of SAS, R and Excel would be useful to generate and diagnose the desired GARCH model for volatility.

References:
1. Carol Alexander. ‘Market Risk Analysis, Practical Financial Econometrics’. Wiley.
2. Jon Danielsson. ‘Financial Risk Forecasting: The Theory and Practice of Forecasting Market Risk with Implementation in R and Matlab’. Wiley.
3. The AUTOREG procedure. ‘SAS/ETS 9.2 User's Guide’. http://support.sas.com
4. The get.hist.quote() function. http://finzi.psych.upenn.edu/R/library/tseries

/*******************READ ME*********************************************
* - Automate univariate volatility modeling by macros -
*
* SAS VERSION: 9.2.2
* R VERSION: 2.13.0 (library: 'tseries', 'foreign')
* EXCEL VERSION:2007
*
* DATE: 08jun2011
* AUTHOR: hchao8@gmail.com
****************END OF READ ME******************************************/

****************(1) MODULE-BUILDING STEP*******************************;
%macro getr(startday = '01jan2005'd, squote =, filepath =, rpath =);
/****************************************************************
* MACRO: getr()
* GOAL: download adjusted close prices for specified quote
* and convert them into returns
* PARAMETERS: startday = start day of data to be downloaded
* squote = quote symbol to be downloaded
* filepath = file path for data exchange
* rpath = installation path for R
*****************************************************************/
options mprint mlogic;
data _null_;
day = &startday;
call symput('startdate', %str(put(&startday,yymmdd10.)));
call symput('enddate', %str(put(today(),yymmdd10.)));
run;

proc sql;
create table _tmp0 (string char(800));
insert into _tmp0
values("library(tseries,foreign)")
values("p=get.hist.quote(instrument='quote_choose',")
values("start='start_date',end='end_date',quote ='AdjClose',quiet=T)")
values("y=diff(log(p))")
values("y=y-mean(y)")
values("result=as.data.frame(y)")
values("write.csv(result,file='sas_path/find_result.csv')")
;quit;

data _tmp1;
set _tmp0;
string = tranwrd(string, "start_date", "&startdate");
string = tranwrd(string, "end_date", "&enddate");
string = tranwrd(string, "quote_choose", lowcase("&squote"));
string = tranwrd(string, "sas_path", translate("&filepath", "/", "\"));
string = tranwrd(string, "find_result", "&squote");
run;
data _null_;
set _tmp1;
file "&filepath\sas_r.r";
put string;
run;

options xsync xwait;
x "cd &rpath";
x "R.exe CMD BATCH --vanilla --slave &filepath\sas_r.r";
%mend getr;

%macro univol(predday = '31dec2011'd, q = 1, p = 0, filepath =);
/****************************************************************
* MACRO: univol()
* GOAL: estimate or forcast volatilities by garch(q, p)
* and plot diagnosis
* PARAMETERS: predday = end day for volatility prediction
* q = the subset of ARCH terms to be fitted
* p = the subset of GARCH terms to be fitted
* filepath = file path to exchange data
*****************************************************************/
options mprint mlogic;
data _tmp01;
infile "&filepath\result.csv" delimiter = ',' missover dsd
lrecl=32767 firstobs=2 end = eof;
format date yymmdd10.; informat date yymmdd10.;
format r best32.; informat r best32.;
input date $ r;
if eof then call symput('maxdaygot', date);
run;

data _null_;
format date yymmdd10.;
date = &maxdaygot;
dayinterval = intck('day', date, &predday);
call symput('dayinterval', dayinterval);
run;

%if %eval(&dayinterval) gt 0 %then %do;
data _tmp02(drop=i);
format date yymmdd10.;
date = &maxdaygot;
do i = 1 to &dayinterval;
r = .;
date + 1;
output;
end;
run;
data _tmp01;
set _tmp01 _tmp02;
run;
%end;

ods html file = "&filepath\output.xls" gpath = "&filepath\" style = harvest;
title; footnote;
ods graphics on;
ods select standardresidualplot fitplot qqplot residualhistogram acfplot;
proc autoreg data=_tmp01 all plots(unpack);
model r = / noint garch=(q=&q, p=&p);
output out=_tmp02 cev=v;
run;
ods graphics off;
data _tmp03;
set _tmp02;
length type $ 8.;
if r ne . then do;
type = 'estimate'; output; end;
else do;
type = 'forecast'; output; end;
run;

proc print data = _tmp03 noobs;
run;
proc sgplot data=_tmp01;
series y=r x=date /lineattrs=(color=blue);
refline 0/ axis = y lineattrs = (pattern=shortdash);
run;
proc sgplot data=_tmp03;
series x=date y=v/group=type;
refline &maxdaygot/ axis = x lineattrs = (pattern=shortdash);
run;
ods html close;
%mend univol;

****************(2) TESTING STEP****************************************;
%getr(startday = '01jan2005'd, squote = ^gspc, filepath = c:\tmp,
rpath = c:\Program Files\R\R-2.13.0\bin);
%univol(predday = '31dec2011'd, q = 4, p = 1, filepath = c:\tmp);

****************END OF ALL CODING***************************************;

Saturday, June 4, 2011

The eve of Lehman Brothers' demise


Recently Moody’s warned the US government to degrade its credit rating if the nation’s debt limit increase is not approved [Ref. 1]. The news came right after Standard & Poor’s lowered US’s sovereign rating from AAA to AA. Those rating changes suggest the accumulation of default risk and may cause some butterfly effect.

Before the start of this Great Recession, without much notice, Lehman Brothers’ default probability increased drastically according to a classic model by Merton [Ref. 2]. And this change failed to be disclosed by either Standard & Poor’s rating or the stock price. Here I translated Gunter and Peter’s VBA code for Merton’s model [Ref. 3] into SAS code and reproduced the trend plot. The result clearly shows that implementation of probability and statistics may catch alert within the narrow 'escape' window, and therefore help avoid or mitigate risks .

References:
1. ‘Moody’s Warns of Downgrade for U.S. Credit’. The New York Times. 02JUN2011
2. Merton, R.C. ‘On the pricing of corporate debt: The risk structure of interest rates’. The Journal of Finance. 29(2): 449-470. 1974
3. Gunter Loeffler and Peter Posch. ‘Credit Risk Modeling using Excel and VBA’. The 2nd edition. Wiley.


/*******************READ ME*********************************************
* - The eve of Lehman Brothers' demise -
*
* SAS VERSION: 9.2.2
* DATE: 04jun2011
* AUTHOR: hchao8@gmail.com
****************END OF READ ME******************************************/

proc fcmp outlib = work.cg.func;
function cg_ps(s, sigma_s, d, lambda, sigma_b, t);
d1 = (s + lambda*d) * exp(sigma_b ** 2) / (lambda *d);
alpha = (((sigma_s*s) / (s + lambda * d))**2 * t + sigma_b**2)**0.5;
x = probnorm(-(alpha/2) + (log(d1)/alpha)) -
d1 * probnorm(-(alpha/2) - (log(d1) / alpha));
return(x);
endsub;
run;

data record;
input @1 date $7. @11 sp 4.2 @18 dps 20.8 @32 Vol30d 4.2 @43 s_p $2.;
cards;
Q4 2003 36.11 69.95612419 25.26 A+
/*To buy Gunter and Peter's book will have the full data*/
Q2 2008 36.81 127.8 99.93 A
;;;
run;

options cmplib = work.cg;
data scored;
set record;
global_rcv = 0.5;
vol_barrier = 0.1;
time = 1;
vol30d = vol30d / 100;
pd = 1 - cg_ps(sp, vol30d, dps, global_rcv, vol_barrier, time);
label sp = 'Lehman Brothers'' stock price'
pd = 'Probability of default';
run;

proc sgplot data = scored;
series x = date y = sp;
series x = date y = pd / y2axis;
yaxis values= (0 to 90 by 10) label = 'stock price($)';
y2axis values= (0 to 0.4 by 0.05) grid
label = 'Default rating by Merton''s model';
refline 'Q4 2005' / axis = x;
inset "Time period when S&P rating as A" / position = topright ;
inset "Time period when S&P rating as A+" / position = topleft;
run;

Thursday, June 2, 2011

Using Proc IML for credit risk validation


Validation step is crucial for a scorecard in credit risk industry. Gunter and Peter mentioned in their fantastic book [Ref. 1] that cumulative accuracy profile (CAP) and receiver operating characteristic (ROC) are two popular methods. Thus, the values of accuracy ratio from CAP (or I refer it as Gini coefficient) and area under curve(AUC) from ROC would be important metrics to evaluate the discriminatory power of the scorecard. And actually they can be derived from each other by their linear relationship.

In the latest post of his blog, Rick Wicklin introduced how to implement the trapezoidal rule or calculate trapezoid areas under curve by a function of Proc IML [Ref. 2]. Although the same methodology can be realized by Data Step array or Proc FCMP, the beauty of Rick’s method is that it avoids the loops through IML’s matrix operation and therefore is more efficient and scalable. In the example below, I built Rick’s function into a macro to calculate AUC and accuracy ratio for a tiny testing dataset. The ‘TrapIntegral’ function can be further applied for validation of large-scale credit risk records.

References:
1. Gunter Löeffler and Peter Posch. ‘Credit Risk Modeling using Excel and VBA’. The 2nd edition. Wiley.
2. Rick Wicklin. ‘The Trapezoidal Rule of Integration’. The Do Loop. 01JUN2011.

/*******************READ ME*********************************************
* - Using Proc IML for credit risk validation -
*
* SAS VERSION: 9.2.2
* EXCEL VERSION: 2007
* DATE: 02jun2011
* AUTHOR: hchao8@gmail.com
*
****************END OF READ ME******************************************/

****************(1) MODULE-BUILDING STEP********************************;
%macro auc(data =, path =, filename =);
/*****************************************************************
* MACRO: auc()
* GOAL: calcuate auc and accuracy ratio for default risk
* PARAMETERS: data = dataset to use
* path = output path
* filename = name for validation card
*****************************************************************/
options mprint mlogic;
ods listing close;
proc sql;
select sum(default) into :totaldef
from &data;
quit;

data _tmp01;
set &data nobs = nobs;
xratio = ifn(default = 0, 1, 0)/(nobs - &totaldef);
yratio = default/&totaldef;
run;
proc sort data = _tmp01 out = _tmp02;
by descending rating descending default;
run;
data _tmp03;
set _tmp02;
by descending rating;
retain x y;
if _n_ = 1 then do; x = 0; y = 0; end;
x + xratio;
y + yratio;
if last.rating;
run;
data _tmp04;
if _n_ = 1 then do; x = 0; y = 0; end; output;
set _tmp03(keep = x y);
run;

proc iml;
use _tmp04;
read all var{x y};
start TrapIntegral(x,y);
N = nrow(x);
dx = x[2:N] - x[1:N-1];
meanY = (y[2:N] + y[1:N-1])/2;
return( dx` * meanY );
finish;
area = TrapIntegral(x,y);
acuratio = 2*area - 1;
call symput('area', left(char(area)));
call symput('acuratio', left(char(acuratio)));
quit;

ods html file = "&path&filename..xls" gpath = "&path" style = harvest;
title; footnote;
proc print data = &data label noobs;
run;

proc sgplot data = _tmp04;
series x = x y = y ;
scatter x = x y = y;
band x =x upper = y lower = 0 / transparency=.5;
xaxis grid;
yaxis grid;
inset "AUC is: %sysfunc(putn(&area, 8.4));
Accuracy Ratio is: %sysfunc(putn(&acuratio, 8.4))"
/ position = bottomright border;
keylegend "scatter";
run;
ods html close;

proc datasets;
delete _:;
quit;
ods listing;
%mend auc;

****************(2) TESTING STEP****************************************;
data test;
input Observation Rating $ Default;
label rating = 'Rating(A is best)'
default = 'Default(1=default)';
cards;
1 A 0
2 A 0
3 A 0
4 B 1
5 B 0
6 B 0
7 C 1
8 C 1
9 C 1
10 C 0
;;;
run;

%auc(data = test, path = h:\, filename = valid);
****************END OF ALL CODING***************************************;

Tuesday, May 31, 2011

A scorecard for probability of default with sparkline


In the 1st chapter of their must-read credit risk modeling book, Gunter and Peter used the ratios of working capital(WC), retained earnings(RE), earnings before interest and taxes(EBIT), sales(S) and market value of equity(ME) over either total liabilities (TL) or total assets(TA), to build a logit default risk model for 4000 records by 791 firms through 10 years [Ref.1]. The authors implemented VBA’s user-defined functions in Excel to realize the modeling and scoring procedures. In SAS, Proc Logistic does the same job.

Macros in SAS and Excel can be used together. Excel2010’ new Sparkline functions visualize the fluctuations of values in many rows. For those firms which eventually didn’t default in Gunter and Peter’s example, Sparkline can help observe the changing pattern of default risk for specific firms, such as which year the firms’ maximum default risk occur. Collin and Eli disclosed some definitions to translate a SAS dataset to an Excel table [Ref. 2]. Thus, by using their method, a SAS macro that generates VBA code will automate this process for a default risk scorecard with Sparkline.

References:
1. Gunter Löeffler and Peter Posch. ‘Credit Risk Modeling using Excel and VBA’. The 2nd edition. Wiley.
2. Collin Elliot and Eli Morris. ‘Excel lent SAS Formulas: The Creation and Export of Excel Formulas Using SAS’ . SAS Global 2009.

/*******************READ ME*********************************************
* - A scorecard for probability of default(PD) with sparkline -
*
* SAS VERSION: 9.1.3
* EXCEL VERSION: 2010
* DATE: 31may2011
* AUTHOR: hchao8@gmail.com
*
****************END OF READ ME******************************************/

%macro splscd(data = , path = , filename = );
/*****************************************************************
* MACRO: splscd()
* GOAL: create xls and vba for a scorecard with sparkline
* PARAMETERS: data = dataset for modeling and scoring
* path = output path
* filename = name for scorecard
*****************************************************************/
options mprint mlogic;
data _excelCol(where = (start le 256));
length label $2;
do c1 = -1 to 25;
do c2 = 0 to 25;
alpha1 = byte(rank('A')+ c1);
alpha2 = byte(rank('A')+ c2);
label = compress(alpha1||alpha2, " @");
start + 1;
fmtName = "column";
output;
end;
end;
run;

proc format cntlin = _excelCol;
run;

proc logistic data = &data;
model default = WCoverTA REoverTA EBIToverTA MEoverTL SoverTA;
score data = &data out = _scored;
run;

data _tmp01;
set _scored;
where default = 0;
keep id year p_1;
run;

proc sort data = _tmp01;
by id year;
run;

proc transpose data = _tmp01 out = _tmp02(keep = id year:) prefix = year;
by id;
id year;
var p_1;
run;

ods listing close;
ods output variables = _vartab;
proc contents data = _tmp02;
run;

proc sql;
select variable into: varlist separated by ' '
from _vartab
order by substr(variable, 5, 4)
;
select count(*) format = column. into: col_num
from _vartab
;
select count(*)+1 format = column. into: spl_col
from _vartab
;
quit;

data _tmp03;
retain &varlist;
set _tmp02 nobs = nobs;
sparkline =.;
call symput('nobs_plus', nobs + 1);
run;

ods html file = "&path\&filename..xls" style = minimal;
option missing = '';
title; footnote;
proc print data = _tmp03 noobs;
run;
ods html close;

proc sql;
create table _tmp04 (string char(200));
insert into _tmp04
values("Sub sas2vba()")
values("''''''''CREATE SPARKLINE'''''''''")
values('Columns("spl_col:spl_col").ColumnWidth=30')
values("Dim mySG As SparklineGroup")
values('Set mySG = _ ')
values('Range("$spl_col$2:$spl_col$nobs_plus").SparklineGroups.Add(Type:=xlSparkColumn, SourceData:="B2:col_numnobs_plus")')
values('mySG.SeriesColor.ThemeColor=6')
values("mySG.Points.Highpoint.Visible=True")
values("''''''''FORMAT THE TABLE'''''''''")
values('ActiveSheet.ListObjects.Add(xlSrcRange,Range("$A$1:$spl_col$nobs_plus"), , xlYes).Name="myTab"')
values('Range("myTab[#All]").Select')
values('ActiveSheet.ListObjects("myTab").TableStyle="TableStyleMedium1"')
values("''''''''SAVE AS EXCEL2010 FORMAT'''''''''")
values('ChDir "sas_path"')
values('ActiveWorkbook.SaveAs Filename:="sas_path\excel_file.xlsx",FileFormat:=xlOpenXMLWorkbook,CreateBackup:=False')
values("End Sub")
;
quit;

data _tmp05;
set _tmp04;
string = tranwrd(string, "spl_col", "&spl_col");
string = tranwrd(string, "nobs_plus", "&nobs_plus");
string = tranwrd(string, "col_num", "&col_num");
string = tranwrd(string, "sas_path", "&path");
string = tranwrd(string, "excel_file", "&filename");
if _n_ in (3, 6, 10) then string = compress(string, ' ');
run;

data _null_;
set _tmp05;
file "&path\&filename..bas";
put string;
run;

proc datasets nolist;
delete _:;
quit;
%mend splscd;

%splscd(data = test1, path = c:\tmp, filename = scorecard);

Sunday, May 29, 2011

Monte Carlo and quasi-Monte Carlo simulations for credit risk

In SAS, we can do quasi-Monte Carlo simulation by Halton’s low-discrepancy sequences, which are better than random variables from uniform distribution . The only procedure in SAS 9.2 to produce Halton’s sequence is probably the MDC procedure in SAS/ETS [Ref. 2] but hard to output. However, we can build a user-defined function by PROC FCMP to realize our goals. I showed an example by modifying the codes from Paolo Brandimarte’s Matlab book [Ref. 1] to estimate the area of an arbitrary surface. Overall, Halton’s method would converge with more sampling points, while uniform randomization will cause estimates fluctuating along the real value.

/*******************READ ME*********************************************
* - QUASI-MONTE CARLO SIMULATION BY FUNCTIONAL PROGRAMMING -
*
* VERSION: SAS 9.2(ts2m0), windows 64bit
* DATE: 02apr2011
* AUTHOR: hchao8@gmail.com
*
****************END OF READ ME*****************************************/

****************(1) MODULE-BUILDING STEP******************;
******(1.1) COMPILE USER-DEFINED FUNCTIONS*************;
proc fcmp outlib = sasuser.qmc.funcs;
/***********************************************************
* FUNCTION: h = halton(n, b)
* INPUT: n = the nth number | b = the base number
* OUTPUT: h = the halton's low-discrepancy number
***********************************************************/
function halton(n, b);
n0 = n;
h = 0;
f = 1 / b;
do while (n0 > 0);
n1 = floor(n0 / b);
r = n0 - n1*b;
h = h + f*r;
f = f / b;
n0 = n1;
end;
return(h);
endsub;

/***********************************************************
* FUNCTION: z = surface1(x, y)
* INPUT: x, y = independent variables
* OUTPUT: z = response variable
***********************************************************/
function surface1(x, y);
pi = constant("PI");
z = exp((-x)*y) * (sin(6*pi*x) + cos(8*pi*y));
return(z);
endsub;
run;

******(1.2) BUILD A 3D PLOTTING MACRO*************;
%macro plot3d(ds = , x = , y = , z = , width = , height = , zangle = );
ods html style = money;
ods graphics / width = &width.px height = &height.px imagefmt = png;
proc template;
define statgraph surfaceplotparm;
begingraph;
layout overlay3d / cube = true rotate = &zangle;
surfaceplotparm x = &x y = &y z = &z
/ surfacetype = fill surfacecolorgradient = &z;
endlayout;
endgraph;
end;
run;

proc sgrender data = &ds
template = surfaceplotparm;
run;
ods graphics off;
ods html close;
%mend;

****************END OF STEP (1)******************;

****************(2) PROGRAMMING STEP**********************;
******(2.1) IMPORT USER-DEFINED FUNCTIONS*************;
option cmplib = (sasuser.qmc);

******(2.2) DISTRIBUTIONS BETWEEN HALTON AND UNIFORM RANDOM NUMBERS*;
data test;
do n = 1 to 100;
do b = 2, 7;
halton_random_number = halton(n, b);
uniform_random_number = ranuni(20110401);
output;
end;
end;
run;

proc transpose data = test out = test1;
by n;
var halton_random_number uniform_random_number;
id b;
run;

******(2.3) GENERATE DATA FOR PLOTTING FUNCTION'S SURFACE****;
data surface;
do x = 0 to 1 by 0.01;
do y = 0 to 1 by 0.01;
z = surface1(x, y);
output;
end;
end;
run;

******(2.4) CONDUCT QUASI-MONTE CARLO SIMULATION***;
data simuds;
do i = 1 to 50;
do n = 1 to 100*i;
do b = 2, 7;
halton_random_number = halton(n, b);
uniform_random_number = ranuni(20110401);
output;
end;
end;
end;
run;

proc transpose data = simuds out = simuds_t;
by i n;
id b;
var halton_random_number uniform_random_number;
run;

data simuds1;
set simuds_t;
x = surface1(_2, _7);
run;

proc sql;
create table simuds2 as
select i, _name_, mean(x) as area label = 'Area by simulation'
from simuds1
group by i, _name_
;quit;

****************END OF STEP (2)******************;

****************(3) VISUALIZATION STEP*******************************;
******(3.1) PLOT DATA BY STEP 2.2*************;
ods html style = money;
proc sgscatter data = test1;
plot _2*_7 / grid group = _name_;
label _2 = 'Sequences with 2 as base'
_7 = 'Sequences with 7 as base'
_name_ = 'Methods';
run;
ods html close;

******(3.2) PLOT DATA BY STEP 2.3*************;
%plot3d(ds = surface, x = x , y = y, z = z, width = 800, height = 800, zangle = 60)

******(3.3) PLOT DATA BY STEP 2.4*************;
ods html style = ocean;
proc sgplot data = simuds2;
series x = i y = area / group = _name_ ;
refline 0.0199 / axis = y label = ('Real area');
xaxis label = 'Random numbers --- ×100';
label _name_ = 'Methods';
run;
ods html close;

****************END OF STEP (3)******************;

****************END OF ALL CODING***************************************;


First, we can use Monte Carlo simulation to evaluate the risk of a portfolio of credit instruments. As for a risk manager, the common question is to answer the probability of the losses for a portfolio over certain time period. To conduct a Monte Carlo simulation, four variables, such as Probability of default(PD), Loss given default(LGD), Exposure at default(EAD), Weight(correlations among individual credit events), are required. Here I simulated a portfolio with 100 obligors. Then I ran a 10000- loop for MC and calculated the loss at given percentiles. The histogram of the portfolio loss is displayed above.

data raw;
format pd lgd percent8.;
w = 0.3;
do i = 1 to 50;
PD = 0.01;
LGD= 0.5;
EAD= 100;
output;
end;
do i = 51 to 100;
PD = 0.05;
LGD= 0.5;
EAD= 100;
output;
end;
label pd = 'Probability of default'
lgd = 'Loss given default'
ead = 'Exposure at default'
w = 'Weight';
run;

libname mem 'c:\tmp' memlib;
data mem.raw;
set raw;
run;

%macro mc(cycle = );
filename junk dummy;
proc printto log=junk; run;
%do i = 1 %to &cycle;
%if %eval(&i) = 1 %then %do;
proc sql;
create table mem.result (sumloss num);
quit;
%end;
data mem._tmp01;
set mem.raw;
retain z;
if _n_ = 1 then z = rannor(0);
d = probit(pd);
a = w*z + (1-w**2)**0.5*rannor(0);
if a < d then loss = lgd*ead;
else loss = 0;
run;
proc sql;
insert into mem.result
select sum(loss) from mem._tmp01;
quit;
%end;
proc univariate data = mem.result noprint;
output out = mem.pct pctlpts = 90 95 99 99.5 pctlpre = loss;
run;
proc printto; run;
%mend;
%mc(cycle = 10000);

References:
1. Paolo Brandimarte. Numerical methods in finance. John Wiley & Sons. 2002.
2. SAS/ETS 9.2 user’s guide. SAS Publishing. 2008