<jupyter_start><jupyter_text>IntroductionVariables, arithmetic operators~~~+ - * / ** % //~~~assignment~~~=~~~assign and increment~~~+=~~~<jupyter_code>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)


a = 2
b = 7.1
c = 4

d = a + b * c

print(a**b)
a = 7
b = 2

print(a//b)


a = 5

# a = a + 2
a += 2
a -= 3
a *=4
a //= 3
print(a)


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)<jupyter_output>-3 8
-2 -3
-1 -8<jupyter_text>Flow Control, Loops<jupyter_code>x = -3
for i in range(13):
    fx = 3*x**2 + 4*x - 7
    print(x, fx)
    x += 0.5
for i in range(10):
    for j in range(10):
        print(i+1,' x ', j+1, '=', (i+1)*(j+1))<jupyter_output>1  x  1 = 1
1  x  2 = 2
1  x  3 = 3
1  x  4 = 4
1  x  5 = 5
1  x  6 = 6
1  x  7 = 7
1  x  8 = 8
1  x  9 = 9
1  x  10 = 10
2  x  1 = 2
2  x  2 = 4
2  x  3 = 6
2  x  4 = 8
2  x  5 = 10
2  x  6 = 12
2  x  7 = 14
2  x  8 = 16
2  x  9 = 18
2  x  10 = 20
3  x  1 = 3
3  x  2 = 6
3  x  3 = 9
3  x  4 = 12
3  x  5 = 15
3  x  6 = 18
3  x  7 = 21
3  x  8 = 24
3  x  9 = 27
3  x  10 = 30
4  x  1 = 4
4  x  2 = 8
4  x  3 = 12
4  x  4 = 16
4  x  5 = 20
4  x  6 = 24
4  x  7 = 28
4  x  8 = 32
4  x  9 = 36
4  x  10 = 40
5  x  1 = 5
5  x  2 = 10
5  x  3 = 15
5  x  4 = 20
5  x  5 = 25
5  x  6 = 30
5  x  7 = 35
5  x  8 = 40
5  x  9 = 45
5  x  10 = 50
6  x  1 = 6
6  x  2 = 12
6  x  3 = 18
6  x  4 = 24
6  x  5 = 30
6  x  6 = 36
6  x  7 = 42
6  x  8 = 48
6  x  9 = 54
6  x  10 = 60
7  x  1 = 7
7  x  2 = 14
7  x  3 = 21
7  x  4 = 28
7  x  5 = 35
7  x  6 = 42
7  x  7 = 49
7  x  8 = 56
7  x  9 = 63
7  x  10 = 70
8  x  1 = 8
8  x  2 = 16
8  x  3 = 24
8  x  4 = 32
8  x  5 = 40
8  x  6 = 48
8  x  7 = 56
8  x  8 = 64
8[...]<jupyter_text>Multiplication Table2017-09-19<jupyter_code>for i in range(20):
    for j in range(20):
        print((i+1)*(j+1), end=' ')
    print()<jupyter_output>1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 
2 4 6 8 10 12 14 16 18 20 22 24 26 28 30 32 34 36 38 40 
3 6 9 12 15 18 21 24 27 30 33 36 39 42 45 48 51 54 57 60 
4 8 12 16 20 24 28 32 36 40 44 48 52 56 60 64 68 72 76 80 
5 10 15 20 25 30 35 40 45 50 55 60 65 70 75 80 85 90 95 100 
6 12 18 24 30 36 42 48 54 60 66 72 78 84 90 96 102 108 114 120 
7 14 21 28 35 42 49 56 63 70 77 84 91 98 105 112 119 126 133 140 
8 16 24 32 40 48 56 64 72 80 88 96 104 112 120 128 136 144 152 160 
9 18 27 36 45 54 63 72 81 90 99 108 117 126 135 144 153 162 171 180 
10 20 30 40 50 60 70 80 90 100 110 120 130 140 150 160 170 180 190 200 
11 22 33 44 55 66 77 88 99 110 121 132 143 154 165 176 187 198 209 220 
12 24 36 48 60 72 84 96 108 120 132 144 156 168 180 192 204 216 228 240 
13 26 39 52 65 78 91 104 117 130 143 156 169 182 195 208 221 234 247 260 
14 28 42 56 70 84 98 112 126 140 154 168 182 196 210 224 238 252 266 280 
15 30 45 60 75 90 105 120 135 150 165 180 195 210 225 240 255 270 285 300 
16 32 [...]<jupyter_text>Print the Fibionacci Sequence<jupyter_code>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<jupyter_output>1
1
2
3
5
8
13
21
34
55
89
144<jupyter_text>2017-09-26Simulate gambling using a coin flipModel:\begin{eqnarray*}e_k & \in & \{-1, +1\} \\x_k & = & x_{k-1} + e_k\end{eqnarray*}<jupyter_code>%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()<jupyter_output><empty_output><jupyter_text>Estimate the probability of ruin in betting using a fair coin flipusing a Monte Carlo Simulation<jupyter_code>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))   
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))   
np.random.randn()<jupyter_output><empty_output><jupyter_text>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$.<jupyter_code>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))<jupyter_output>0.49836<jupyter_text>Lists, Tuples and Dictionaries List<jupyter_code>lst = [1,2,3,7,'abc']

