def price_call_discount_iter(no_of_steps, r0, k, ravg, step_size, sigma, time, expiry, fv, no_of_sim, strike, is_explicit): randoms = np.random.normal(0, 1, no_of_steps) r_path = build_r_path(r0, no_of_steps, k, ravg, step_size, sigma, randoms) if is_explicit: price = Question1.price_discount_bond_explicit(r_path[no_of_steps - 1], sigma, k, ravg, expiry, time, fv) else: price = Question1.price_discount_bond( r_path[no_of_steps - 1], sigma, k, ravg, fv, time - expiry, 2 * (time - expiry) / no_of_steps, no_of_sim) return math.exp(-sum(r_path) * step_size) * max(price - strike, 0.0)
def main(): tTotal = 350 repeat = 25 # Run the two given simulations print 'Running simulation 1/2' sim1 = runSim(tTotal, repeat, 10**5, 0.01, 5.0) print 'Running simulation 2/2' sim2 = Erdos.runSim(tTotal, repeat, 10**5, 0.01, 5.0) plt.figure() printGraph(sim1, tTotal, repeat, "Scale-free network", stepsize=1) printGraph(sim2, tTotal, repeat, "Erdos-Renyi network", stepsize=1) plt.legend(loc=2) plt.title("Question 4a with 2 simulations") print """ The figure shows the Erdos-Renyi and scale-free network simulation for <k>=5, i=0.1 and N=10^5. Every simulation is simulated with """ + str( tTotal) + """ steps and this is repeated """ + str(repeat) + """ times. """ plt.show()
def calculate_price_implicit(sigma, dx, step_size, r0, time, strike, k, ravg, fv, expiry): no_of_paths = int(r0 / dx) # Generate rates and calculate terminal prices rate_path = [ r0 + dx * count for count in range(no_of_paths, -no_of_paths - 1, -1) ] prices_ter = [ max( Question1.price_discount_bond(rate, sigma, k, ravg, fv, (time - expiry), 1 / 252, 1000) - strike, 0.0) for rate in rate_path ] # Generate call Prices max_time_steps = int(expiry / step_size) call_prices = np.full([2 * no_of_paths + 1, max_time_steps], np.nan) call_prices[:, (max_time_steps - 1)] = prices_ter # Calculate price at every time for count in range(max_time_steps - 2, -1, -1): call_prices[:, count] = calculate_IFD(no_of_paths, call_prices[:, count + 1], rate_path, step_size, sigma, dx, ravg, k) return call_prices[no_of_paths, 0]
def linear_regression_with_single_attribute( training_set, testing_set, k): # k is the index of that attribute in data array, 0<=k<13 x = np.ones((len(training_set), 2)) # 2d matrix with 2 columns array_y = [] row = 0 for d in training_set: x[row][0] = d[k] array_y.append(d[13]) row += 1 y = np.array(array_y) w = np.around(Question1.calculate_regression_coefficient(x, y), 5) training_mse = calculate_MSE(w, x, y) # Using the testing set to calculate mse test_x = np.ones((len(testing_set), 2)) test_array_y = [] row = 0 for t in testing_set: test_x[row][0] = t[k] test_array_y.append(t[13]) row += 1 test_y = np.array(test_array_y) testing_mse = calculate_MSE(w, test_x, test_y) result = [] result.append(np.around(training_mse, 5)) result.append(np.around(testing_mse, 5)) return result
def _main(): fileName = 'Subject005Trial08.txt' forcePlateNames = ['FP1'] footMarkerNames = ['RHEE', 'RMT5'] forceData = Question1.parsePointFile(fileName, forcePlateNames, suffix='ForX') momentData = Question1.parsePointFile(fileName, forcePlateNames, suffix='MomX') copData = Question1.parsePointFile(fileName, forcePlateNames, suffix='CopX') markerData = Question1.parsePointFile(fileName, footMarkerNames) xCoords = np.zeros(400) zCoords = np.zeros_like(xCoords) yTorques = np.zeros_like(xCoords) for i, frame in enumerate(range(600,1000)): xCoords[i], zCoords[i], yTorques[i] = calcualteCop(forceData['FP1'][frame], momentData['FP1'][frame]) # print xCoord, copData['FP1'][i,0], zCoord, copData['FP1'][i,2], yTorque plt.style.use('/home/will/Projects/MCLS_CSU/MCLS_Res/GeneralTools/Visualization/matplotlibStyleSheets/MCLSPoster') fig, ax = plt.subplots(nrows=3) xVals = np.arange(600, 1000)*0.01 ax[0].plot(xVals, xCoords, color='g', linewidth=2) ax[1].plot(xVals, zCoords, color='r', linewidth=2) ax[2].plot(xVals, yTorques, color='b', linewidth=2) ax[0].set_ylabel(r'$COP_x$') ax[1].set_ylabel(r'$COP_z$') ax[2].set_ylabel(r'$T_y$') ax[2].set_xlabel('Time (s)') for i in range(3): ax[i].grid() ax[i].set_ylim(0,1) ax[2].set_ylim(-4,4) fig2, ax2 = plt.subplots(nrows=1) copx = ax2.plot(xVals, xCoords, color='g', linewidth=2) rhee = ax2.plot(xVals, markerData['RHEE'][600:1000,0], color='c', linewidth=2.5) rmt = ax2.plot(xVals, markerData['RMT5'][600:1000,0], color='m', linewidth=2.5) ax2.set_xlabel('Time (s)') ax2.set_ylabel(r'$COP_x, Marker_x$') ax2.set_ylim(0,1) ax2.grid() fig2.legend([copx[0], rhee[0], rmt[0]], (r'$COP_x$', 'RHEE', 'RMT5'), loc='upper center', ncol=3, borderpad=0.4, numpoints=2, columnspacing=0.5) plt.show()
def question4(market_price, oas): y = 0.0005 wac = 0.08 loan = 100000 r0 = 0.078 k = 0.6 ravg = 0.08 sigma = 0.12 time = 30 no_of_sim = 1000 price_plus = Question1.price_mbs(wac, loan, r0, k, ravg, sigma, time, "NUMERIX", no_of_sim, oas + y) price_minus = Question1.price_mbs(wac, loan, r0, k, ravg, sigma, time, "NUMERIX", no_of_sim, oas - y) duration = (price_minus - price_plus)/(2*y*market_price) convexity = (price_plus + price_minus - 2*market_price)/(2* market_price * (y**2)) print("OAS Duration is {0:.4f}".format(duration)) print("OAS Convexity is {0:.4f}".format(convexity))
def main(): coupled = euler() tTotal = 15 # Run the coupled ODE functions coupled.calc(f=coupled.coupledODE, N=10**5, averageK=5.0, initial=0.001, risk=0.01, steps=tTotal, name='Question 1 <k>=5.0 & i=0.01') coupled.calc(f=coupled.coupledODE, N=10**5, averageK=.8, initial=0.001, risk=0.1, steps=tTotal, name='Question 1 <k>=0.8 & i=0.1') # Run the erdos simulation repeat = 30 print 'Running simulation 1/2' sim1 = Erdos.runSim(tTotal, repeat, 10**5, 0.01, 5.0) print 'Running simulation 2/2' sim2 = Erdos.runSim(tTotal, repeat, 10**5, 0.1, 0.8) Erdos.printGraph(sim1, tTotal, repeat, "N=10^5, i = 0.01, <k> = 5.0", stepsize=1) Erdos.printGraph(sim2, tTotal, repeat, "N=10^5, i = 0.1, <k> = 0.8", stepsize=1) print """ Alle methoden zijn uitgevoerd met de gegeven waarden uit de opgaves. De Erdos methodes is """ + str(repeat) + """ keer uitgevoerd voor een beter gemiddeld resultaat. Verder zijn nu voor alle methodes """ + str(tTotal) + """ stappen berekend. """ coupled.showplot()
def _main(): # Define the file that contains the data, the desired range of frames, and the marker names that will be used. fileName = 'Subject005Trial08.txt' frames = range(600, 1000) desiredPointNames3 = ['RGTRO', 'RHEE', 'RMT5'] desiredPointNames5 = ['RGTRO', 'RLEK', 'RLM', 'RHEE', 'RMT5'] # Parse the marker data, and define the number of frames and number of markers marker3Data = Question1.parsePointFile(fileName, desiredPointNames3) marker5Data = Question1.parsePointFile(fileName, desiredPointNames5) frameNumber = len(frames) # Define the leg model femurLength = 0.46 # m shankLength = 0.41 # m footLength = 0.20 # m femurAxis = np.array([0.0, -1]) shankAxis = np.array([0.0, -1]) footAxis = np.array([1, 0.0]) femurBody = BodySegment(femurLength, femurAxis) shankBody = BodySegment(shankLength, shankAxis) footBody = BodySegment(footLength, footAxis) bodySegments = [femurBody, shankBody, footBody] initialGuess = np.array([0.38, 0.84, 40.0, -60.0, 0.0])#np.zeros(5) marker3Results = run3MarkerForwardKinematics(marker3Data, bodySegments, frameNumber, frames, initialGuess) marker5Results = run5MarkerForwardKinematics(marker5Data, bodySegments, frameNumber, frames, initialGuess) print 'Tx = ', min(marker3Results[:,0]), max(marker3Results[:,0]) print 'Ty = ', min(marker3Results[:,1]), max(marker3Results[:,1]) print 'hip = ', min(marker3Results[:,2]), max(marker3Results[:,2]) print 'knee = ', min(marker3Results[:,3]), max(marker3Results[:,3]) print 'foot = ', min(marker3Results[:,4]), max(marker3Results[:,4]) plotGeneralizedCoordinates([marker3Results, marker5Results]) return
def linear_regression_with_all_attributes(training_set, testing_set): x = np.ones((len(training_set), 14)) # 2d matrix with 14 columns array_y = [] row = 0 for t in training_set: # put the elements of t into the row column = 0 while column < 13: x[row][column] = t[column] column += 1 array_y.append(t[13]) row += 1 y = np.array(array_y) w = np.around(Question1.calculate_regression_coefficient(x, y), 7) # print w error = [] # calculate mse on training set training_error = calculate_MSE(w, x, y) # calculate mse on testing set test_x = np.ones((len(testing_set), 14)) test_array_y = [] row = 0 for t in testing_set: column = 0 while column < 13: test_x[row][column] = t[column] column += 1 test_array_y.append(t[13]) row += 1 test_y = np.array(test_array_y) testing_error = calculate_MSE(w, test_x, test_y) error.append(training_error) error.append(testing_error) return error
def main(): tTotal = 350 repeat = 25 # Run the two given simulations print 'Running simulation 1/2' sim1 = runSim(tTotal, repeat, 10**5, 0.01, 5.0) print 'Running simulation 2/2' sim2 = Erdos.runSim(tTotal, repeat, 10**5, 0.01, 5.0) plt.figure() printGraph(sim1, tTotal, repeat, "Scale-free network", stepsize=1) printGraph(sim2, tTotal, repeat, "Erdos-Renyi network", stepsize=1) plt.legend(loc=2) plt.title("Question 4a with 2 simulations") print """ The figure shows the Erdos-Renyi and scale-free network simulation for <k>=5, i=0.1 and N=10^5. Every simulation is simulated with """ + str(tTotal) + """ steps and this is repeated """ + str(repeat) + """ times. """ plt.show()
def main(): Question1.q1() Question2.q2() Question3.q3() Question4.q4()
def test_both_spaces(self): self.assertEqual( Question1.remove_white_espace(" hi there what's up "), "hi there what's up")
if not (pain in [1, 2, 3, 4, 5]): raise ValueError('Pain level can only take 1, 2, 3, 4, 5') score = dictCoefficients['Vision'][vision - 1] score *= dictCoefficients['Hearing'][hearing - 1] score *= dictCoefficients['Speech'][speech - 1] score *= dictCoefficients['Ambulation'][ambulation - 1] score *= dictCoefficients['Dexterity'][dexterity - 1] score *= dictCoefficients['Emotion'][emotion - 1] score *= dictCoefficients['Cognition'][cognition - 1] score *= dictCoefficients['Pain'][pain - 1] score *= MultConstant score -= Constant return score ## TESTING using the values online import Question1 as eq # should equal ~0.70 print("Score for 2, 1, 1, 2, 1, 2, 1, 3") print(eq.get_score(2, 1, 1, 2, 1, 2, 1, 3)) # should equal 1 print(eq.get_score(1, 1, 1, 1, 1, 1, 1, 1)) # enter score that isn't valid - ValueError message should pop up for hearing level print(eq.get_score(1, 7, 1, 2, 3, 2, 4, 1))