Julia Basics

Motivation

  • We want to understand what Julia code does.
  • We want to write useful prompts based on an understanding of Julia’s distinctive features.
Learning Goals
  • Read and write basic Julia syntax.
  • Understand how Julia differs from other programming languages.
Remarks
  • This lecture does not cover every detail of Julia’s syntax because I assume that you already know basic programming concepts.
  • Instead, it focuses on the features that distinguish Julia from other languages.
  • Please ask questions during the lecture or hands-on session.

Environment Setup

File Types

  • .jl files
    • A .jl file is a plain-text Julia source file.
    • Use .jl files for scripts, modules, and packages.
    • Run a .jl file from the terminal with: julia filename.jl.
  • .qmd files
    • A .qmd file is a Quarto document that combines Markdown text, executable Julia code, and rendered output.
    • This document is written as a .qmd file.
    • Quarto can render .qmd files to HTML, PDF, or Word.
    • This format is useful for inspecting results and sharing them with coauthors.
      • HTML output provides clear rendering for mathematics, figures, and tables.

Key Features of Julia

  • Julia code is often concise and readable. Julia also compiles functions to machine code, which can make numerical programs fast.
  • A function can have several versions, called methods, for different kinds of input. Julia automatically chooses the appropriate method from the types of all arguments; this is called multiple dispatch.
  • You can define new types and add methods that make existing functions work with them, without changing the original functions.
  • Much of Julia’s standard functionality is implemented in Julia itself, which makes the implementation easier to inspect and extend.
  • Julia has a broad ecosystem for scientific and numerical computing.

Basics

Variables

  • Assigning a value binds a name to that value.
  • Multiple assignment binds several names at once, and += updates a binding.
x = 10
println(x)

a, b, c = 1, 2, 3

x += 1
println(x)
10
11
  • Rebinding y changes only y; it does not change z.
y = z = 5
println(y, z)

y += 1
println(y, z)
55
65
  • Julia allows Unicode identifiers. This can make mathematical code close to notation in papers, but use it sparingly.
β = 0.95
println(β)

こんにちは = "Hello"
println(こんにちは)

👍 = "It's all good."
println(👍)
0.95
Hello
It's all good.

Numbers

  • The Bool type has two values: true and false.
println(true)
println(false)
println(typeof(true))
true
false
Bool
  • Because Bool is a subtype of Integer, arithmetic treats true as one and false as zero.
println(Bool <: Integer)
println(true + true)
println(3 * false)
true
2
0
  • Int usually means the native machine integer type. On most current machines this is Int64; use the default unless you have a specific reason to control memory layout or external compatibility.
println(Sys.WORD_SIZE)
println(typeof(1))
64
Int64
  • Use typemax to see the largest integer value. The exponent after 10^ gives the order of magnitude.
integer_order10(T) = floor(Int, log10(Float64(typemax(T))))

for T in [Int16, Int32, Int64]
    println("$(rpad(string(T), 5)): max = $(typemax(T)), about 10^$(integer_order10(T))")
end
Int16: max = 32767, about 10^4
Int32: max = 2147483647, about 10^9
Int64: max = 9223372036854775807, about 10^18
  • Float16, Float32, and Float64 use increasing storage and provide increasing range and precision. Decimal literals use Float64 by default.
println(sizeof(Float16))
println(sizeof(Float32))
println(sizeof(Float64))
println(typeof(1.0))
2
4
8
Float64
  • For floating-point numbers, floatmin gives the smallest positive normal value. This tells us how small a positive number can be before underflow becomes a concern.
small_float_order10(T) = floor(Int, log10(Float64(floatmin(T))))

for T in [Float16, Float32, Float64]
    println("$(rpad(string(T), 7)): smallest normal = $(floatmin(T)), about 10^$(small_float_order10(T))")
end
Float16: smallest normal = 6.104e-5, about 10^-5
Float32: smallest normal = 1.1754944e-38, about 10^-38
Float64: smallest normal = 2.2250738585072014e-308, about 10^-308
Tip
  • As a rule of thumb, use Int and Float64 by default.
  • Consider smaller fixed-width integer or floating-point types when reducing memory use or computation time is important, or when an external format requires a specific type.
  • Julia represents familiar mathematical constants as Irrational values and converts them to concrete floating-point types when needed.
