In [2]:
a = [1,2,5]
b = [4,7,6]
print('a =',a)
print('b =',b)
a = b
print('a =',a)
print('b =',b)
b = [1,1,1]
print('a =',a)
print('b =',b)
In [7]:
a = 2
b = 7.1
c = 4
d = a + b * c
print(a**b)
In [1]:
a = 7
b = 2
print(a//b)
In [17]:
a = 5
# a = a + 2
a += 2
a -= 3
a *=4
a //= 3
print(a)
In [22]:
x = -3
fx = 3*x**2 + 4*x - 7
print(x, fx)
x = -2
fx = 3*x**2 + 4*x - 7
print(x, fx)
x = -1
fx = 3*x**2 + 4*x - 7
print(x, fx)
Flow Control, Loops
In [36]:
x = -3
for i in range(13):
fx = 3*x**2 + 4*x - 7
print(x, fx)
x += 0.5
In [38]:
for i in range(10):
for j in range(10):
print(i+1,' x ', j+1, '=', (i+1)*(j+1))
Multiplication Table 2017-09-19
In [43]:
for i in range(20):
for j in range(20):
print((i+1)*(j+1), end=' ')
print()
Print the Fibionacci Sequence
In [9]:
x_prevprev = 1
x_prev = 1
print(x_prevprev)
print(x_prev)
for i in range(10):
x = x_prevprev + x_prev
print(x)
x_prevprev = x_prev
x_prev = x
2017-09-26
Simulate gambling using a coin flip
Model: \begin{eqnarray*} e_k & \in & \{-1, +1\} \\ x_k & = & x_{k-1} + e_k \end{eqnarray*}
In [100]:
%matplotlib inline
import numpy as np
import matplotlib.pylab as plt
MAX_TURN = 100
INITIAL_CAPITAL = 10.
X = np.zeros(MAX_TURN)
capital = INITIAL_CAPITAL
for turn in range(MAX_TURN):
gain = 2*np.random.randint(high=2, low=0)-1
capital += gain
X[turn] = capital
if capital==0:
print(turn+1)
break
plt.plot(X)
plt.show()
Estimate the probability of ruin in betting using a fair coin flip using a Monte Carlo Simulation
In [1]:
import numpy as np
EPOCHS = 1000
MAX_TURN = 100
INITIAL_CAPITAL = 10
lost = 0
for epoch in range(EPOCHS):
capital = INITIAL_CAPITAL
for turn in range(MAX_TURN):
gain = 2*np.random.randint(high=2, low=0)-1
capital += gain
if capital==0:
lost+=1
break
print("{0:.2f}".format(lost/EPOCHS))
In [62]:
import numpy as np
# This is a comment
EPOCHS = 10000
MAX_TURN = 100
INITIAL_CAPITAL = 10
lost = 0
sigma = 1
for epoch in range(EPOCHS):
capital = INITIAL_CAPITAL
for turn in range(MAX_TURN):
gain = sigma*np.random.randn()
capital += gain
if capital<=0:
lost+=1
break
print("{0:.5f}".format(lost/EPOCHS))
In [37]:
np.random.randn()
Out[37]:
Start with an asset of price $S$ at $t=0$.
Assume that the price is evolving according to the brownian motion with volatility $\sigma^2$
Estimate the probability that at time $T$, the price is higher than $K$.
In [112]:
S = 10
K = 10
T = 100
sigma = 1
EPOCH = 100000
count_higher_K = 0
for e in range(EPOCH):
gain = np.random.randn()*T**0.5*sigma
if S + gain >= K:
count_higher_K += 1
print("{0:.5f}".format(count_higher_K/EPOCH))
List
In [127]:
lst = [1,2,3,7,'abc']
for x in lst:
print(x)
In [135]:
lst.append('tail')
In [136]:
lst
Out[136]:
In [125]:
lst.clear()
In [126]:
lst
Out[126]:
In [143]:
u = lst.copy()
In [146]:
lst
Out[146]:
In [144]:
u[0] = 10
In [151]:
lst.count('tail')
Out[151]:
In [153]:
lst.extend(range(3))
In [156]:
lst.index('abc')
Out[156]:
In [161]:
lst.insert(3,8)
In [162]:
lst
Out[162]:
In [177]:
lst = [1,'abc',5,'tail','tail']
In [170]:
lst.pop()
Out[170]:
In [175]:
lst.remove(5)
In [178]:
lst.reverse()
In [179]:
lst
Out[179]:
In [180]:
lst.sort()
In [182]:
lst = ['hjk','abc','zzs']
lst.sort()
lst
Out[182]:
In [184]:
lst = []
for x in range(11):
# lst.append(x**2)
lst.insert(0,x**2)
lst
Out[184]:
list comprehension
In [186]:
lst = [x**2 for x in reversed(range(11))]
lst
Out[186]:
In [187]:
lst = [[x,x**2] for x in range(11)]
lst
Out[187]:
In [202]:
lst = []
N = 10+2
for i in range(1,N):
u = [x**2 for x in range(i)]
lst.append(u)
lst
Out[202]:
In [197]:
lst
Out[197]:
In [196]:
lst.append([0,1,2])
In [192]:
lst = [[x**2 for x in range(u)] for u in range(1,12)]
lst
Out[192]:
In [204]:
lst = []
lst2 = []
for x in range(11):
lst.append(x**2)
lst2.insert(x,lst.copy())
lst2
Out[204]:
In [209]:
lst = []
lst2 = []
for x in range(11):
lst.append(x**2)
lst2.append(lst)
lst2
Out[209]:
In [216]:
fb = [1, 1]
N = 20
for i in range(N-2):
fb.append(fb[-1]+fb[-2])
fb
Out[216]:
In [207]:
a = [1,2,3]
b = a
b[0] = 16
a
Out[207]:
Tuples
In [114]:
u = (1,4,5)
u[0] = 7
In [117]:
person = {'name': 'Taylan', 'surname': 'Cemgil', 'age': 48}
print(person['name'])
print(person['surname'])
print(person['age'])
In [224]:
30*750/5
Out[224]:
European Call \begin{eqnarray} U_T & = & \exp(-rT) \left\langle (S_T - K)^+ \right\rangle \end{eqnarray}
European Put \begin{eqnarray} Y_T & = & \exp(-rT) \left\langle (K - S_T)^+ \right\rangle \end{eqnarray}
In [250]:
import numpy as np
r = 0.05
S0 = 100
K = 110
sigma = 0.1
T = 1
np.random.randn()
N = 100000
C = 0
P = 0
for i in range(N):
WT = np.random.randn()*np.sqrt(T)
ST = S0*np.exp((r-0.5*sigma**2)*T + sigma*WT)
C += max(0, ST - K)
P += max(0, K - ST)
call_price = (C/N)*np.exp(-r*T)
put_price = (P/N)*np.exp(-r*T)
print('Call price = ', call_price)
print('Put price = ', put_price)
In [19]:
import numpy as np
r = 0.05
S0 = 100
K = 110
sigma = 0.1
T = 1
np.random.randn()
EPOCH = 100000
N = 12
C = 0
P = 0
for i in range(EPOCH):
S_bar = 0
S = S0
for j in range(N):
WT = np.random.randn()*np.sqrt(T/N)
S = S*np.exp((r-0.5*sigma**2)*(T/N) + sigma*WT)
S_bar += S
S_bar /= N
C += max(0, S_bar - K)
P += max(0, K - S_bar)
call_price = (C/EPOCH)*np.exp(-r*T)
put_price = (P/EPOCH)*np.exp(-r*T)
print('Asian')
print('Call price = ', call_price)
print('Put price = ', put_price)
In [1]:
L = [ 3,2,1,0,4,7,9 ]
## Create a list with even numbers only
L2 = []
for x in range(len(L)):
if L[x]%2==0:
L2.append(L[x])
else:
pass
print(L2)
In [ ]:
## Create a list with even numbers only
L2 = []
for e in L:
if e%2==0:
L2.append(e)
else:
pass
In [2]:
L2 = list(filter(lambda x: x%2==0, L))
print(L2)
In [3]:
def is_even(x):
return x%2==0
In [7]:
L2 = list(filter(is_even, L))
print(L2)
In [11]:
for x in filter(is_even, L):
print(x, end=' ')
In [12]:
L = [ 3,2,1,0,4,7,9 ]
S = []
for x in L:
if x%2==0:
S.append(x)
for x in L:
if x%2==1:
S.append(x)
S
Out[12]:
In [13]:
L = [ 3,2,1,0,4,7,9 ]
S = []
for x in L:
if x%2==0:
S.insert(0,x)
else:
S.append(x)
S
Out[13]:
In [17]:
list(filter(is_even, L))+list(filter(lambda x: x%2==1, L))
Out[17]:
In [23]:
import numpy as np
U = np.array(L)
U[U%2==0]
Out[23]:
In [31]:
from functools import reduce
reduce(lambda x,y: x+y, filter(is_even, L))/len(list(filter(is_even, L)))
Out[31]:
In [34]:
L
reduce(lambda x,y: x*y, L)
Out[34]:
In [36]:
list(map(lambda x: x**2+1, L))
Out[36]:
In [38]:
L*2
Out[38]:
In [60]:
import numpy as np
N = 100
Z = 3
rho = 1
s = 0
for i in range(N):
x = np.random.exponential(scale=1./rho)
if x>Z:
s+=1
print(s/N)
print(np.exp(-rho*Z))
Target Density:
$$ p(x) = \rho \exp(-\rho x) $$Proposal $$ q(x) = r \exp(-r x) $$
Importance sampling identity
$$ E_p\{\phi(x)\} = E_q\{\frac{p(x)}{q(x)}\phi(x)\} $$$$ W(x) = \frac{p(x)}{q(x)} = \frac{\rho \exp(-\rho x)}{r \exp(-r x)} = \frac{\rho}{r} \exp(-(\rho-r)x) $$
In [93]:
import numpy as np
N = 100
Z = 20
rho = 1
r = 0.01
s = 0
for i in range(N):
x = np.random.exponential(scale=1./r)
W = rho/r*np.exp(-(rho-r)*x)
if x>Z:
s+= W
print(s/N)
print(np.exp(-rho*Z))
Dictionaries
json
In [2]:
person = {'name': 'Taylan', 'surname': 'Cemgil', 'age': 48}
person2 = {'name': 'Ahmet', 'surname': 'Ahmetoglu', 'age': 12}
person3 = {'name': 'Cetin', 'surname': 'Cetin', 'age': 62}
print(person['name'])
print(person['surname'])
print(person['age'])
In [8]:
people = [person, person2, person3]
In [16]:
for x in people[0:2]:
print(x['name'], x['surname'])
In [21]:
#txt = 'JSON (JavaScript Object Notation) is a lightweight data-interchange format.'
txt = 'JSON (JavaScript Object Notation) is a lightweight data-interchange format. It is easy for humans to read and write. It is easy for machines to parse and generate. It is based on a subset of the JavaScript Programming Language, Standard ECMA-262 3rd Edition - December 1999.'
In [118]:
counts = {}
for i in range(len(txt)):
key = txt[i]
if key in counts.keys():
counts[key] += 1
else:
counts[key] = 1
counts
Out[118]:
In [23]:
counts = {}
for i in range(len(txt)-1):
key = txt[i]+txt[i+1]
if key in counts.keys():
counts[key] += 1
else:
counts[key] = 1
counts
In [109]:
txt = 'babababcccbcbcbcbcbcaabababababaab'
counts = {'a':0, 'b':0, 'c': 0}
for i in range(len(txt)):
counts[txt[i]]+=1
counts
counts['d'] = 0
In [24]:
temp = txt
remove_list = ['(',')','.',',','-']
while True:
words = temp.partition(' ')
if words[2] == '':
break
w = words[0]
for l in remove_list:
w = w.replace(l,'')
if len(w)>0:
print(w)
temp = words[2]
In [41]:
txt2 = ''
for i in range(len(txt)):
txt2 = txt2+txt[i]*5
print(txt2)
In [137]:
a = (3,'abc',3.4)
a[2] = 5
In [151]:
txt.replace('.','').replace('(','').replace(')','').replace(',','').replace('-','').split()
Out[151]:
In [156]:
for w in txt.split():
print(w)
txt.maketrans