x = 10
println(x)
a, b, c = 1, 2, 3
x += 1
println(x)10
11
+= updates a binding.x = 10
println(x)
a, b, c = 1, 2, 3
x += 1
println(x)10
11
y changes only y; it does not change z.y = z = 5
println(y, z)
y += 1
println(y, z)55
65
β = 0.95
println(β)
こんにちは = "Hello"
println(こんにちは)
👍 = "It's all good."
println(👍)0.95
Hello
It's all good.
Bool type has two values: true and false.println(true)
println(false)
println(typeof(true))true
false
Bool
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
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))")
endInt16: 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
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))")
endFloat16: 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
Int and Float64 by default.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
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
println(2 + 3 * 4)
println((2 + 3) * 4)
println(2 * 3^2)
println((2 * 3)^2)14
20
18
36
*.x = 3
println(2x^2 - 3x + 1)
println(2(x - 1)^2 - 3(x - 1) + 1)10
3
println(1 < 2 <= 2 < 3)
x = [0.2, 1.4, -0.1]
println(0 .< x .< 1)true
Bool[1, 0, 0]
coordinates = (3.0, 4.0)
println(coordinates)
println(coordinates[1])(3.0, 4.0)
3.0
estimate = (coefficient = 1.2, standard_error = 0.3)
println(estimate)
println(estimate.coefficient)(coefficient = 1.2, standard_error = 0.3)
1.2
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]
! conventionally modify one or more of their arguments.push! and pushfirst! to add one element, and append! and prepend! to add the elements of another collection.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]
prices = Dict("apple" => 2.00, "banana" => 1.25)
prices["orange"] = 1.50
println(prices["apple"])
println(haskey(prices, "orange"))2.0
true
categories = Set(["micro", "macro", "micro"])
push!(categories, "econometrics")
println(categories)
println("macro" in categories)Set(["macro", "micro", "econometrics"])
true
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)
endnumber = 1, letter = A
number = 2, letter = A
number = 1, letter = B
number = 2, letter = B
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)
endvalue = 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
findall, findfirst, and findlast to locate elements that satisfy a condition.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
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]
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]]
missing represents a value that is unknown or not observed.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]
missing.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]
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]
values = [10, 20, 30]
println(values[1])
values[2] = 25
println(values)10
[10, 25, 30]
: to select all indices along a dimension.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]
X = [1, 2, 3]
println(X .^ 3)[1, 8, 27]
column = [10, 20]
row = [1 2 3]
println(column .+ row)[11 12 13; 21 22 23]
@. 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]
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]
|> passes the value on its left to the function on its right.result = [1, 2, 3] |> sum |> sqrt
println(result)2.449489742783178
&& or || only when it is needed.value = 4
value > 0 && println("positive")
value < 0 || println("not negative")positive
not negative
condition ? x : y selects one of two values.value = 3
parity = iseven(value) ? "even" : "odd"
println(parity)odd
if statement runs different blocks according to a condition.value = -2
if value > 0
println("positive")
elseif value < 0
println("negative")
else
println("zero")
endnegative
while loop repeats while its condition remains true.let counter = 1
while counter <= 3
println(counter)
counter += 1
end
end1
2
3
for loop iterates over the elements of a collection.for number in 1:3
println(number)
end1
2
3
continue skips the rest of the current iteration.for number in 1:5
if iseven(number)
continue
end
println(number)
end1
3
5
break exits a loop immediately.for number in 1:5
if number == 3
break
end
println(number)
end1
2
try block runs code that may fail, and catch handles an exception.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.")
endArgumentError
The attempt is complete.
function and end. Arguments are local bindings inside the function.function square(number)
return number^2
end
println(square(4))16
... accepts any number of positional arguments.function add_all(numbers...)
return sum(numbers)
end
println(add_all(1, 2, 3))6
raise_to_power(base, exponent = 2) = base^exponent
println(raise_to_power(3))
println(raise_to_power(3, 3))9
27
; and is passed by name.scale(value; factor = 2) = value * factor
println(scale(3))
println(scale(3; factor = 4))6
12
double = number -> 2 * number
println(double(4))8
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
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
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
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
typeof to inspect its concrete type.println(typeof(1))
println(typeof(1.0))Int64
Float64
:: to require a variable to contain a value of a particular type.observation_count::Int = 100
println(observation_count)100
double_integer(value::Int) = 2 * value
println(double_integer(4))8
try
double_integer(4.0)
catch error
println(typeof(error))
endMethodError
<: 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
struct defines an immutable composite type with named fields.struct Observation
value::Float64
end
observation = Observation(1.5)
println(observation.value)1.5
combine(left::Integer, right::Integer) = left + right
combine(left::AbstractString, right::AbstractString) = left * rightcombine (generic function with 2 methods)
println(combine(2, 3))
println(combine("Julia", "!"))5
Julia!
combine(times::Integer, text::AbstractString) = repeat(text, times)
println(combine(3, "ha"))
println(combine(2, 3))hahaha
5
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
endMain.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
@.@show prints both an expression and its value, which is useful for inspecting intermediate results.value = 3
@show value^2value ^ 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.@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
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
[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
[[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"using.using Random
Random.seed!(1234)
println(rand(3))
println(randn(3))[0.32597672886359486, 0.5490511363155669, 0.21858665481883066]
[0.7189099374659392, 0.4202471777937789, -0.685670902276119]
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]
using Statistics
values = [1.0, 2.0, 3.0, 4.0]
println(mean(values))
println(std(values))2.5
1.2909944487358056
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
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
optimize uses the derivative-free NelderMead() method by default.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
using Plots
x_values = 1:3
y_values = [1.0, 2.0, 1.5]
plot(x_values, y_values; marker = :circle, label = "series")X contain an intercept and one regressor, and let Y contain the outcome.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
beta_hat = inv(X' * X) * X' * Y
beta_hat2-element Vector{Float64}:
0.9999999999999987
1.0
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
using Random
generate_random_draws(number_of_observations) = rand(number_of_observations, 2)generate_random_draws (generic function with 1 method)
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
OLSData stores only the observed outcome vector Y and design matrix X.struct OLSData
Y::Vector{Float64}
X::Matrix{Float64}
endx1 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)
endgenerate_data (generic function with 1 method)
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(data) = inv(data.X' * data.X) * data.X' * data.Yestimate_ols (generic function with 1 method)
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]
using Statistics
mean_squared_error(coefficients, data) = mean((data.Y - data.X * coefficients) .^ 2)mean_squared_error (generic function with 1 method)
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_plotOptim can minimize the same objective numerically.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]
Optim estimates should be nearly identical.