println(π)
println(ℯ)
println(Base.MathConstants.golden)
println(Base.MathConstants.eulergamma)
println(typeof(π))
println(Float64(π))
π
ℯ
φ
γ
Irrational{:π}
3.141592653589793

Arithmetic

  • Julia supports the usual arithmetic operators and standard elementary functions.
println(1 + 2 + 3)
println(3 * 2 / 12)
println(2^3)
println(10 % 3)
println(log(exp(1)))
6
0.5
8
1
1.0
  • Exponentiation is evaluated before multiplication and division, which are evaluated before addition and subtraction. Parentheses override this order.
println(2 + 3 * 4)
println((2 + 3) * 4)
println(2 * 3^2)
println((2 * 3)^2)
14
20
18
36
  • Numeric literal coefficients let you write simple formulas without explicit *.
x = 3
println(2x^2 - 3x + 1)
println(2(x - 1)^2 - 3(x - 1) + 1)
10
3
  • Comparisons can be chained, which is useful in numerical code.
println(1 < 2 <= 2 < 3)

x = [0.2, 1.4, -0.1]
println(0 .< x .< 1)
true
Bool[1, 0, 0]

Collections

  • A tuple is a fixed-length, immutable collection. Access an unnamed tuple by position.
coordinates = (3.0, 4.0)
println(coordinates)
println(coordinates[1])
(3.0, 4.0)
3.0
  • A named tuple assigns a name to each element, making small collections of related values easier to read.
estimate = (coefficient = 1.2, standard_error = 0.3)
println(estimate)
println(estimate.coefficient)
(coefficient = 1.2, standard_error = 0.3)
1.2
  • A range represents an evenly spaced sequence without storing every value as a separate element.
  • Use collect when you need to materialize a range as a vector.
years = 2020:2024
println(years)
println(collect(years))

grid = range(0.0, 1.0, length = 5)
println(grid)
println(collect(grid))
2020:2024
[2020, 2021, 2022, 2023, 2024]
0.0:0.25:1.0
[0.0, 0.25, 0.5, 0.75, 1.0]
  • Functions ending in ! conventionally modify one or more of their arguments.
  • Use push! and pushfirst! to add one element, and append! and prepend! to add the elements of another collection.
  • Use pop! and popfirst! to remove and return an element.
values = [2, 3]
pushfirst!(values, 1)
push!(values, 4)
append!(values, [5, 6])
prepend!(values, [-1, 0])
println(values)

first_value = popfirst!(values)
last_value = pop!(values)
println("Removed first: ", first_value)
println("Removed last: ", last_value)
println(values)
[-1, 0, 1, 2, 3, 4, 5, 6]
Removed first: -1
Removed last: 6
[0, 1, 2, 3, 4, 5]
  • A dictionary stores key-value pairs. Access a value by its key rather than by its position.
prices = Dict("apple" => 2.00, "banana" => 1.25)
prices["orange"] = 1.50
println(prices["apple"])
println(haskey(prices, "orange"))
2.0
true
  • A set stores unique values and is useful for membership tests and removing duplicates.
categories = Set(["micro", "macro", "micro"])
push!(categories, "econometrics")
println(categories)
println("macro" in categories)
Set(["macro", "micro", "econometrics"])
true
  • An array comprehension constructs an array, whereas a generator produces values as they are needed.
squares = [number^2 for number in 1:5]
square_generator = (number^2 for number in 1:5)
println(squares)
println(collect(square_generator))
[1, 4, 9, 16, 25]
[1, 4, 9, 16, 25]
  • Iterators.product creates a Cartesian product. Its elements can be destructured while iterating.
cartesian_pairs = Iterators.product(1:2, ["A", "B"])

for (number, letter) in cartesian_pairs
    println("number = ", number, ", letter = ", letter)
end
number = 1, letter = A
number = 2, letter = A
number = 1, letter = B
number = 2, letter = B
  • Iterate directly when you need each value, use eachindex when you need valid indices, and use enumerate when you need both positions and values.
values = [10, 20, 30]

for value in values
    println("value = ", value)
