isinstance(1,int)
isinstance(3.2,float)
isinstance(3.2,int)
An Example
import matplotlib.pyplot as plt
def add_to_plot(x,y):
result = False
if (isinstance(x,int) or isinstance(x,float)) and \
(isinstance(y,int) or isinstance(y,float)):
plt.plot(x,y,"ro")
result = True
return result
x = 3
y = 4
if add_to_plot(x,y):
print("Plotted ",x,",",y)
else:
print("Plotting ",x,",",y,"failed!")
x = 2
y = 9.2
if add_to_plot(x,y):
print("Plotted ",x,",",y)
else:
print("Plotting ",x,",",y,"failed!")
x = 1.3
y = 7
if add_to_plot(x,y):
print("Plotted ",x,",",y)
else:
print("Plotting ",x,",",y,"failed!")
x = 'c'
y = 7
if add_to_plot(x,y):
print("Plotted ",x,",",y)
else:
print("Plotting ",x,",",y,"failed!")
plt.show()
import matplotlib.pyplot as plt
try:
x,y = 1.1, 3
plt.plot(x,y,"ro")
x,y = 3.2, 5
plt.plot(x,y,"ro")
x,y = 'a','yellow'
plt.plot(x,y,"ro")
plt.show()
except ValueError as ve:
print("Got value error = ",ve)
finally:
print("Either ",x,"or",y,"was not a duck.")
![]() |
---|
Python Features |
a,b = b,a
is a specific case off a,b = <expresion>
LHS = <expression>
<expression>
and produces an object, and then changes the variable to reference the object.LHS1, LHS2, LHS2 = <expression1>, <expression2>, <expression3>
a + b,
a
is an expression.a = 3
# a is an expression. Evaluate a.
a
a,b = b,a
Python parses and produces the following codeb
and produce a new object o1
with the value.a
and produce a new object o2
with the value.a
to reference o1
b
to reference o2
# Multiple return example
def three_powers(x):
r1 = x**2
r2 = x**3
r3 = x**3
return r1, r2, r3
# More "traditional" multiple return approach
def another_three_powers(x):
r1 = x**2
r2 = x**3
r3 = x**3
return [r1, r2, r3]
print("Multiple returns = ", three_powers(2))
print("Cranky, old guy multiple returns = ", another_three_powers(2))
a = 1
b = 2
a,b
x = 3
y = 4
(x , y) = (y, x)
y,x
The formula \begin{equation} S_t = S_{t-1} * (1 + \mu\delta t + \sigma\phi \sqrt{\delta t}) \end{equation}
Is the same as \begin{equation} (S_t -S_{t-1}) = \Delta S = S_{t-1}(\mu\delta t + \sigma\phi \sqrt{\delta t})) \end{equation}
![]() |
---|
Geometric Brownian Motion |
\begin{equation} p_i = p_{i-1} * {{D(p_{i-1}) - S} \over S} \end{equation}
# Given a price p, demand at price p and supply at price p,
# compute the next proposed price.
def new_price(p, d, s):
result = p * (d - s)/s
return result
import pandas as pd
def read_stock_data(ticker):
file_name = "../Data/" + ticker + ".csv"
print("File to read = ", file_name)
df = df = pd.read_csv(file_name)
return df
def compute_average(close_prices):
no_of_entries = len(close_prices)
total = 0
for i in range(0,no_of_entries):
total = total + close_prices[i]
result = total / no_of_entries
return result
# Note: Testing the function with a small enough data set
# to manually, visually compare to CSV file. Actual simulation
# will use much large files.
aapl_df = read_stock_data("AAPL")
print("\n\nAll data = \n", df)
close_prices = df['Adj Close']
print('\n\n Close prices = \n', close_prices)
# Note: Testing on small enough data array to
# manually check correctness.
test = [1, 10, 100]
avg = compute_average(test)
print("test average = ", avg)
![]() |
---|
Breaking it Down Barney Style |
Decision Making Process
Tasks
simulator_core.biased_coin
# This code goes in a module/package of reusable functions.
# Import the pseudo-random number generation functions
import random
# This function's parameter is an float in the
# range [0,1]. This represents the probability of
# an event occuring. The function asssumes uniform
# distribution. The function "flips the biased coin"
# and returns 0 or 1 of the event occurs.
def biased_coin(probability):
random_value = random.random()
if random_value <= probability:
return 1
else:
return 0
/tests/unit_test_coin
# import simulator_core
# This code goes in a module/package that unit tests
# reusable functions and modules.
# Simple test of the coin flipper.
def test_flipper():
total = 0
prob = 0.333
count = 100000
for i in range(0,count):
#total = total + sc.random_event(0.333)
total = total + biased_coin(0.333)
avg = total / count
print("test_flipper: result = ", avg,", expectation = ", prob, " flips = ", count)
test_flipper()
![]() |
---|
Some Common Project Structures ] |
![]() |
---|
Initial Project Structure ] |
simulator_core.random_set
# Flips the biased coin N-times and returns the
# vector of results
def random_set(probability, count):
result = []
for i in range(0,count):
event = biased_coin(probability)
result.append(event)
return result
/tests/unit_test_sequence
def eyeball_event_str():
event_stream = random_set(0.333,20)
print("Event stream = ", event_stream)
def test_event_string_avg():
event_stream = random_set(0.333, 10000)
count = len(event_stream)
total = 0
for i in range(0, count):
total = total + event_stream[i]
avg = total / count
print("test_event_string: avg = ", avg, " element count = ", count)
eyeball_event_str()
test_event_string_avg()
simulator_core.failure_streak_lengths
def failure_streak_lengths(event_stream):
result = []
on_a_streak = False;
count = len(event_stream)
on_a_streak = False
current_fail_streak = 0
for i in range(0,count):
current_event = event_stream[i]
if current_event == 0:
if on_a_streak == False:
on_a_streak = True
current_fail_streak = 1
else:
current_fail_streak = current_fail_streak + 1
else:
if on_a_streak == True:
on_a_streak = False;
result.append(current_fail_streak)
current_fail_streak = 0
else:
if on_a_streak == True:
result.append(current_fail_streak)
return result
/tests/unit_test_length
def eyeball_streak_length():
event_stream = random_set(0.333, 30)
print("Event stream = ", event_stream)
fail_streaks = failure_streak_lengths(event_stream)
print("Hitless streaks = ", fail_streaks)
eyeball_streak_length()
simulator_core.histogram_streak_lengths
def histogram_streak_lengths(lengths):
result = []
max_fails = max(lengths)
for j in range(0,max_fails+1):
result.append(0)
for i in range(0,len(lengths)):
fails = lengths[i]
result[fails] = result[fails] + 1
return result
/tests/test_histogram
def eyeball_histogram():
event_stream = random_set(0.250, 30)
print("Event stream = ", event_stream)
fail_streaks = failure_streak_lengths(event_stream)
print("Streaks = ", fail_streaks)
fail_histo = histogram_streak_lengths(fail_streaks)
print("Histogram = ", fail_histo)
eyeball_histogram()
def simulate_season(avg, no_at_bats):
event_stream = random_set(avg, no_at_bats)
fail_streaks = failure_streak_lengths(event_stream)
fail_histo = histogram_streak_lengths(fail_streaks)
return fail_histo
ab = 600
avg = 0.250
print("Simulating seasons with ", ab, "at bats and batting average ", avg)
histo = simulate_season(avg, ab)
for i in range(0,len(histo)):
print("Streak length ", i, " no of occurences ", histo[i])
import matplotlib.pyplot as plt
def add_to_plot(x,y):
result = False
if (isinstance(x,int) or isinstance(x,float)) and \
(isinstance(y,int) or isinstance(y,float)):
plt.plot(x,y,"ro")
result = True
return result
for i in range(0,len(histo)):
add_to_plot(i,histo[i])
plt.title("No of streaks.")
plt.xlabel("Streak length")
plt.ylabel("No. of streaks of length")
plt.show()