The Brass Tacks of Julia Programming – Part I

QuantInsti

Contributor:
QuantInsti
Visit: QuantInsti

This is my second article in the Julia programming series. In my previous blog, I introduced you to Julia programming and discussed its origin and features. Here, I’ll work with the basic syntax of Julia programming.

I’ve divided this article into the following sections:

  • Basic arithmetic operations
  • General operations
  • Strings
  • Data structures
  • Working with matrices
  • Loops
  • Conditional statements
  • Functions
  • Using R and Python code in Julia
  • Python vs Julia – Comparison of syntax for basic operations

Let’s start with the most traditional method of learning any new programming language.

For the first few code snippets, I’ve deliberately used screen grabs from my Julia console so that you get a better feel of it.


Basic arithmetic operations

Let’s do some basic arithmetic operations using Julia. There are multiple ways of performing the same operation.

Here’s how you can write complex numbers and do basic operations on them.

When you add a floating-point number to an integer, it returns a floating-point number.

 ## Returns a float 
1.0 + 2 
Output: 3.0

Let’s look at division.

## Division 
1/2
Output: 0.5

Exponentiations can be done using the “^” symbol.

5^2
Output: 25

Julia can do operations on fractional numbers as well.

## Fractional numbers
1//2
## Adding fractional numbers
1//12 + 3//29
 Output: 65//348


General operations

Looking at the type of a variable is crucial while programming. Here’s how it can be done in Julia.

typeof(1)
typeof(1.0)
typeof('a')
typeof("Test")
Output:

Int64
Float64
Char
String

An important thing to note here is that characters are defined using single quotes while strings are defined using double quotes. A string in single quotes will return an error.

Let’s look at how to convert one variable type into another.

Converting a floating-point number into an integer.

# Method 1
convert(Int32, 1.0)

# Method 2
Int64(4.0)
Output:
1
4

The following example shows the method to comment multiple lines of code in Julia.

#=
Your comments here
Your comments here
Your comments here
=#

Single line comment can be written followed by “#”.

When you get stuck somewhere, the documentation can come in handy. Here’s how you can find out details of any function –

? log
Output: log(b,x) Compute the base blogarithm of x. Throws DomainError for negative Real arguments.
Examples
julia> log(4,8)
1.5
julia> log(4,2)
0.5

Strings

Now, let’s see how to use strings in Julia.

 "This is a string."
Output: This is a string.

Strings can be defined using “” or “”” “””. The use case for the second version would be when you need to use  ” inside your string. For example –

 """ This is the use case for "triple-quote" string definition method.""" 
Output: This is the use case for \"triple-quote\" string definition method.

Here’s how we can use string-like variables.

variable = "Julia"
"This is how variables can be used inside strings in $variable."
Output: This is how variables can be used inside strings in Julia.

Exponentiation can be performed on strings as well. Here’s an example –

 variable^3 
Output: JuliaJuliaJulia

Let’s move on to the methods of manipulating strings. There are multiple ways of doing the same thing. Let’s look at how we can add 2 strings.

# Method 1

string("This is how we", " merge strings")
string("This is how we merge ", 2,  " strings with a number in-between")


# Method 2

var_1 = "This is method 2"
var_2 = "of concatenating strings in Julia"
var_1 * " " * var_2

# Method 3

var_3 = "This is method 3"
"$var_3 $var_2"
Output: 
This is how we merge strings 
This is how we merge 2 strings with a number in-between 
This is method 2 of concatenating strings in Julia 
This is method 3 of concatenating strings in Julia

Data structures

Data structures form the building blocks of any programming language. They provide different ways to organize the data in order to use them efficiently.

Tuples

Tuples are a type of data structure that can’t be modified. Here’s how you can define a tuple.

tuples = (1, 2, 3)
typeof(tuples)
Output:
(1, 2, 3)
Tuple{Int64, Int64, Int64}

Indexing in Julia starts at 1. Here’s how you can access the first and the last element of any data structure in Julia.

# Accessing the first element
tuples[1]

# Accessing the last element
tuples[end]

# [10] [11] Negative indexing doesn't work in Julia
tuples[-1]

# Tuples can't be modified
push!(tuples, 2)
Output:

1
3

BoundsError: attempt to access Tuple{Int64, Int64, Int64} at index [-1]
Stacktrace:
[1] getindex(t::Tuple, i::Int64)
@ Base ./tuple.jl:29
[2] top-level scope
@ In[30]:2
[3] eval
@ ./boot.jl:360 [inlined]
[4] include_string(mapexpr::typeof(REPL.softscope), mod::Module, code::String, filename::String)
@ Base ./loading.jl:1116
MethodError: no method matching push!(::Tuple{Int64, Int64, Int64}, ::Int64)
Closest candidates are:
push!(::Any, ::Any, ::Any) at abstractarray.jl:2387
push!(::Any, ::Any, ::Any, ::Any...) at abstractarray.jl:2388
push!(::AbstractChannel, ::Any) at channels.jl:10
...
Stacktrace:
[1] top-level scope
@ In[33]:2
[2] eval
@ ./boot.jl:360 [inlined]