end

for index in eachindex(values)
    println("index = ", index, ", value = ", values[index])
end

for (position, value) in enumerate(values)
    println("position = ", position, ", value = ", value)
end
value = 10
value = 20
value = 30
index = 1, value = 10
index = 2, value = 20
index = 3, value = 30
position = 1, value = 10
position = 2, value = 20
position = 3, value = 30
  • Use findall, findfirst, and findlast to locate elements that satisfy a condition.
  • Use findmin and findmax to obtain an extreme value and its index, or argmin and argmax when only the index is needed.
values = [1.2, -0.3, 2.1, -1.0]
negative_mask = values .< 0
println(findall(negative_mask))
println(findfirst(negative_mask))
println(findlast(negative_mask))

minimum_value, minimum_index = findmin(values)
maximum_value, maximum_index = findmax(values)
println("minimum = ", minimum_value, ", index = ", minimum_index)
println("maximum = ", maximum_value, ", index = ", maximum_index)
println("argmin = ", argmin(values))
println("argmax = ", argmax(values))
[2, 4]
2
4
minimum = -1.0, index = 4
maximum = 2.1, index = 3
argmin = 4
argmax = 3
  • For sorted collections, searchsorted returns the full matching index range, while searchsortedfirst and searchsortedlast return its boundaries.
sorted_values = [1, 2, 2, 2, 4, 7]
println(searchsorted(sorted_values, 2))
println(searchsortedfirst(sorted_values, 2))
println(searchsortedlast(sorted_values, 2))
2:4
2
4
  • filter, map, and unique select, transform, and deduplicate elements.
  • fill constructs an array with repeated values, while cumsum and cumprod compute cumulative results.
values = [1, 2, 2, 3, 4]
println(filter(isodd, values))
println(map(log, values))
println(unique(values))
println(fill(0.0, 3))
println(cumsum(values))
println(cumprod(1:5))
[1, 3]
[0.0, 0.6931471805599453, 0.6931471805599453, 1.0986122886681098, 1.3862943611198906]
[1, 2, 3, 4]
[0.0, 0.0, 0.0]
[1, 3, 5, 8, 12]
[1, 2, 6, 24, 120]
  • Assignment is not the same as copying. For mutable objects such as arrays, two names can refer to the same object.
a = [1, 2, 3]
b = a
a[1] = 42
println(b)
[42, 2, 3]
  • copy creates a shallow copy, so nested mutable objects are still shared.
  • deepcopy recursively copies nested mutable objects.
original = [[1, 2], [3, 4]]
shallow_copy = copy(original)
deep_copy = deepcopy(original)

original[1][1] = 42
println(shallow_copy)
println(deep_copy)
[[42, 2], [3, 4]]
[[1, 2], [3, 4]]
Tips
  • Use arrays for most numerical calculations.
  • Tuples and named tuples are useful for small, fixed collections, especially for returning multiple related values from a function.
  • When working with CSV data, it is often convenient to read it into a DataFrame, prepare the data there, and convert the variables needed for estimation into arrays.
  • A named tuple can provide a lightweight return value when an estimation routine produces a small, fixed set of results.

Missing Values

  • missing represents a value that is unknown or not observed.
  • Most operations propagate missing. Use ismissing to test for it and skipmissing to iterate over the observed values.
values_with_missing = [1.0, missing, 3.0]
println(missing + 1)
println(ismissing(values_with_missing[2]))
println(collect(skipmissing(values_with_missing)))
missing
true
[1.0, 3.0]
  • CSV and DataFrames commonly represent blank entries with missing.

Working with Arrays

Shapes and Construction

  • An array is a mutable collection whose elements can be accessed by index.
  • A one-dimensional array is a vector, a two-dimensional array is a matrix, and an array can have three or more dimensions.
values = [10, 20, 30]
matrix = [1 2; 3 4]
array_3d = zeros(2, 3, 4)

println(values)
println(matrix)
println(ndims(array_3d))
println(size(array_3d))
println(length(array_3d))
[10, 20, 30]
[1 2; 3 4]
3
(2, 3, 4)
24
  • zeros creates an initialized array of zeros.
  • similar creates an uninitialized array with the same element type and shape by default, so assign values before reading it.
