################################### R Basics ###########################
#In the R script you write code and comments
#any line starting with # is a comment and it is NOT executed
## First things first: set the working directory to the the folder in which your R files are stored using: setwd("C:/")
# note that you need to separate folders by slashes /
#Let's define some variables
s = 0.05
Y = 10
#We can also assign several variables the same value at once
C = I = R = 2
#For displaying them we simply call the name of the object and execute the relevant line
Y
C
#We can define new variables using existing ones
W = Y - R
W
#R has a vast amount of built in functions, for example
max(10,2,100,-3)
sqrt(9)
abs(-13)
#you can find out more about these by using the help function, e.g.:?max()
#How can you delete stuff? Use the remove function rm()
#for individual objects
rm(Y)
#if you want to remove everything
rm(list=ls(all=TRUE))
#You can also assign text (a string) to a variable
text1 = 'Reggaeton'
text2 = "Bad Bunny"
#note "text" is the same as 'text' and a string can contain spaces
#You use the paste function to combine strings
paste(text1, text2)
#R uses standard operators like +, -, *
#for exponents use ^
3^2
########################### if statements and loops ######################
#sometimes we need to introduce if conditions into our code
#The syntax is
#if condition { do something }
a = 10
b = 13
if (b>a) {
print("b is bigger")
}
#we can also tell R what to do in case the condition is not fulfilled
b=10
if (b>a) {
print("b is bigger")
} else {
print("b not bigger")
}
#Next we will look at loops which are a key tool to repeat tasks such as solving
#a theoretical model again and again to find its equilibrium.
#The basic structure is:
for (i in 1:5){
print(i)
}
#Let's use it to solve a simple Keynesian cross model of the form
#Y=C+I
#C=c0+c1Y
#Define exogenous parameters
c0=2
c1=0.8
I=10
#set initial values for two endogenous variable
Y=C=1
#Use a for loop to solve it
C
Y
for (i in 1:100){
Y = C+I
C = c0+c1*Y
}
C
Y
#solution is Y=(I+c0)/(1-c1)=60
#What is special about this loop is that it uses the values from the previous iteration
#to define the values of the next, because it starts with assigning a value to Y
#and then uses that value to assign a new value to C and in the next iteration it
#uses this new value for C to define a new value for Y etc.
########################### Data structures ##########################
#In most applications we produce outputs which do not consist of a single number.
#Often we have an entire stream of results, or we want to analyse data and have to store larger amounts of data
#R has a variety of data structures for this purpose.
#let's clean up first
rm(list=ls(all=TRUE))
####Vectors
#We can create an empty vector and fill it later (with results of our model for example)
vec1 = vector(length=3)
#we can define vectors explicitly using the c() function (c for column?)
vec2 = c(1,2,3)
vec3 = c(6,7,8)
#we can also use the sequence operator
vec4 = 1:10
#and we can define the step size
vec5 = seq(1,2,0.1)
vec5
#we can call specific entries using square brackets
vec5[4]
#if we want to access more elements at once
vec5[c(4,1)]
####Matrices
#define a matrix: 3 rows and 2 columns, all elements equal to 0
mat1 = matrix(0, nrow=3, ncol=2)
mat1
#we can also fill it with specific values
mat2 = matrix(c(1,2,3,4,5,6), nrow = 3, ncol = 2)
mat2
#access specific elements (columns,rows)
mat2[3,1]
#access entire rows or columns
mat2[,1]
mat2[1,]
#access sub matrices
mat2[c(1,2),]
## Combine two column vectors in a matrix
mat3=cbind(vec1, vec2)
mat3
## Combine two row vectors in a matrix
mat4=rbind(vec1, vec2)
mat4
1 Getting Started
Structure of platform
The platform starts off with a general introduction the numerical simulation of economic models (Chapter 2). After that, it jumps right into a series of macroeconomic models. These models are grouped into static and dynamic models. In static models, time plays no role and all variables adjust instantaneously. By contrast, dynamic models characterise the adjustment of variables over time.
The model entries are largely self-contained and can be read independently of each other. For each model, the chapters provide three main components:
- Model descriptions that concisely explain the key ideas, assumptions, and equations of each model. This helps users grasp the underlying concepts and intuition behind the models.
- Annotated code that allows users to numerically simulate the models, examine their results under different scenarios, and produce visualisations to better understand the models’ structure and output. This hands-on approach enables users to gain practical coding skills while exploring different macroeconomic theories.
- Analytical discussions for users who are interested in delving deeper into the mathematical properties of the models.
To further facilitate the understanding of dynamic models, Chapter 9 of the section on dynamic models begins with a general introduction into the mathematical analysis of dynamic models (this is mostly relevant for the analytical discussions of dynamic models).
All simulation codes are written in the open-source programming languages R and Python. R codes are presented in the main text (and images and results in the text are the output of the shown R codes), while the corresponding Python codes are available by clicking on the callout blocks underneath the R codes.
Access and introduction to R and Python
To be able to manipulate the codes on this platform on your own machine, you first need to download and install R and RStudio. For Python, there are different options. One of them is to download and install Spyder via the Anaconda Python distribution. Spyder provides an interface for Python (like RStudio for R). If you install it via Anaconda, it will install Python automatically.
Besides being free, a key advantage of both R and Python is their huge and growing functionality due to new user-written libraries and packages continuously being added. In addition, a large amount of learning material is freely available on the web, e.g. here and here for R and here, and here for Python. However, to get started in can be best to directly delve into some of the codes on this platform and learn by doing. To this end, the following “cheatsheets” that provide a concise overview of key functions are useful:
Once you have installed R or Python, you can play with the codes on this platform yourself by copy and pasting them into the script panel of your local interface (IDE) and hitting CTRL + Enter to execute them. Don’t forget to always comment your code using the “#” symbol and to save your scripts to make sure your future self can seamlessness continue working on it.
The codes below covers some basic operations.^{1} If you are new to R or Python and keen to get started, do the following:
- copy the codes below into the script panel of RStudio or Spyder on your machine
- adjust the working directory to your personal folder
- then run the code
- make sure you understand what it does
################################### Python Basics ###########################
#In the Python script you write code and comments
#any line starting with # is a comment and it is NOT executed
## First things first: set the working directory to the the folder
# in which your Python files are stored using:
# import os
# os.setcwd("C:/yourworkingdirectory")
# note that you need to separate folders by slashes /
# Most of what we will do relies on the library NumPy
# Let's load NumPy and call its commands by the prefix .np
# Load relevant libraries
import numpy as np
#Let's define some variables
= 0.05
s = 10
Y
#We can also assign several variables the same value at once
= I = R = 2
C
#For displaying them we simply call the name of the object and
# execute the relevant line
Y
C
#We can define new variables using existing ones
= Y - R
W
W
#Python/Numpy has a vast amount of built in functions, for example
max(10, 2, 100, -3)
9)
np.sqrt(abs(-13)
#you can find out more about these by using the help function,
#e.g.: help(max)
#How can you delete stuff? Use the del function
#for individual objects
del Y, C, I, R
#You can also assign text (a string) to a variable
= 'Reggaeton'
text1 = "Bad Bunny"
text2 print(text1 + ' ' + text2)
#Python uses standard operators like +, -, *
#for exponents use **
3**2
########################### if statements and loops ######################
#sometimes we need to introduce if conditions into our code
#The syntax is
#if condition xxx:
#do something
= 10
a = 13
b if b > a:
print("b is bigger")
#we can also define what to do in case the condition is not fulfilled
= 10
b if b > a:
print("b is bigger")
else:
print("b not bigger")
#Next we will look at loops which are a key tool to repeat tasks such as solving
#a theoretical model to find its equilibrium.
#The basic structure is:
for i in range(1, 6):
print(i)
# Note the key role played by indentation!
#Let's use it to solve a simple Keynesian cross model of the form
#Y=C+I
#C=c0+c1Y
#Define exogenous parameters and initialise endogenous variables
= 2
c0 = 0.8
c1 = 10
I = C = 1
Y
#Use a for loop that iterates the equations 100 times to solve them
for i in range(1, 100):
= C + I
Y = c0 + c1 * Y
C
Y#correct solution is Y=(I+c0)/(1-c1)=60
#The loop uses the values from the previous iteration
#to calculate the values of the next, because it starts with assigning a value
#to Y and then uses that value to assign a new value to C, and in the next
# iteration it uses this new value for C to define a new value for Y etc.
########################### Data structures ##########################
#In most applications we produce outputs which do not consist of a single number.
#Often we have an entire stream of results, or we want to analyse data and have
# to store larger amounts of data.
# Python/Numpy has a variety of data structures for this purpose.
### Vectors
#We can create an vector of size 3 with only zeros and fill it later
# (with results of our model for example). Importantly, unlike R, Python starts
# counting the elements in vector at 0 rather than 1
= np.zeros((3))
vec1 #we can define vectors explicitly
= np.array([1, 2, 3])
vec2 = np.array([6, 7, 8])
vec3 #we can also use the sequence operator
= np.arange(1, 11)
vec4 #and we can define the step size
= np.arange(1, 2, 0.1)
vec5 #we can call specific entries using square brackets -- note how Python starts
# counting at 0
2]
vec2[#if we want to access more elements at once
0:3]
vec2[
### Matrices
#define a matrix: 3 rows and 2 columns, all elements equal to 0
= np.zeros((3, 2))
mat1 #we can also fill it with specific values
= np.array([[1, 2], [3, 4], [5, 6]])
mat2
#access specific elements (columns,rows)
2, 0]
mat2[#access entire rows or columns
0]
mat2[:,
## Combine two column vectors in a matrix
= np.column_stack((vec1, vec2))
mat3 ## Combine two row vectors in a matrix
= np.row_stack((vec1, vec2)) mat4
Simple exercise
If you further want to practice your coding skills, attempt the following exercises:
- Write a loop which calculates the running sum of \(x_i=\frac{1}{i^2}\) by saving each element \(\sum_{i=1}^{j}x_i\) in a vector (where \(j=1,2,..,10\)).
If your code is correct, you should get the solution:
[1] 1.000000 1.250000 1.361111 1.423611 1.463611 1.491389 1.511797 1.527422
[9] 1.539768 1.549768
- Write a loop which calculates the running sums of \(x_i=\frac{1}{i^2}\) (as in exercise 1) and in addition also \(y_i=\frac{1}{i^3}\). Combine the results in a matrix.
If your code is correct, you should get the solution:
x y
[1,] 1.000000 1.000000
[2,] 1.250000 1.125000
[3,] 1.361111 1.162037
[4,] 1.423611 1.177662
[5,] 1.463611 1.185662
[6,] 1.491389 1.190292
[7,] 1.511797 1.193207
[8,] 1.527422 1.195160
[9,] 1.539768 1.196532
[10,] 1.549768 1.197532