Here’s how you can merge tuples –

# Concatenating tuples
(tuples..., tuples...)

# This method of adding "..." after any variable can be used to merge any two datatypes
Output:

(1, 2, 3, 1, 2, 3)

Vectors

Vectors are a type of data structure that can be modified. Here’s how you can work with vectors.

# Method 1
vector = [8, 1, 9, 12]

# Method 2
vector_2 = [8 ; 1 ; 9 ; 12]
Output:

4-element Vector{Int64}:

8
1
9
12

Here’s how mutation can be done in Julia. Using the “!” symbol, write the changes to the original variable. This is equivalent to “inplace=True” in Python.

# Mutation in Julia
sort(vector)

# The original vector doesn't change
sort!(vector)

# The original vector changes
vector
Output:

4-element Vector{Int64}:
1
8
9
12

To perform an element-wise operation, use the “.” operator.

vector + 1 # This doesn’t work

vector .+ 1

# Adding vectors
vector + vector_2
Output: 

4-element Vector{Int64}:
2
9
10
13

4-element Vector{Int64}:
2
16
18
24

Now, vectors can contain variables of different data types. Here’s an example –

vector_3 = [1, 5, "foo", 1+3im]
Output:

4-element Vector{Any}:
1
5
"foo"
1 + 3im

Notice that the vector type is assumed to be “Any” as there are variables of different data types.

Let’s look at the method of generating a sequence of numbers. Here’s an example of generating a sequence from 1 to 10 with a spacing of 2.

seq = [1:2:10;]

Here’s what the output looks like.

Output:

5-element Vector{Int64}:
1
3
5
7
9

Dictionaries

Now we move on to creating dictionaries. Dictionaries are used in a programming language to store information about a unique variable.

Just as each word in a human language dictionary has an associated meaning, in Julia we have each key that has a value associated with it.This can be useful in cases where you want to look up values associated with a particular key.

Here’s how you can create a dictionary in Julia.

dictionary = Dict('A' => 1, 'B' => 2)

This is what the output looks like –

Output:

Dict{Char, Int64} with 2 entries:
'A' => 1
'B' => 2

Now that we have created a dictionary, we would like to access various elements of it. Here’s how we can do it.

# Accessing the keys
keys(dictionary)

# Accessing the values associated with each key
values(dictionary)
Output:

KeySet for a Dict{Char, Int64} with 2 entries. Keys:
'A'
'B'

ValueIterator for a Dict{Char, Int64} with 2 entries. Values:
1
2

Let’s add a new entry to the dictionary.

# Adding a new entry

merge!(dictionary, Dict('J' => 23))
Output:

Dict{Char, Int64} with 3 entries:
'J' => 23
'A' => 1
'B' => 2

Notice that the “!” symbol makes the change permanent.

Let’s remove an entry now.

## Removing an entry permanently from a dictionary
pop!(dictionary, 'J')

dictionary
Output:

Dict{Char, Int64} with 2 entries:
'A' => 1
'B' => 2

Stay tuned for the next installment in which Anshul Tayal will discuss working with matrices.

Visit QuantInsti for additional insight on this article: https://blog.quantinsti.com/julia-syntax/.

Disclosure: Interactive Brokers

Information posted on IBKR Traders’ Insight that is provided by third-parties and not by Interactive Brokers does NOT constitute a recommendation by Interactive Brokers that you should contract for the services of that third party. Third-party participants who contribute to IBKR Traders’ Insight are independent of Interactive Brokers and Interactive Brokers does not make any representations or warranties concerning the services offered, their past or future performance, or the accuracy of the information provided by the third party. Past performance is no guarantee of future results.

This material is from QuantInsti and is being posted with permission from QuantInsti. The views expressed in this material are solely those of the author and/or QuantInsti and IBKR is not endorsing or recommending any investment or trading discussed in the material. This material is not and should not be construed as an offer to sell or the solicitation of an offer to buy any security. To the extent that this material discusses general market activity, industry or sector trends or other broad based economic or political conditions, it should not be construed as research or investment advice. To the extent that it includes references to specific securities, commodities, currencies, or other instruments, those references do not constitute a recommendation to buy, sell or hold such security. This material does not and is not intended to take into account the particular financial conditions, investment objectives or requirements of individual customers. Before acting on this material, you should consider whether it is suitable for your particular circumstances and, as necessary, seek professional advice.

In accordance with EU regulation: The statements in this document shall not be considered as an objective or independent explanation of the matters. Please note that this document (a) has not been prepared in accordance with legal requirements designed to promote the independence of investment research, and (b) is not subject to any prohibition on dealing ahead of the dissemination or publication of investment research.

Any trading symbols displayed are for illustrative purposes only and are not intended to portray recommendations.