matrix = zeros(2, 3)
workspace = similar(matrix)
fill!(workspace, 1.0)
println(matrix)
println(workspace)
[0.0 0.0 0.0; 0.0 0.0 0.0]
[1.0 1.0 1.0; 1.0 1.0 1.0]

Concatenation and Repetition

  • vcat concatenates arrays along the first dimension, while hcat concatenates them along the second dimension.
top_row = [1 2]
bottom_row = [3 4]
println(vcat(top_row, bottom_row))

left_column = [1, 3]
right_column = [2, 4]
println(hcat(left_column, right_column))
[1 2; 3 4]
[1 2; 3 4]
  • repeat repeats an array a specified number of times along each dimension.
block = [1 2]
println(repeat(block, 2, 1))
println(repeat(block, 1, 2))
[1 2; 1 2]
[1 2 1 2]

Multidimensional Indexing

  • Julia uses one-based indexing, and array elements can be changed after the array is created.
values = [10, 20, 30]
println(values[1])

values[2] = 25
println(values)
10
[10, 25, 30]
  • Use one index per dimension, and use : to select all indices along a dimension.
  • A multidimensional array also supports linear indexing in column-major order, so the first index changes fastest.
matrix = reshape(collect(1:6), 2, 3)
println(matrix)
println(matrix[2, 2])
println(matrix[4])
println(matrix[:, 2])
println(matrix[1, 2:end])
[1 3 5; 2 4 6]
4
4
[3, 4]
[3, 5]

Broadcasting and Fusion

  • Dot operators apply operations element by element. This is central for array code.
X = [1, 2, 3]
println(X .^ 3)
[1, 8, 27]
  • Broadcasting combines scalars and arrays, as well as arrays with compatible shapes.
column = [10, 20]
row = [1 2 3]
println(column .+ row)
[11 12 13; 21 22 23]
  • Nested dot operations fuse into a single loop without allocating temporary arrays for intermediate results.
  • @. adds dots to the operations in an expression, and its assignment writes the result into the existing array.
values = [1.0, 2.0, 3.0]
result = similar(values)
@. result = 3 * values^2 + 2 * values + 1
println(result)
[6.0, 17.0, 34.0]
Tips
  • Use dotted operations for element-wise calculations. Julia fuses consecutive dotted operations into a single loop, which usually avoids intermediate arrays.
  • Unlike the traditional performance advice for MATLAB or R, Julia code does not need to be vectorized solely for speed. Explicit loops are also efficient.

Boolean Masks

  • Boolean broadcasting often returns a compact BitArray, such as a BitVector, which can be used as an indexing mask.
values = [-1, 2, 3]
mask = values .> 0
println(mask)
println(typeof(mask))
println(values[mask])
Bool[0, 1, 1]
BitVector
[2, 3]

Control Flow

  • The pipe operator |> passes the value on its left to the function on its right.
result = [1, 2, 3] |> sum |> sqrt
println(result)
2.449489742783178
  • Short-circuit evaluation runs the right side of && or || only when it is needed.
value = 4
value > 0 && println("positive")
value < 0 || println("not negative")
positive
not negative
  • The conditional operator condition ? x : y selects one of two values.
value = 3
parity = iseven(value) ? "even" : "odd"
println(parity)
odd
  • An if statement runs different blocks according to a condition.
value = -2

if value > 0
    println("positive")
elseif value < 0
    println("negative")
else
    println("zero")
end
negative
  • A while loop repeats while its condition remains true.
let counter = 1
    while counter <= 3
        println(counter)
        counter += 1
    end
end
1
2
3
  • A for loop iterates over the elements of a collection.
for number in 1:3
    println(number)
end
1
2
3
  • continue skips the rest of the current iteration.
for number in 1:5
    if iseven(number)
        continue
    end
    println(number)
end
1
3
5
  • break exits a loop immediately.
for number in 1:5
    if number == 3
        break
    end
    println(number)
end
1
2
  • A try block runs code that may fail, and catch handles an exception.
  • A finally block runs whether or not an exception occurs.
try
    parse(Int, "not a number")
catch error
    println(typeof(error))
