Skip to content

Instantly share code, notes, and snippets.

@svaksha
Forked from cuckookernel/pythontojulia.md
Created May 12, 2017 12:27
Show Gist options
  • Save svaksha/bf2b287e85967dcaad03a26d8b1e523d to your computer and use it in GitHub Desktop.
Save svaksha/bf2b287e85967dcaad03a26d8b1e523d to your computer and use it in GitHub Desktop.
Python to Julia Quick translation / conversion reference Guide

A quick and dirty syntax translation / conversion reference guide to ease the transition between Python and Julia. This is not meant as a reference to the language. For that you should read the manual.

Some important differences

  • Arrays in Julia are indexed starting from 1.
  • In Julia classes (i.e. types) don't own methods. Methods are implementations of generic functions and are invoked in a "static style", i.e. instead of Python's str1.rstrip(), we will have rstrip( str1 ), instead of file1.close(), close( file1 ).

Some important similarities.

Core

Getting around: All objects

Python Julia Comments
True true
False false
None nothing
type( obj ) typeof( obj )
{} Dict{KeyType,ValueType}()
elif elseif
lambda x, y : y + x * 2 (x,y) -> y + x * 2
"string %s interpolation %d" % ( str1, i1) "string $str1 interpolation $i1 " You can interpolate arbitrary expressions by enclosing them in braces, as in "${x+y}"
xrange(10,4,-2)` 10:-2:4
range(10,4,-2) [10:-2:4] Do this only if you really have to, as it will consume memory proportional to the length of the range
id( obj ) object_id( obj )
raise excetion throw( exception )
obj.fun( x, y) fun( obj, x, y)
with Lazy.jl
@> obj f(x,y)
## Basic String operations
Python Julia
str1 + str2 + str2 string( str1, str2, str3 )
len( str1 ) length( str1 )
str1.rstrip() rstrip( str1 )
str1.startswith( x ) ??? write your own such as the one in pytojul.jl

Regular expressions

Python Julia
m = re.match( r"(\d+):(\d+)", mystr ) m = match( r"(\d+):(\d+)", mystr )
m is not None m != nothing
arr = m.groups() arr = m.captures

File processing

Python Julia
f = open( "file.txt" ) f = open( "file.txt")
for line in f for line in eachline( f )
f.close() close( f )

Exceptions

(http://julia.readthedocs.org/en/latest/manual/control-flow/#exception-handling)

Python Julia
raise excetion throw( exception )
RuntimeError( "msg" ) (?) ErrorException( "msg" )
module pytojul.jl
export startswith
function startswith( x::ASCIIString, y::ASCIIString )
# Disclaimer: This function is still buggy. Please help me find the bug...
if length(y) > length(x)
return false
else
for i = 1 : length(y)
if x[i] != y[i]
return false
end
end
return true
end
end
end #module
@kbenchaaboun
Copy link

import numpy as np
import time
import sys

Spot = 36
σ = 0.2
n = 100000
m = 10
K = 40
r = 0.06
T = 1
order = int(sys.argv[1])
Δt = T / m
zeros = np.zeros(n)
t_span = np.round(np.arange(Δt, T + Δt, Δt), 6)

def first_one_np(x):
import numpy as np
original = x
x = np.greater(x, 0.)
n_columns = x.shape[1]
batch_size = x.shape[0]
x_not = 1 - x
sum_x = np.minimum(np.cumprod(x_not, axis=1), 1.)
ones = np.ones((batch_size, 1))
lag = sum_x[:, :(n_columns - 1)]
lag = np.column_stack([ones, lag])
return original * (lag * x)

def chebyshev_basis(x, k):
B = {}
B[0] = np.ones_like(x)
B[1] = x
for n in range(2, k):
B[n] = 2 * x * B[n - 1] - B[n - 2]

return np.column_stack(list(B.values()))

def scale(x):
xmin = x.min()
xmax = x.max()
a = 2 / (xmax - xmin)
b = -0.5 * a * (xmin + xmax)
return a * x + b

==============================================================================

%% Specify the stochastic process

==============================================================================

def advance(S):
dB = np.sqrt(Δt) * np.random.normal(size=[n])
out = S + r * S * Δt + σ * S * dB
return out

def main():
S = {0.: Spot * np.ones([n])}
# poisson = {0.: 0.}

for t in t_span:
    t_previous = np.round(t - Δt, 6)
    S[t] = advance(S[t_previous])

discount = np.exp(-r * Δt)
# zero = tf.constant(0, dtype=dtype)

CFL = {t: np.maximum(0., K - S[t]) for t in list(S.keys())}
# ==============================================================================
# %% Recursion
# ==============================================================================

value = {T: CFL[T] * discount}
CV = {T: zeros}

# for t in range(m - 2, -1, -1):
for t in t_span[::-1][1:]:
    t_next = np.round(t + Δt, 6)
    XX = chebyshev_basis(scale(S[t]), order)
    YY = value[t_next]

    β = np.linalg.lstsq(XX, YY, rcond=-1)[0]
    CV[t] = XX @ β
    value[t] = discount * np.where(CFL[t] > CV[t],
                                   CFL[t],
                                   value[t_next])

POF = {t: np.where(CV[t] > CFL[t], zeros, CFL[t]) for t in t_span}

# for t in list(poisson.keys()):
#     POF[t] = (1 - poisson[t]) * POF[t]

POF = np.stack(list(POF.values()), axis=1)

FPOF = first_one_np(POF)
dFPOF = {i: FPOF[:, i] * np.exp(-r * i * Δt) for i in range(m)}
dFPOF = np.column_stack(list(dFPOF.values()))
PRICE = dFPOF.sum(axis=1).mean()
return PRICE

t0 = time.time()
main()
t1 = time.time()
print((t1 - t0) * 4 * 1000) # Multiply by four bc we need the greeks

@schneiderfelipe
Copy link

Now there is a startswith function in Base.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment