Econometrics and Free Software2014-07-14T07:49:59-07:00http://b-rodrigues.github.comBruno Rodriguesbrodrigues@unistra.frObject Oriented Programming with R: An example with a Cournot duopoly2014-04-23T00:00:00-07:00http://b-rodrigues.github.com/2014/04/23/r-s4-rootfinding
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<!-- MathJax scripts -->
<script type="text/javascript" src="https://c328740.ssl.cf1.rackcdn.com/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML">
</script>
</head>
<body>
<p>I started reading <em>Applied Computational Economics & Finance</em> by Mario J. Miranda and Paul L. Fackler. It is a very interesting book that I recommend to every one of my colleagues. The only issue I have with this book, is that the programming language they use is Matlab, which is proprietary. While there is a free as in freedom implementation of the Matlab language, namely Octave, I still prefer using R. In this post, I will illustrate one example the authors present in the book with R, using the package <code>rootSolve</code>. <code>rootSolve</code> implements Newtonian algorithms to find roots of functions; to specify the functions for which I want the roots, I use R's Object-Oriented Programming (OOP) capabilities to build a model that returns two functions. This is optional, but I found that it was a good example to illustrate OOP, even though simpler solutions exist, one of which was proposed by reddit user TheDrownedKraken (whom I thank) and will be presented at the end of the article.</p>
<h3>Theoretical background</h3>
<p>The example is taken from Miranda's and Fackler's book, on page 35. The authors present a Cournot duopoly model. In a Cournot duopoly model, two firms compete against each other by quantities. Both produce a certain quantity of an homogenous good, and take the quantity produce by their rival as given. </p>
<p>The inverse demand of the good is :</p>
<img src="http://latex.codecogs.com/png.latex?P(q) = q^{-\dfrac{1}{\eta}" alt="P(q) = q^{-\dfrac{1}{\eta}" />
<p>the cost function for firm i is:</p>
<img src="http://latex.codecogs.com/png.latex?C_i(q_i) = P(q_1+q_2)*q_i - C_i(q_i)" alt="C_i(q_i) = P(q_1+q_2)*q_i - C_i(q_i)}" />
<p>and the profit for firm i:</p>
<img src="http://latex.codecogs.com/png.latex?\pi_i(q1,q2) = P(q_1+q_2)q_i - C_i(q_i)" alt="\pi_i(q1,q2) = P(q_1+q_2)q_i - C_i(q_i)" />
<p>The optimality condition for firm i is thus:</p>
<img src="http://latex.codecogs.com/png.latex?\dfrac{\partial \pi_i}{\partial q_i} = (q1+q2)^{-\dfrac{1}{\eta}} - \dfrac{1}{\eta} (q_1+q_2)^{\dfrac{-1}{\eta-1}}q_i - c_iq_i=0." alt="\dfrac{\partial \pi_i}{\partial q_i} = (q1+q2)^{-\dfrac{1}{\eta}} - \dfrac{1}{\eta} (q_1+q_2)^{\dfrac{-1}{\eta-1}}q_i - c_iq_i=0." />
<h3>Implementation in R</h3>
<p>If we want to find the optimal quantities <img src="http://latex.codecogs.com/png.latex?\inline q_1" alt="\inline q_1" /> and <img src="http://latex.codecogs.com/png.latex?\inline q_2" alt="\inline q_2" /> we need to program the optimality condition and we could also use the jacobian of the optimality condition. The jacobian is generally useful to speed up the root finding routines. This is were OOP is useful. Firt let's create a new class, called <em>Model</em>:</p>
<pre><code class="r">setClass(Class = "Model", slots = list(OptimCond = "function", JacobiOptimCond = "function"))
</code></pre>
<p>This new class has two <em>slots</em>, which here are functions (in general <em>slots</em> are properties of your class); we need the model to return the optimality condition and the jacobian of the optimality condition.</p>
<p>Now we can create a function which will return these two functions for certain values of the parameters, <em>c</em> and <img src="http://latex.codecogs.com/png.latex?\inline \eta" alt="\inline \eta" /> of the model:</p>
<pre><code class="r">my_mod <- function(eta, c) {
e = -1/eta
OptimCond <- function(q) {
return(sum(q)^e + e * sum(q)^(e - 1) * q - diag(c) %*% q)
}
JacobiOptimCond <- function(q) {
return((e * sum(q)^e) * array(1, c(2, 2)) + (e * sum(q)^(e - 1)) * diag(1,
2) + (e - 1) * e * sum(q)^(e - 2) * q * c(1, 1) - diag(c))
}
return(new("Model", OptimCond = OptimCond, JacobiOptimCond = JacobiOptimCond))
}
</code></pre>
<p>The function <code>my_mod</code> takes two parameters, <code>eta</code> and <code>c</code> and returns two functions, the optimality condition and the jacobian of the optimality condition. Both are now accessible via <code>my_mod(eta=1.6,c = c(0.6,0.8))@OptimCond</code> and <code>my_mod(eta=1.6,c = c(0.6,0.8))@JacobiOptimCond</code> respectively (and by specifying values for <code>eta</code> and <code>c</code>).</p>
<p>Now, we can use the <code>rootSolve</code> package to get the optimal values <img src="http://latex.codecogs.com/png.latex?\inline q_1" alt="\inline q_1" /> and <img src="http://latex.codecogs.com/png.latex?\inline q_2" alt="\inline q_2" /> :</p>
<pre><code class="r">library("rootSolve")
multiroot(f = my_mod(eta = 1.6, c = c(0.6, 0.8))@OptimCond, start = c(1, 1),
maxiter = 100, jacfunc = my_mod(eta = 1.6, c = c(0.6, 0.8))@JacobiOptimCond)
</code></pre>
<pre><code>## $root
## [1] 0.8396 0.6888
##
## $f.root
## [,1]
## [1,] -2.220e-09
## [2,] 9.928e-09
##
## $iter
## [1] 4
##
## $estim.precis
## [1] 6.074e-09
</code></pre>
<p>After 4 iterations, we get that <img src="http://latex.codecogs.com/png.latex?\inline q_1" alt="\inline q_1" /> and <img src="http://latex.codecogs.com/png.latex?\inline q_2" alt="\inline q_2" /> are equal to 0.84 and 0.69 respectively, which are the same values as in the book!</p>
<h3>Suggestion by Reddit user, TheDrownedKraken</h3>
<p>I posted this article on rstats subbreddit on <a href="http://www.reddit.com">www.reddit.com</a>. I got a very useful comment by reddit member TheDrownedKraken which suggested the following approach, which doesn't need a new class to be build. I thank him for this. Here is his suggestion:</p>
<pre><code class="r">generator <- function(eta, a) {
e = -1/eta
OptimCond <- function(q) {
return(sum(q)^e + e * sum(q)^(e - 1) * q - diag(a) %*% q)
}
JacobiOptimCond <- function(q) {
return((e * sum(q)^e) * array(1, c(2, 2)) + (e * sum(q)^(e - 1)) * diag(1,
2) + (e - 1) * e * sum(q)^(e - 2) * q * c(1, 1) - diag(a))
}
return(list(OptimCond = OptimCond, JacobiOptimCond = JacobiOptimCond))
}
f.s <- generator(eta = 1.6, a = c(0.6, 0.8))
multiroot(f = f.s$OptimCond, start = c(1, 1), maxiter = 100, jacfunc = f.s$JacobiOptimCond)
</code></pre>
<pre><code>## $root
## [1] 0.8396 0.6888
##
## $f.root
## [,1]
## [1,] -2.220e-09
## [2,] 9.928e-09
##
## $iter
## [1] 4
##
## $estim.precis
## [1] 6.074e-09
</code></pre>
</body>
Using R as a Computer Algebra System with Ryacas2013-12-31T00:00:00-08:00http://b-rodrigues.github.com/2013/12/31/r-cas
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<!-- MathJax scripts -->
<script type="text/javascript" src="https://c328740.ssl.cf1.rackcdn.com/mathjax/2.0-latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML">
</script>
</head>
<body>
<p>R is used to perform statistical analysis and doesn't focus on symbolic maths. But it is sometimes useful to let the computer derive a function for you (and have the analytic expression of said derivative), but maybe you don't want to leave your comfy R shell. It is possible to turn R into a full-fledged computer algebra system. CASs are tools that perform symbolic operations, such as getting the expression of the derivative of a user-defined (and thus completely arbitrary) function. Popular CASs include the proprietary Mathematica and Maple. There exists a lot of CASs under a Free Software license, Maxima (based on the very old Macsyma), Yacas, Xcas… In this post I will focus on Yacas and the <code>Ryacas</code> libarary. There is also the possibility to use the <code>rSympy</code> library that uses the <code>Sympy</code> Python library, which has a lot more features than Yacas. However, depending on your operating system installation can be tricky as it also requires <code>rJava</code> as a dependency. </p>
<p>Even though <code>Ryacas</code> is quite nice to have, there are some issues though. For example, let's say you want the first derivative of a certain function f. If you use <code>Ryacas</code> to get it, the returned object won't be a function. There is a way to “extract” the text from the returned object and make a function out of it. But there are still other issues; I'll discuss them later.</p>
<h2>Installation</h2>
<p>Installation should be rather painless. On Linux you need to install Yacas first, which should be available in the major distros' repositories. Then you can install <code>Ryacas</code> from within the R shell. On Windows, you need to run these three commands (don't bother installing Yacas first):</p>
<pre><code>install.packages('Ryacas')
library(Ryacas)
yacasInstall()
</code></pre>
<p>You can find more information on the <a href="https://code.google.com/p/ryacas/#INSTALLATION">project's page</a>.</p>
<h2>Example session</h2>
<p>First, you must load <code>Ryacas</code> and define symbols that you will use in your functions.</p>
<pre><code class="r">require("Ryacas")
</code></pre>
<pre><code>## Loading required package: Ryacas Loading required package: XML
</code></pre>
<pre><code class="r">x <- Sym("x")
</code></pre>
<p>You can then define your fonctions:</p>
<pre><code class="r">my_func <- function(x) {
return(x/(x^2 + 3))
}
</code></pre>
<p>And you can get the derivative for instance:</p>
<pre><code class="r">my_deriv <- yacas(deriv(my_func(x), x))
</code></pre>
<pre><code>## [1] "Starting Yacas!"
</code></pre>
<p>If you check the class of <code>my_deriv</code>, you'll see that it is of class <code>yacas</code>, which is not very useful. Let's «convert» it to a function:</p>
<pre><code class="r">my_deriv2 <- function(x) {
eval(parse(text = my_deriv$YacasForm))
}
</code></pre>
<p>We can then evaluate it. A lot of different operations are possible. But there are some problems.</p>
<h2>Issues with Ryacas</h2>
<p>You can't use elements of a vector as parameters of your function, i.e.:</p>
<pre><code class="r">theta <- Sym("theta")
func <- function(x) {
return(theta[1] * x + theta[2])
}
# Let's integrate this
Func <- yacas(Integrate(func(x), x))
</code></pre>
<p>returns <code>(x^2*theta)/2+NA*x;</code> which is not quite what we want…there is a workaround however. Define your functions like this:</p>
<pre><code class="r">a <- Sym("a")
b <- Sym("b")
func2 <- function(x) {
return(a * x + b)
}
# Let's integrate this
Func2 <- yacas(Integrate(func2(x), x))
</code></pre>
<p>we get the expected result: <code>(x^2*a)/2+b*x;</code>. Now replace <code>a</code> and <code>b</code> by the thetas:</p>
<pre><code class="r">Func2 <- gsub("a", "theta[1]", Func2$YacasForm)
Func2 <- gsub("b", "theta[2]", Func2)
</code></pre>
<p>Now we have what we want: </p>
<pre><code class="r">Func2
</code></pre>
<pre><code>## [1] "(x^2*theta[1])/2+theta[2]*x;"
</code></pre>
<p>You can then copy-paste this result into a function.</p>
<p>Another problem is if you use built-in functions that are different between R and Yacas. For example:</p>
<pre><code class="r">my_log <- function(x) {
return(sin(log(2 + x)))
}
</code></pre>
<p>Now try to differentiate it:</p>
<pre><code class="r">dmy_log <- yacas(deriv(my_log(x), x))
</code></pre>
<p>you get: <code>Cos(Ln(x+2))/(x+2);</code>. The problem with this, is that R doesn't recognize <code>Cos</code> as the cosine (which is <code>cos</code> in R) and the same goes for <code>Ln</code>. These are valid Yacas functions, but that is not the case in R. So you'll have to use <code>gsub</code> to replace these functions and then copy paste the end result into a function.</p>
<h2>Conclusion</h2>
<p>While it has some flaws, <code>Ryacas</code> can be quite useful if you need to derive or integrate complicated expressions that you then want to use in R. Using some of the tricks I showed here, you should be able to overcome some of its shortcomings. If installation of <code>rJava</code> and thus <code>rSympy</code> becomes easier, I'll probably also do a short blog-post about it, as it has more features than <code>Ryacas</code>.</p>
</body>
Nonlinear Gmm with R - Example with a logistic regression2013-11-07T00:00:00-08:00http://b-rodrigues.github.com/2013/11/07/gmm-with-rmd
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<!-- MathJax scripts -->
<script type="text/javascript" src="https://c328740.ssl.cf1.rackcdn.com/mathjax/2.0-latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML">
</script>
</head>
<body>
<p>In this post, I will explain how you can use the R <code>gmm</code> package to estimate a non-linear model, and more specifically a logit model. For my research, I have to estimate Euler equations using the Generalized Method of Moments. I contacted Pierre Chaussé, the creator of the <code>gmm</code> library for help, since I was having some difficulties. I am very grateful for his help (without him, I'd still probably be trying to estimate my model!).</p>
<h3>Theoretical background, motivation and data set</h3>
<p>I will not dwell in the theory too much, because you can find everything you need <a href="https://en.wikipedia.org/wiki/Generalized_method_of_moments">here</a>. I think it's more interesting to try to understand why someone would use the Generalized Method of Moments instead of maximization of the log-likelihood. Well, in some cases, getting the log-likelihood can be quite complicated, as can be the case for arbitrary, non-linear models (for example if you want to estimate the parameters of a very non-linear utility function). Also, moment conditions can sometimes be readily available, so using GMM instead of MLE is trivial. And finally, GMM is... well, a very general method: every popular estimator can be obtained as a special case of the GMM estimator, which makes it quite useful.</p>
<p>Another question that I think is important to answer is: why this post? Well, because that's exactly the kind of post I would have loved to have found 2 months ago, when I was beginning to work with the GMM. Most posts I found presented the <code>gmm</code> package with very simple and trivial examples, which weren't very helpful. The example presented below is not very complicated per se, but much more closer to a real-world problem than most stuff that is out there. At least, I hope you will find it useful!</p>
<p>For illustration purposes, I'll use data from Marno Verbeek's <em>A guide to modern Econometrics</em>, used in the illustration on page 197. You can download the data from the book's companion page <a href="http://www.econ.kuleuven.ac.be/gme/">here</a> under the section <em>Data sets</em> or from the <code>Ecdat</code> package in R. I use the data set from Gretl though, as the dummy variables are numeric (instead of class <code>factor</code>) which makes life easier when writing your own functions. You can get the data set <a href="/assets/files/benefits.R">here</a>. </p>
<h3>Implementation in R</h3>
<p>I don't estimate the exact same model, but only use a subset of the variables available in the data set. Keep in mind that this post is just for illustration purposes.</p>
<p>First load the <code>gmm</code> package and load the data set:</p>
<pre><code class="r">require("gmm")
data <- read.table("path/to/data/benefits.R", header = T)
attach(data)
</code></pre>
<p>We can then estimate a logit model with the <code>glm()</code> function:</p>
<pre><code class="r">native <- glm(y ~ age + age2 + dkids + dykids + head + male + married + rr + rr2, family = binomial(link = "logit"), na.action = na.pass)
summary(native)
</code></pre>
<pre><code>##
## Call:
## glm(formula = y ~ age + age2 + dkids + dykids + head + male +
## married + rr + rr2, family = binomial(link = "logit"), na.action = na.pass)
##
## Deviance Residuals:
## Min 1Q Median 3Q Max
## -1.889 -1.379 0.788 0.896 1.237
##
## Coefficients:
## Estimate Std. Error z value Pr(>|z|)
## (Intercept) -1.00534 0.56330 -1.78 0.0743 .
## age 0.04909 0.02300 2.13 0.0328 *
## age2 -0.00308 0.00293 -1.05 0.2924
## dkids -0.10922 0.08374 -1.30 0.1921
## dykids 0.20355 0.09490 2.14 0.0320 *
## head -0.21534 0.07941 -2.71 0.0067 **
## male -0.05988 0.08456 -0.71 0.4788
## married 0.23354 0.07656 3.05 0.0023 **
## rr 3.48590 1.81789 1.92 0.0552 .
## rr2 -5.00129 2.27591 -2.20 0.0280 *
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
##
## (Dispersion parameter for binomial family taken to be 1)
##
## Null deviance: 6086.1 on 4876 degrees of freedom
## Residual deviance: 5983.9 on 4867 degrees of freedom
## AIC: 6004
##
## Number of Fisher Scoring iterations: 4
</code></pre>
<p>Now comes the interesting part: how can you estimate such a non-linear model with the <code>gmm()</code> function from the <code>gmm</code> package? </p>
<p>For every estimation with the Generalized Method of Moments, you will need valid moment conditions. It turns out that in the case of the logit model, this moment condition is quite simple:</p>
$$
E[X' * (Y-\Lambda(X'\theta))] = 0
$$
<p>where \( \Lambda() \) is the logistic function. Let's translate this condition into code. First, we need the logistic function:</p>
<pre><code class="r">logistic <- function(theta, data) {
return(1/(1 + exp(-data %*% theta)))
}
</code></pre>
<p>and let's also define a new data frame, to make our life easier with the moment conditions (don't forget to add a column of ones to the matrix, hence the <code>1</code> after <code>y</code>):</p>
<pre><code class="r">dat <- data.matrix(cbind(y, 1, age, age2, dkids, dykids, head, male, married,
rr, rr2))
</code></pre>
<p>and now the moment condition itself:</p>
<pre><code class="r">moments <- function(theta, data) {
y <- as.numeric(data[, 1])
x <- data.matrix(data[, 2:11])
m <- x * as.vector((y - logistic(theta, x)))
return(cbind(m))
}
</code></pre>
<p>The moment condition(s) are given by a function which returns a matrix with as many columns as moment conditions (same number of columns as parameters for just-identified models).</p>
<p>To use the <code>gmm()</code> function to estimate our model, we need to specify some initial values to get the maximization routine going. One neat trick is simply to use the coefficients of a linear regression; I found it to work well in a lot of situations:</p>
<pre><code class="r">init <- (lm(y ~ age + age2 + dkids + dykids + head + male + married + rr + rr2))$coefficients
</code></pre>
<p>And finally, we have everything to use <code>gmm()</code>:</p>
<pre><code class="r">my_gmm <- gmm(moments, x = dat, t0 = init, type = "iterative", crit = 1e-25, wmatrix = "optimal", method = "Nelder-Mead", control = list(reltol = 1e-25, maxit = 20000))
summary(my_gmm)
</code></pre>
<pre><code>##
## Call:
## gmm(g = moments, x = dat, t0 = init, type = "iterative", wmatrix = "optimal",
## crit = 1e-25, method = "Nelder-Mead", control = list(reltol = 1e-25,
## maxit = 20000))
##
##
## Method: iterative
##
## Kernel: Quadratic Spectral
##
## Coefficients:
## Estimate Std. Error t value Pr(>|t|)
## (Intercept) -0.9090571 0.5751429 -1.5805761 0.1139750
## age 0.0394254 0.0231964 1.6996369 0.0891992
## age2 -0.0018805 0.0029500 -0.6374640 0.5238227
## dkids -0.0994031 0.0842057 -1.1804799 0.2378094
## dykids 0.1923245 0.0950495 2.0234150 0.0430304
## head -0.2067669 0.0801624 -2.5793498 0.0098987
## male -0.0617586 0.0846334 -0.7297189 0.4655620
## married 0.2358055 0.0764071 3.0861736 0.0020275
## rr 3.7895781 1.8332559 2.0671300 0.0387219
## rr2 -5.2849002 2.2976075 -2.3001753 0.0214383
##
## J-Test: degrees of freedom is 0
## J-test P-value
## Test E(g)=0: 0.00099718345776501 *******
##
## #############
## Information related to the numerical optimization
## Convergence code = 10
## Function eval. = 17767
## Gradian eval. = NA
</code></pre>
<p>Please, notice the options <code>crit=1e-25,method="Nelder-Mead",control=list(reltol=1e-25,maxit=20000)</code>: these options mean that the Nelder-Mead algorithm is used, and to specify further options to the Nelder-Mead algorithm, the <code>control</code> option is used. This is very important, as Pierre Chaussé explained to me: non-linear optimization is an art, and most of the time the default options won't cut it and will give you false results. To add insult to injury, the Generalized Method of Moments itself is very capricious and you will also have to play around with different initial values to get good results. As you can see, the Convergence code equals 10, which is a code specific to the Nelder-Mead method which indicates «degeneracy of the Nelder–Mead simplex.» . I'm not sure if this is a bad thing though, but other methods can give you better results. I'd suggest you try always different maximization routines with different starting values to see if your estimations are robust. Here, the results are very similar to what we obtained with the built-in function <code>glm()</code> so we can stop here.</p>
<p>Should you notice any error whatsoever, do not hesitate to tell me.</p>
</body>
Method of Simulated Moments with R2013-01-29T00:00:00-08:00http://b-rodrigues.github.com/2013/01/29/method-of-simulated-moments-with-r
<p>Second update on my research, details <a href="/pages/Research.html">here</a>.</p>
Simulated Maximum Likelihood with R2013-01-16T00:00:00-08:00http://b-rodrigues.github.com/2013/01/16/simulated-maximum-likelihood-with-r
<p>First update on my research, details <a href="/pages/Research.html">here</a>.</p>
New website!2012-12-11T00:00:00-08:00http://b-rodrigues.github.com/2012/12/11/new-website
<p>This is my new website! It’s built using jekyll-bootstrap and hosted on Github. </p>