finally
    println("The attempt is complete.")
end
ArgumentError
The attempt is complete.

Functions

  • Define a function with function and end. Arguments are local bindings inside the function.
function square(number)
    return number^2
end

println(square(4))
16
  • A variadic argument followed by ... accepts any number of positional arguments.
function add_all(numbers...)
    return sum(numbers)
end

println(add_all(1, 2, 3))
6
  • An optional positional argument has a default value and can be replaced by its position.
raise_to_power(base, exponent = 2) = base^exponent
println(raise_to_power(3))
println(raise_to_power(3, 3))
9
27
  • A keyword argument follows ; and is passed by name.
scale(value; factor = 2) = value * factor
println(scale(3))
println(scale(3; factor = 4))
6
12
  • An anonymous function defines a function without giving it a name in the definition.
double = number -> 2 * number
println(double(4))
8

Scope

  • Code at the top level of a file or module is in global scope.
  • A global const binding should not be reassigned after it is defined.
global_value = 10
const DISCOUNT_FACTOR = 0.95
println(global_value)
println(DISCOUNT_FACTOR)
10
0.95
  • A let block creates a local scope. A binding created there does not replace a binding with the same name outside the block.
value = 10

let value = 20
    println(value)
end

println(value)
20
10
  • Most block constructs in Julia create a new local scope.
  • if, begin, and the ifelse function do not create a new local scope.
scope_value = 1

if true
    scope_value = 2
end

begin
    scope_value = ifelse(true, 3, 4)
end

println(scope_value)
3
  • A module does not create a local scope; it creates a separate global scope.
module ExampleModule
    message = "Hello from the module"
end

println(ExampleModule.message)
Hello from the module

Types

Values and Types

  • Every value in Julia has a type. Use typeof to inspect its concrete type.
println(typeof(1))
println(typeof(1.0))
Int64
Float64

Type Declarations

  • A type declaration uses :: to require a variable to contain a value of a particular type.
observation_count::Int = 100
println(observation_count)
100
  • A function argument can include a type declaration.
double_integer(value::Int) = 2 * value
println(double_integer(4))
8
  • Calling the function with a value that does not match the declared argument type raises an error because Julia cannot find a matching method.
try
    double_integer(4.0)
catch error
    println(typeof(error))
end
MethodError

Type Hierarchy

  • Concrete types represent specific kinds of values, while abstract types group related types in a hierarchy.
  • Use <: to test a subtype relationship and isa to test whether a value belongs to a type.
flowchart TD
    Any --> Number
    Number --> Real
    Number --> ComplexT["Complex{T}"]
    Real --> Integer
    Real --> AbstractFloat
    Real --> RationalT["Rational{T}"]
    Integer --> Bool
    Integer --> Signed
    Integer --> Unsigned
    Signed --> SignedIntegers["Int8, Int16, Int32, Int64, Int128, BigInt"]
    Unsigned --> UnsignedIntegers["UInt8, UInt16, UInt32, UInt64, UInt128"]
    AbstractFloat --> FloatingTypes["Float16, Float32, Float64, BigFloat"]

flowchart TD
    Any --> Number
    Number --> Real
    Number --> ComplexT["Complex{T}"]
    Real --> Integer
    Real --> AbstractFloat
    Real --> RationalT["Rational{T}"]
    Integer --> Bool
    Integer --> Signed
    Integer --> Unsigned
    Signed --> SignedIntegers["Int8, Int16, Int32, Int64, Int128, BigInt"]
    Unsigned --> UnsignedIntegers["UInt8, UInt16, UInt32, UInt64, UInt128"]
    AbstractFloat --> FloatingTypes["Float16, Float32, Float64, BigFloat"]

println(Int <: Integer)
println(Integer <: Real)
println(1 isa Integer)
true
true
true

Composite Types

  • A struct defines an immutable composite type with named fields.
struct Observation
    value::Float64
end

observation = Observation(1.5)
println(observation.value)
1.5

Multiple Dispatch

  • A generic function can have multiple methods. Each method defines behavior for a particular combination of argument types.
combine(left::Integer, right::Integer) = left + right
combine(left::AbstractString, right::AbstractString) = left * right
combine (generic function with 2 methods)
  • When the generic function is called, Julia uses the types of all positional arguments to select a matching method.