for x in lst:
    print(x)

lst.append('tail')
lst
lst.clear()
lst
u = lst.copy()
lst
u[0] = 10
lst.count('tail')
lst.extend(range(3))
lst.index('abc')
lst.insert(3,8)
lst
lst = [1,'abc',5,'tail','tail']
lst.pop()
lst.remove(5)
lst.reverse()
lst
lst.sort()
lst = ['hjk','abc','zzs']
lst.sort()
lst
lst = []
for x in range(11):
    # lst.append(x**2)
    lst.insert(0,x**2)
lst<jupyter_output><empty_output><jupyter_text>list comprehension<jupyter_code>lst = [x**2 for x in reversed(range(11))]
lst
lst = [[x,x**2] for x in range(11)]
lst
lst = []

N = 10+2

for i in range(1,N):
    u = [x**2 for x in range(i)]
    lst.append(u)
lst
lst
lst.append([0,1,2])

lst = [[x**2 for x in range(u)] for u in range(1,12)]
lst
lst = []
lst2 = []

for x in range(11):
    lst.append(x**2)
    lst2.insert(x,lst.copy())
lst2
lst = []
lst2 = []

for x in range(11):
    lst.append(x**2)
    lst2.append(lst)
lst2
fb = [1, 1]
N = 20
for i in range(N-2):
    fb.append(fb[-1]+fb[-2])
fb
a = [1,2,3]
b = a

b[0] = 16
a<jupyter_output><empty_output><jupyter_text>Tuples<jupyter_code>u = (1,4,5)

u[0] = 7
person = {'name': 'Taylan', 'surname': 'Cemgil', 'age': 48}

print(person['name'])
print(person['surname'])
print(person['age'])

30*750/5<jupyter_output><empty_output><jupyter_text>Option Pricing Vanilla \begin{eqnarray}W_T & \sim & \mathcal{N}(0, T) \\S_T & = & S_0 \exp\left((r-\frac{1}2\sigma^2)T + \sigma W_T \right) \\\end{eqnarray}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} Asian\begin{eqnarray}W_i & \sim & \mathcal{N}(0, T/N) \\S_i & = & S_{i-1} \exp\left((r-\frac{1}2\sigma^2)(T/N) + \sigma W_i \right) \\\bar{S} & = & \frac{1}{N}\sum_i S_i\end{eqnarray}<jupyter_code>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)
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)
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)
## Create a list with even numbers only
L2 = []
for e in L:
    if e%2==0:
        L2.append(e)
    else:
        pass


L2 = list(filter(lambda x: x%2==0, L))
print(L2)

def is_even(x):
    return x%2==0
L2 = list(filter(is_even, L))
print(L2)

for x in filter(is_even, L):
    print(x, end='  ')
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
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

list(filter(is_even, L))+list(filter(lambda x: x%2==1, L))
import numpy as np

U = np.array(L)
U[U%2==0]
from functools import reduce

reduce(lambda x,y: x+y, filter(is_even, L))/len(list(filter(is_even, L)))
L

reduce(lambda x,y: x*y, L)
list(map(lambda x: x**2+1, L))
L*2<jupyter_output><empty_output><jupyter_text>Importance sampling<jupyter_code>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))<jupyter_output>0.06
0.0497870683679<jupyter_text>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)$$<jupyter_code>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))<jupyter_output>5.89102741885e-09
2.06115362244e-09<jupyter_text>Dictionariesjson<jupyter_code>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'])



people = [person, person2, person3]

for x in people[0:2]:
    print(x['name'], x['surname'])
#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.'
counts = {}
for i in range(len(txt)):
    key = txt[i]
    if key in counts.keys():
        counts[key] += 1
    else:
        counts[key] = 1

counts
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
txt = 'babababcccbcbcbcbcbcaabababababaab'
counts = {'a':0, 'b':0, 'c': 0}
for i in range(len(txt)):
    counts[txt[i]]+=1

counts

counts['d'] = 0
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]

txt2 = ''
for i in range(len(txt)):
    txt2 = txt2+txt[i]*5

print(txt2)
a = (3,'abc',3.4)
a[2] = 5
txt.replace('.','').replace('(','').replace(')','').replace(',','').replace('-','').split()
for w in txt.split():
    print(w)

txt.maketrans<jupyter_output>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.
{'fraction_non_alphanumeric': 0.16332017138536503, 'fraction_numerical': 0.12366630261278669, 'mean_word_length': 2.7304920087746787, 'pattern_counts': {'":': 0, '<': 50, '<?xml version=': 0, '>': 53, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 8, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '14', 'dir': 'jupyter-structured-clean-dedup', 'id': '159249', 'license': 'MIT', 'n_tokens_mistral': 6403, 'n_tokens_neox': 5288, 'n_words': 1652, 'path': 'fe588/FE588 Introduction Fall 2017.ipynb', 'repo_name': 'bkoyuncu/notes', 'size': '11903'}