println(combine(2, 3))
println(combine("Julia", "!"))
5
Julia!
  • Multiple dispatch makes code extensible because a new method can support another combination of types without changing existing methods.
combine(times::Integer, text::AbstractString) = repeat(text, times)

println(combine(3, "ha"))
println(combine(2, 3))
hahaha
5

Modules

  • A module creates a namespace for related definitions.
  • Define a module with module and end, and use export to identify names intended for users.
module ExampleTools
    export double_value

    double_value(value) = 2 * value
    triple_value(value) = 3 * value
end
Main.Notebook.ExampleTools
  • using loads a module and makes its exported names available without qualification.
using .ExampleTools
println(double_value(4))
8
  • import can bring a specific name into scope explicitly.
import .ExampleTools: triple_value
println(triple_value(4))
12

Useful Macros

  • A macro transforms a Julia expression before it is evaluated. Macro calls begin with @.
  • @show prints both an expression and its value, which is useful for inspecting intermediate results.
value = 3
@show value^2
value ^ 2 = 9
9
  • @assert checks that a condition is true and throws an error when it is false.
value = 3
@assert value > 0
println("The condition holds.")
The condition holds.
  • @time provides a quick measurement of elapsed time and memory allocation.
  • The first call may include compilation time, so @time is best used as an initial check rather than a comprehensive benchmark.
values = rand(100_000)
@time sum(values)
  0.011378 seconds (65.96 k allocations: 3.217 MiB, 99.60% compilation time)
49912.53994794804
  • For more systematic and repeatable performance measurement, use BenchmarkTools.jl, which will be introduced in a later lecture.

Packages and Environments

Project Environment

  • A project environment defines the packages and versions used by one project.
  • After cloning a repository, run the following command from the project directory.
julia --project=. -e 'using Pkg; Pkg.instantiate()'
  • The command activates the project and installs the package versions recorded for that environment.

  • Julia manages the environment with the two files below. Package operations create or update them; in a cloned project, they are normally already present.

  • Project.toml

    • Declares the project’s direct dependencies and compatibility requirements.
    • The [deps] table maps package names to unique UUIDs, while [compat] states allowed versions for Julia and packages.
[deps]
CSV = "336ed68f-0bac-5ca0-87d4-7b16caf5d00b"
DataFrames = "a93c6f00-e57d-5684-b7b6-d8193f3e46c0"

[compat]
julia = "=1.12.6"
  • Manifest.toml
    • Acts as a machine-generated lockfile for all direct and indirect dependencies, allowing the environment to be reproduced with exact versions.
    • The header identifies the Julia and manifest versions, while each [[deps.PackageName]] table records dependencies, a UUID, a source hash, and a version when applicable.
julia_version = "1.12.6"
manifest_format = "2.0"

[[deps.DataStructures]]
deps = ["OrderedCollections"]
git-tree-sha1 = "6fb53a69613a0b2b68a0d12671717d307ab8b24e"
uuid = "864edb3b-99cc-5e75-8d2d-829cb0a9cfe8"
version = "0.19.5"

Packages

  • Standard libraries such as Random, LinearAlgebra, and Statistics ship with Julia.
  • External packages such as Distributions, CSV, DataFrames, Optim, and Plots are installed in the project environment.
  • Load either kind with using.

Random

  • Random provides reproducible random-number generation.
using Random

Random.seed!(1234)
println(rand(3))
println(randn(3))
[0.32597672886359486, 0.5490511363155669, 0.21858665481883066]
[0.7189099374659392, 0.4202471777937789, -0.685670902276119]

LinearAlgebra

  • LinearAlgebra provides matrix operations, linear solves, and norms.
  • The least-squares estimate is \(\hat{\beta} = \operatorname*{arg\,min}_{\beta} \lVert y - X\beta \rVert_2^2\).
  • For this dense rectangular matrix, X \ y uses a QR factorization with column pivoting to solve the least-squares problem.
using LinearAlgebra

X = [1.0 1.0; 1.0 2.0; 1.0 3.0]
y = [1.0, 2.0, 2.0]
beta_hat = X \ y
println(beta_hat)
[0.6666666666666667, 0.49999999999999983]

Statistics

  • Statistics provides common summary statistics.
using Statistics

values = [1.0, 2.0, 3.0, 4.0]
println(mean(values))
println(std(values))
2.5
1.2909944487358056

Distributions

  • Distributions provides objects for common probability distributions.
  • Normal() creates a standard normal distribution, and quantile evaluates its inverse cumulative distribution function (inverse CDF).
using Distributions

standard_normal = Normal()
println(mean(standard_normal))
println(std(standard_normal))
println(quantile(standard_normal, 0.95))
0.0
1.0
1.6448536269514717

CSV and DataFrames

  • CSV reads tabular data, and DataFrames provides tools for inspecting and transforming it.
using CSV
using DataFrames

csv_data = IOBuffer("y,x\n1.0,2.0\n,3.0\n")
data = CSV.read(csv_data, DataFrame)
println(data)
println(dropmissing(data))
2×2 DataFrame
 Row │ y          x
     │ Float64?   Float64
─────┼────────────────────
   1 │       1.0      2.0
   2 │ missing        3.0
1×2 DataFrame
 Row │ y        x
     │ Float64  Float64
─────┼──────────────────
   1 │     1.0      2.0

Optim

  • Optim minimizes objective functions and reports the solution and objective value.
  • With only an objective function and an initial vector, optimize uses the derivative-free NelderMead() method by default.
  • Pass another method as the third argument to use alternatives such as BFGS(), LBFGS(), ConjugateGradient(), GradientDescent(), or SimulatedAnnealing().
using Optim

objective(parameters) = (parameters[1] - 2.0)^2
optimization_result = optimize(objective, [0.0])
println(Optim.minimizer(optimization_result))
println(Optim.minimum(optimization_result))
[1.9999755859375008]
5.96046447714875e-10

Plots

  • Plots creates figures from vectors and other data.
using Plots

x_values = 1:3
y_values = [1.0, 2.0, 1.5]
plot(x_values, y_values; marker = :circle, label = "series")

Short demo: OLS

  • This example begins with a small OLS calculation and then estimates the same model with simulated data.

Small OLS Example

  • Let X contain an intercept and one regressor, and let Y contain the outcome.
  • The textbook OLS estimator is \(\hat{\beta} = (X^\top X)^{-1}X^\top Y\).
  • This expression assumes that \(X^\top X\) is invertible.
using LinearAlgebra

X = [1.0 1.0; 1.0 2.0; 1.0 3.0]
Y = [2.0, 3.0, 4.0]
display(X)
display(Y)
3×2 Matrix{Float64}:
 1.0  1.0
 1.0  2.0
 1.0  3.0
3-element Vector{Float64}:
 2.0
 3.0
 4.0
  • Calculate the OLS estimates in the next cell.
beta_hat = inv(X' * X) * X' * Y
beta_hat
2-element Vector{Float64}:
 0.9999999999999987
 1.0

Simulated OLS Data

  • The simulated model is \(Y_i = \beta_0 + \beta_1 x_i + \varepsilon_i\).
  • Set both true coefficients to one and generate 10,000 observations.
true_coefficients = [1.0, 1.0]
number_of_observations = 10_000
println(
    "True coefficients: ", true_coefficients,
    "\nNumber of observations: ", number_of_observations,
)
True coefficients: [1.0, 1.0]
Number of observations: 10000

Generate Random Draws

  • First, define a function that generates a matrix of independent \(U(0,1)\) random variables.
  • Each row is an observation. The first column provides draws for the regressor, and the second provides draws for the error term.
using Random

generate_random_draws(number_of_observations) = rand(number_of_observations, 2)
generate_random_draws (generic function with 1 method)
  • Call the function once and display the first 10 rows as a matrix.
Random.seed!(1234)

random_draws = generate_random_draws(number_of_observations)
random_draws[1:10, :]
10×2 Matrix{Float64}:
 0.579862   0.393008
 0.411294   0.425278
 0.972136   0.529091
 0.0149088  0.620936
 0.520355   0.997118
 0.639562   0.831362
 0.839622   0.402862
 0.967143   0.422051
 0.789764   0.0131283
 0.696041   0.454826

Generate Data

  • OLSData stores only the observed outcome vector Y and design matrix X.
struct OLSData
    Y::Vector{Float64}
    X::Matrix{Float64}
end
  • Next, define a function that receives the random-draw matrix.
  • Rescale the first column from \(U(0,1)\) to \(U(-1,1)\) with \(x_{1i} = 2u_i - 1\).
  • The inverse standard normal CDF transforms the second column into the unobserved error term: \(\varepsilon_i = \Phi^{-1}(u_i)\).
  • The design matrix adds an intercept to x1 before generating Y.
using Distributions

function generate_data(coefficients, random_draws)
    x1 = 2 .* random_draws[:, 1] .- 1
    X = hcat(ones(size(random_draws, 1)), x1)
    Y = X * coefficients + quantile.(Normal(), random_draws[:, 2])
    return OLSData(Y, X)
end
generate_data (generic function with 1 method)
  • Run the function with the true coefficients and the random draws.
ols_data = generate_data(true_coefficients, random_draws)

println("First rows of X:\n", ols_data.X[1:3, :])
println("First values of Y: ", ols_data.Y[1:3])
First rows of X:
[1.0 0.15972424026826482; 1.0 -0.17741176410029902; 1.0 0.9442721649109374]
First values of Y: [0.8882354479530992, 0.6341801994381832, 2.01725629117784]

Estimate OLS

  • Define the OLS estimator using the textbook formula.
estimate_ols(data) = inv(data.X' * data.X) * data.X' * data.Y
estimate_ols (generic function with 1 method)
  • Apply the function to the simulated data.
beta_hat = estimate_ols(ols_data)
println(
    "True coefficients: ", true_coefficients,
    "\nOLS estimates: ", beta_hat,
)
True coefficients: [1.0, 1.0]
OLS estimates: [0.9920844176999882, 0.9857650774480333]
  • The OLS estimates should be close to the true coefficients in this simulated sample.

Mean Squared Error

  • The mean squared error is \(Q(b) = N^{-1}\sum_{i=1}^N (Y_i - X_i^\top b)^2\).
  • Define a function that evaluates this objective at any proposed coefficients.
using Statistics

mean_squared_error(coefficients, data) = mean((data.Y - data.X * coefficients) .^ 2)
mean_squared_error (generic function with 1 method)

Objective Surface

  • Evaluate the objective around the true intercept and slope.
using Plots

intercept_values = range(0.5, 1.5; length = 50)
slope_values = range(0.5, 1.5; length = 50)
mse_values = [
    mean_squared_error([intercept, slope], ols_data)
    for slope in slope_values, intercept in intercept_values
]

objective_plot = contour(
    intercept_values,
    slope_values,
    mse_values;
    xlabel = "β₀",
    ylabel = "β₁",
    title = "Mean squared error",
    fill = true,
)
scatter!(
    objective_plot,
    [true_coefficients[1]],
    [true_coefficients[2]];
    label = "True coefficients",
    markershape = :circle,
)
scatter!(
    objective_plot,
    [beta_hat[1]],
    [beta_hat[2]];
    label = "OLS estimate",
    markershape = :star5,
)
objective_plot
  • The OLS estimate is the minimum of the plotted objective, while the true coefficients are nearby in this finite sample.

Numerical Optimization

  • Optim can minimize the same objective numerically.
  • The anonymous function passes each proposed coefficient vector to mean_squared_error.
using Optim

optimization_result = Optim.optimize(
    coefficients -> mean_squared_error(coefficients, ols_data),
    [0.0, 0.0],
)
optimized_coefficients = Optim.minimizer(optimization_result)

println(
    "True coefficients: ", true_coefficients,
    "\nOLS estimates: ", beta_hat,
    "\nOptim estimates: ", optimized_coefficients,
)
True coefficients: [1.0, 1.0]
OLS estimates: [0.9920844176999882, 0.9857650774480333]
Optim estimates: [0.9921027878748632, 0.985814997892541]
  • The analytical OLS estimates and the numerical Optim estimates should be nearly identical.

Reference

  • https://docs.julialang.org/en/v1/