Video: https://youtu.be/dYhrCUFN0eM
Article: https://medium.com/p/the-gentlest-introduction-to-tensorflow-248dc871a224
Code: https://github.com/nethsix/gentle_tensorflow/blob/master/code/linear_regression_one_feature.py
This alternative introduction to Google's official Tensorflow (TF) tutorial strips away the unnecessary concepts that overly complicates getting started. The goal is to use TF to perform Linear Regression (LR) that has only a single-feature. We show how to model the LR using a TF graph, how to define the cost function to measure how well the an LR model fits the dataset, and finally train the LR model to find the best fit model.
Gentlest Introduction to Tensorflow - Part 2Khor SoonHin
Video: https://youtu.be/Trc52FvMLEg
Article: https://medium.com/@khor/gentlest-introduction-to-tensorflow-part-2-ed2a0a7a624f
Code: https://github.com/nethsix/gentle_tensorflow
Continuing from Part 1 where we used Tensorflow to perform linear regression for a model with single feature, here we:
* Use Tensorboard to visualize linear regression variables and the Tensorflow network graph
* Perform stochastic/mini-batch/batch gradient descent
Jose Leiva, data scientist at Ets Asset Management Factory, gives an accurate and simple introduction to Machine Learning. He explains some of the problems that quantitative managers have to get alpha in the markets, and how to face them using Deep Learning.
Gentlest Introduction to Tensorflow - Part 3Khor SoonHin
Articles:
* https://medium.com/all-of-us-are-belong-to-machines/gentlest-intro-to-tensorflow-part-3-matrices-multi-feature-linear-regression-30a81ebaaa6c
* https://medium.com/all-of-us-are-belong-to-machines/gentlest-intro-to-tensorflow-4-logistic-regression-2afd0cabc54
Video: https://youtu.be/F8g_6TXKlxw
Code: https://github.com/nethsix/gentle_tensorflow
In this part, we:
* Use Tensorflow for linear regression models with multiple features
* Use Tensorflow for logistic regression models with multiple features. Specifically:
* Predict multi-class/discrete outcome
* Explain why we use cross-entropy as cost function
* Explain why we use softmax
* Tensorflow Cheatsheet #1
* Single feature linear regression
* Multi-feature linear regression
* Multi-feature logistic regression
Video: https://youtu.be/dYhrCUFN0eM
Article: https://medium.com/p/the-gentlest-introduction-to-tensorflow-248dc871a224
Code: https://github.com/nethsix/gentle_tensorflow/blob/master/code/linear_regression_one_feature.py
This alternative introduction to Google's official Tensorflow (TF) tutorial strips away the unnecessary concepts that overly complicates getting started. The goal is to use TF to perform Linear Regression (LR) that has only a single-feature. We show how to model the LR using a TF graph, how to define the cost function to measure how well the an LR model fits the dataset, and finally train the LR model to find the best fit model.
Gentlest Introduction to Tensorflow - Part 2Khor SoonHin
Video: https://youtu.be/Trc52FvMLEg
Article: https://medium.com/@khor/gentlest-introduction-to-tensorflow-part-2-ed2a0a7a624f
Code: https://github.com/nethsix/gentle_tensorflow
Continuing from Part 1 where we used Tensorflow to perform linear regression for a model with single feature, here we:
* Use Tensorboard to visualize linear regression variables and the Tensorflow network graph
* Perform stochastic/mini-batch/batch gradient descent
Jose Leiva, data scientist at Ets Asset Management Factory, gives an accurate and simple introduction to Machine Learning. He explains some of the problems that quantitative managers have to get alpha in the markets, and how to face them using Deep Learning.
Gentlest Introduction to Tensorflow - Part 3Khor SoonHin
Articles:
* https://medium.com/all-of-us-are-belong-to-machines/gentlest-intro-to-tensorflow-part-3-matrices-multi-feature-linear-regression-30a81ebaaa6c
* https://medium.com/all-of-us-are-belong-to-machines/gentlest-intro-to-tensorflow-4-logistic-regression-2afd0cabc54
Video: https://youtu.be/F8g_6TXKlxw
Code: https://github.com/nethsix/gentle_tensorflow
In this part, we:
* Use Tensorflow for linear regression models with multiple features
* Use Tensorflow for logistic regression models with multiple features. Specifically:
* Predict multi-class/discrete outcome
* Explain why we use cross-entropy as cost function
* Explain why we use softmax
* Tensorflow Cheatsheet #1
* Single feature linear regression
* Multi-feature linear regression
* Multi-feature logistic regression
TensorFlow is a wonderful tool for rapidly implementing neural networks. In this presentation, we will learn the basics of TensorFlow and show how neural networks can be built with just a few lines of code. We will highlight some of the confusing bits of TensorFlow as a way of developing the intuition necessary to avoid common pitfalls when developing your own models. Additionally, we will discuss how to roll our own Recurrent Neural Networks. While many tutorials focus on using built in modules, this presentation will focus on writing neural networks from scratch enabling us to build flexible models when Tensorflow’s high level components can’t quite fit our needs.
About Nathan Lintz:
Nathan Lintz is a research scientist at indico Data Solutions where he is responsible for developing machine learning systems in the domains of language detection, text summarization, and emotion recognition. Outside of work, Nathan is currently writting a book on TensorFlow as an extension to his tutorial repository https://github.com/nlintz/TensorFlow-Tutorials
Link to video https://www.youtube.com/watch?v=op1QJbC2g0E&feature=youtu.be
Dynamic Programming and Reinforcement Learning applied to Tetris GameSuelen Carvalho
Slides presented as a work to Artificial Intelligence's class at IME-USP. This presentation is about how reinforcement learning is applied to a Tetris game.
Steffen Rendle, Research Scientist, Google at MLconf SFMLconf
Abstract:
Developing accurate recommender systems for a specific problem setting seems to be a complicated and time-consuming task: models have to be defined, learning algorithms derived and implementations written. In this talk, I present the factorization machine (FM) model which is a generic factorization approach that allows to be adapted to problems by feature engineering. Efficient FM learning algorithms are discussed among them SGD, ALS/CD and MCMC inference including automatic hyperparameter selection. I will show on several tasks, including the Netflix prize and KDDCup 2012, that FMs are flexible and generate highly competitive accuracy. With FMs these results can be achieved by simple data preprocessing and without any tuning of regularization parameters or learning rates.
An Introduction to core ideas, characteristics and benefits of functional programming and their implementation within the so called ‘object – functional’ language Scala.
Leaving the widely known concepts of object oriented programming aside, the focus is directed on how to leverage Scala in order to perform the following topics (extract):
* Functions and Function types
* Lambdas and Closures
* Currying and partial Argument Application
* Algebraic datatypes and Pattern matching
* Higher Order Functions
* Composition and Combinators
Slides for the Differential Machine Learning masterclass given by Brian Huge and Antoine Savine in Barcelona at the Quant Minds International event of December 2021.
This presentation summarises two years of research and development at Danske Bank on the pricing and risk of financial derivatives by machine learning and artificial intelligence.
The presentation develops the themes introduced in two articles in Risk Magazine, October 2020 and October 2021. Those themes are being further developed in the book Modern Computational Finance: Differential Machine Learning, with Chapman and Hall, autumn 2022.
Introduction to Factorization Machines model with an example. Motivations - why you should have it in your toolbox, model and it expressiveness, use case for context-aware recommendations and Field-Aware Factorization Machines.
I am Wycliffe S. I am a Python Homework Expert at pythonhomeworkhelp.com. I hold a Master's in Computer Science from, the University of Aberdeen, UK. I have been helping students with their homework for the past 13 years. I solve homework related to Python.
Visit pythonhomeworkhelp.com or email support@pythonhomeworkhelp.com. You can also call on +1 678 648 4277 for any assistance with Python Homework.
I am Ben R. I am a Statistics Assignment Expert at statisticshomeworkhelper.com. I hold a Ph.D. in Statistics, from University of Denver, USA. I have been helping students with their homework for the past 5 years. I solve assignments related to Statistics.
Visit statisticshomeworkhelper.com or email info@statisticshomeworkhelper.com.
You can also call on +1 678 648 4277 for any assistance with Statistics Assignments.
TensorFlow is a wonderful tool for rapidly implementing neural networks. In this presentation, we will learn the basics of TensorFlow and show how neural networks can be built with just a few lines of code. We will highlight some of the confusing bits of TensorFlow as a way of developing the intuition necessary to avoid common pitfalls when developing your own models. Additionally, we will discuss how to roll our own Recurrent Neural Networks. While many tutorials focus on using built in modules, this presentation will focus on writing neural networks from scratch enabling us to build flexible models when Tensorflow’s high level components can’t quite fit our needs.
About Nathan Lintz:
Nathan Lintz is a research scientist at indico Data Solutions where he is responsible for developing machine learning systems in the domains of language detection, text summarization, and emotion recognition. Outside of work, Nathan is currently writting a book on TensorFlow as an extension to his tutorial repository https://github.com/nlintz/TensorFlow-Tutorials
Link to video https://www.youtube.com/watch?v=op1QJbC2g0E&feature=youtu.be
Dynamic Programming and Reinforcement Learning applied to Tetris GameSuelen Carvalho
Slides presented as a work to Artificial Intelligence's class at IME-USP. This presentation is about how reinforcement learning is applied to a Tetris game.
Steffen Rendle, Research Scientist, Google at MLconf SFMLconf
Abstract:
Developing accurate recommender systems for a specific problem setting seems to be a complicated and time-consuming task: models have to be defined, learning algorithms derived and implementations written. In this talk, I present the factorization machine (FM) model which is a generic factorization approach that allows to be adapted to problems by feature engineering. Efficient FM learning algorithms are discussed among them SGD, ALS/CD and MCMC inference including automatic hyperparameter selection. I will show on several tasks, including the Netflix prize and KDDCup 2012, that FMs are flexible and generate highly competitive accuracy. With FMs these results can be achieved by simple data preprocessing and without any tuning of regularization parameters or learning rates.
An Introduction to core ideas, characteristics and benefits of functional programming and their implementation within the so called ‘object – functional’ language Scala.
Leaving the widely known concepts of object oriented programming aside, the focus is directed on how to leverage Scala in order to perform the following topics (extract):
* Functions and Function types
* Lambdas and Closures
* Currying and partial Argument Application
* Algebraic datatypes and Pattern matching
* Higher Order Functions
* Composition and Combinators
Slides for the Differential Machine Learning masterclass given by Brian Huge and Antoine Savine in Barcelona at the Quant Minds International event of December 2021.
This presentation summarises two years of research and development at Danske Bank on the pricing and risk of financial derivatives by machine learning and artificial intelligence.
The presentation develops the themes introduced in two articles in Risk Magazine, October 2020 and October 2021. Those themes are being further developed in the book Modern Computational Finance: Differential Machine Learning, with Chapman and Hall, autumn 2022.
Introduction to Factorization Machines model with an example. Motivations - why you should have it in your toolbox, model and it expressiveness, use case for context-aware recommendations and Field-Aware Factorization Machines.
I am Wycliffe S. I am a Python Homework Expert at pythonhomeworkhelp.com. I hold a Master's in Computer Science from, the University of Aberdeen, UK. I have been helping students with their homework for the past 13 years. I solve homework related to Python.
Visit pythonhomeworkhelp.com or email support@pythonhomeworkhelp.com. You can also call on +1 678 648 4277 for any assistance with Python Homework.
I am Ben R. I am a Statistics Assignment Expert at statisticshomeworkhelper.com. I hold a Ph.D. in Statistics, from University of Denver, USA. I have been helping students with their homework for the past 5 years. I solve assignments related to Statistics.
Visit statisticshomeworkhelper.com or email info@statisticshomeworkhelper.com.
You can also call on +1 678 648 4277 for any assistance with Statistics Assignments.
Presentation from Moscow Data Fest #1, September 12.
Moscow Data Fest is a free one-day event that brings together Data Scientists for sessions on both theory and practice.
Link: http://www.meetup.com/Moscow-Data-Fest/
Time Series Analysis:Basic Stochastic Signal RecoveryDaniel Cuneo
Simple case of a recovering a stochastic signal from a time series with a linear combination of nuisance signals.
Errata:
corrected error in the Gaussian fit.
corrected the JackKnife example and un-centers data.
Corrected sig fig language and rationale
removed jk calculation of mean reformatted cells
JLK Chapter 5 – Methods and ModularityDRAFT January 2015 Edition.docxvrickens
JLK Chapter 5 – Methods and ModularityDRAFT January 2015 Edition pg. 25
An Introduction to
Computer Science with Java, Python and C++
Community College of Philadelphia edition
Copyright 2017 by C.W. Herbert, all rights reserved.
Last edited October 8, 28, 2019 by C. W. Herbert
This document is a draft of a chapter from An Introduction to Computer Science with Java, Python and C++, written by Charles Herbert. It is available free of charge for students in Computer Science courses at Community College of Philadelphia during the Fall 2019 semester. It may not be reproduced or distributed for any other purposes without proper prior permission.
Please report any typos, other errors, or suggestions for improving the text to [email protected]
Chapter 5 – Python Functions and Modular Programming
Contents
Lesson 5.1User Created Functions in Python2
Python Function Parameters2
Value returning functions3
Example – Methods and Parameter Passing5
9
Lesson 5.2Top-Down Design and Modular Development10
Chapter Exercises13
User Created Functions in Python
So far we have only created software with one continuous Python script. We have used functions from other python modules, such as the square root method from the math class math.sqrt(n). Now we will begin to create our own functions of our own.
A Python function is a block of code that can be used to perform a specific task within a larger computer program. It can be called as needed from other Python software. Most programming languages have similar features, such as methods in Java or subroutines in system software.
The code for user-defined functions in Python is contained in a function definition. A Python function definition is a software unit with a header and a block of Python statements. The header starts with the keyword def followed by the name of the function, then a set parenthesis with any parameters for the function. A colon is used after the parentheses to indicate a block of code follows, just as with the if and while statements. The block of code to be included within the function is indented.
Here is an example of a Python function:
# firstFunction.py
# first demonstration of the use of a function for CSCI 111
# last edited 10/08/2o19 by C. Herbert
function
definition
def myFunction():
print ( "This line being printed by the function MyFunction.\n")
# end myFunction()
### main program ###
function used by the main part of the script
print("Beginning\n")
myFunction()
print("End\n")
# end main program
Functions can used for code that will be repeated within a program, or for modular development, in which long programs are broken into parts and the parts are developed independently. The parts can be developed as Python functions, then integrated to work together by being called from other software.
Python Function Parameters
Data can be passed to a Python function as a parameter of the function. Function parameters are variables listed in parentheses foll ...
Event Management System Vb Net Project Report.pdfKamal Acharya
In present era, the scopes of information technology growing with a very fast .We do not see any are untouched from this industry. The scope of information technology has become wider includes: Business and industry. Household Business, Communication, Education, Entertainment, Science, Medicine, Engineering, Distance Learning, Weather Forecasting. Carrier Searching and so on.
My project named “Event Management System” is software that store and maintained all events coordinated in college. It also helpful to print related reports. My project will help to record the events coordinated by faculties with their Name, Event subject, date & details in an efficient & effective ways.
In my system we have to make a system by which a user can record all events coordinated by a particular faculty. In our proposed system some more featured are added which differs it from the existing system such as security.
Sachpazis:Terzaghi Bearing Capacity Estimation in simple terms with Calculati...Dr.Costas Sachpazis
Terzaghi's soil bearing capacity theory, developed by Karl Terzaghi, is a fundamental principle in geotechnical engineering used to determine the bearing capacity of shallow foundations. This theory provides a method to calculate the ultimate bearing capacity of soil, which is the maximum load per unit area that the soil can support without undergoing shear failure. The Calculation HTML Code included.
Hybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdffxintegritypublishin
Advancements in technology unveil a myriad of electrical and electronic breakthroughs geared towards efficiently harnessing limited resources to meet human energy demands. The optimization of hybrid solar PV panels and pumped hydro energy supply systems plays a pivotal role in utilizing natural resources effectively. This initiative not only benefits humanity but also fosters environmental sustainability. The study investigated the design optimization of these hybrid systems, focusing on understanding solar radiation patterns, identifying geographical influences on solar radiation, formulating a mathematical model for system optimization, and determining the optimal configuration of PV panels and pumped hydro storage. Through a comparative analysis approach and eight weeks of data collection, the study addressed key research questions related to solar radiation patterns and optimal system design. The findings highlighted regions with heightened solar radiation levels, showcasing substantial potential for power generation and emphasizing the system's efficiency. Optimizing system design significantly boosted power generation, promoted renewable energy utilization, and enhanced energy storage capacity. The study underscored the benefits of optimizing hybrid solar PV panels and pumped hydro energy supply systems for sustainable energy usage. Optimizing the design of solar PV panels and pumped hydro energy supply systems as examined across diverse climatic conditions in a developing country, not only enhances power generation but also improves the integration of renewable energy sources and boosts energy storage capacities, particularly beneficial for less economically prosperous regions. Additionally, the study provides valuable insights for advancing energy research in economically viable areas. Recommendations included conducting site-specific assessments, utilizing advanced modeling tools, implementing regular maintenance protocols, and enhancing communication among system components.
Forklift Classes Overview by Intella PartsIntella Parts
Discover the different forklift classes and their specific applications. Learn how to choose the right forklift for your needs to ensure safety, efficiency, and compliance in your operations.
For more technical information, visit our website https://intellaparts.com
COLLEGE BUS MANAGEMENT SYSTEM PROJECT REPORT.pdfKamal Acharya
The College Bus Management system is completely developed by Visual Basic .NET Version. The application is connect with most secured database language MS SQL Server. The application is develop by using best combination of front-end and back-end languages. The application is totally design like flat user interface. This flat user interface is more attractive user interface in 2017. The application is gives more important to the system functionality. The application is to manage the student’s details, driver’s details, bus details, bus route details, bus fees details and more. The application has only one unit for admin. The admin can manage the entire application. The admin can login into the application by using username and password of the admin. The application is develop for big and small colleges. It is more user friendly for non-computer person. Even they can easily learn how to manage the application within hours. The application is more secure by the admin. The system will give an effective output for the VB.Net and SQL Server given as input to the system. The compiled java program given as input to the system, after scanning the program will generate different reports. The application generates the report for users. The admin can view and download the report of the data. The application deliver the excel format reports. Because, excel formatted reports is very easy to understand the income and expense of the college bus. This application is mainly develop for windows operating system users. In 2017, 73% of people enterprises are using windows operating system. So the application will easily install for all the windows operating system users. The application-developed size is very low. The application consumes very low space in disk. Therefore, the user can allocate very minimum local disk space for this application.
Welcome to WIPAC Monthly the magazine brought to you by the LinkedIn Group Water Industry Process Automation & Control.
In this month's edition, along with this month's industry news to celebrate the 13 years since the group was created we have articles including
A case study of the used of Advanced Process Control at the Wastewater Treatment works at Lleida in Spain
A look back on an article on smart wastewater networks in order to see how the industry has measured up in the interim around the adoption of Digital Transformation in the Water Industry.
Final project report on grocery store management system..pdfKamal Acharya
In today’s fast-changing business environment, it’s extremely important to be able to respond to client needs in the most effective and timely manner. If your customers wish to see your business online and have instant access to your products or services.
Online Grocery Store is an e-commerce website, which retails various grocery products. This project allows viewing various products available enables registered users to purchase desired products instantly using Paytm, UPI payment processor (Instant Pay) and also can place order by using Cash on Delivery (Pay Later) option. This project provides an easy access to Administrators and Managers to view orders placed using Pay Later and Instant Pay options.
In order to develop an e-commerce website, a number of Technologies must be studied and understood. These include multi-tiered architecture, server and client-side scripting techniques, implementation technologies, programming language (such as PHP, HTML, CSS, JavaScript) and MySQL relational databases. This is a project with the objective to develop a basic website where a consumer is provided with a shopping cart website and also to know about the technologies used to develop such a website.
This document will discuss each of the underlying technologies to create and implement an e- commerce website.
Vaccine management system project report documentation..pdfKamal Acharya
The Division of Vaccine and Immunization is facing increasing difficulty monitoring vaccines and other commodities distribution once they have been distributed from the national stores. With the introduction of new vaccines, more challenges have been anticipated with this additions posing serious threat to the already over strained vaccine supply chain system in Kenya.
Automobile Management System Project Report.pdfKamal Acharya
The proposed project is developed to manage the automobile in the automobile dealer company. The main module in this project is login, automobile management, customer management, sales, complaints and reports. The first module is the login. The automobile showroom owner should login to the project for usage. The username and password are verified and if it is correct, next form opens. If the username and password are not correct, it shows the error message.
When a customer search for a automobile, if the automobile is available, they will be taken to a page that shows the details of the automobile including automobile name, automobile ID, quantity, price etc. “Automobile Management System” is useful for maintaining automobiles, customers effectively and hence helps for establishing good relation between customer and automobile organization. It contains various customized modules for effectively maintaining automobiles and stock information accurately and safely.
When the automobile is sold to the customer, stock will be reduced automatically. When a new purchase is made, stock will be increased automatically. While selecting automobiles for sale, the proposed software will automatically check for total number of available stock of that particular item, if the total stock of that particular item is less than 5, software will notify the user to purchase the particular item.
Also when the user tries to sale items which are not in stock, the system will prompt the user that the stock is not enough. Customers of this system can search for a automobile; can purchase a automobile easily by selecting fast. On the other hand the stock of automobiles can be maintained perfectly by the automobile shop manager overcoming the drawbacks of existing system.
Overview of the fundamental roles in Hydropower generation and the components involved in wider Electrical Engineering.
This paper presents the design and construction of hydroelectric dams from the hydrologist’s survey of the valley before construction, all aspects and involved disciplines, fluid dynamics, structural engineering, generation and mains frequency regulation to the very transmission of power through the network in the United Kingdom.
Author: Robbie Edward Sayers
Collaborators and co editors: Charlie Sims and Connor Healey.
(C) 2024 Robbie E. Sayers
1. 10/13/2019 Python_For_Finance Chap5 Modeling Interest Rates and Derivatives - Jupyter Notebook
localhost:8888/notebooks/Desktop/PythonRelated/Mastering-Python-for-Finance-Second-Edition-master/Python_For_Finance Chap5 Modeling Interest Rates and … 1/17
5. Modeling Interest Rates and Derivatives
In [1]:
In [2]:
78.35261664684589
# A simple Python zero-coupon bond calculator
def zero_coupon_bond(par, y, t):
"""
Price a zero coupon bond.
:param par: face value of the bond.
:param y: annual yield or rate of the bond.
:param t: time to maturity, in years.
"""
return par/(1+y)**t
print(zero_coupon_bond(100, 0.05, 5))
2. 10/13/2019 Python_For_Finance Chap5 Modeling Interest Rates and Derivatives - Jupyter Notebook
localhost:8888/notebooks/Desktop/PythonRelated/Mastering-Python-for-Finance-Second-Edition-master/Python_For_Finance Chap5 Modeling Interest Rates and … 2/17
In [23]: # Boostrapping a yield curve
import math
class BootstrapYieldCurve(object):
def __init__(self):
self.zero_rates = dict()
self.instruments = dict()
def add_instrument(self, par, T, coup, price, compounding_freq=2):
self.instruments[T] = (par, coup, price, compounding_freq)
def get_maturities(self):
"""
:return: a list of maturities of added instruments
"""
return sorted(self.instruments.keys())
def get_zero_rates(self):
"""
Returns a list of spot rates on the yield curve.
"""
self.bootstrap_zero_coupons()
self.get_bond_spot_rates()
return [self.zero_rates[T] for T in self.get_maturities()]
def bootstrap_zero_coupons(self):
"""
Bootstrap the yield curve with zero coupon instruments first.
"""
for (T, instrument) in self.instruments.items():
(par, coup, price, freq) = instrument
if coup == 0:
spot_rate = self.zero_coupon_spot_rate(par, price, T)
self.zero_rates[T] = spot_rate
def zero_coupon_spot_rate(self, par, price, T):
"""
:return: the zero coupon spot rate with continuous compounding.
"""
spot_rate = math.log(par/price)/T
return spot_rate
def get_bond_spot_rates(self):
"""
Get spot rates implied by bonds, using short-term instruments.
"""
for T in self.get_maturities():
instrument = self.instruments[T]
(par, coup, price, freq) = instrument
if coup != 0:
spot_rate = self.calculate_bond_spot_rate(T, instrument)
self.zero_rates[T] = spot_rate
def calculate_bond_spot_rate(self, T, instrument):
try:
(par, coup, price, freq) = instrument
3. 10/13/2019 Python_For_Finance Chap5 Modeling Interest Rates and Derivatives - Jupyter Notebook
localhost:8888/notebooks/Desktop/PythonRelated/Mastering-Python-for-Finance-Second-Edition-master/Python_For_Finance Chap5 Modeling Interest Rates and … 3/17
In [24]:
In [27]:
periods = T*freq
value = price
per_coupon = coup/freq
for i in range(int(periods)-1):
t = (i+1)/float(freq)
spot_rate = self.zero_rates[t]
discounted_coupon = per_coupon*math.exp(-spot_rate*t)
value -= discounted_coupon
last_period = int(periods)/float(freq)
spot_rate = -math.log(value/(par+per_coupon))/last_period
return spot_rate
except:
print("Error: spot rate not found for T=", t)
yield_curve = BootstrapYieldCurve()
yield_curve.add_instrument(100, 0.25, 0., 97.5)
yield_curve.add_instrument(100, 0.5, 0., 94.9)
yield_curve.add_instrument(100, 1.0, 0., 90.)
yield_curve.add_instrument(100, 1.5, 8, 96., 2)
yield_curve.add_instrument(100, 2., 12, 101.6, 2)
y = yield_curve.get_zero_rates()
x = yield_curve.get_maturities()
4. 10/13/2019 Python_For_Finance Chap5 Modeling Interest Rates and Derivatives - Jupyter Notebook
localhost:8888/notebooks/Desktop/PythonRelated/Mastering-Python-for-Finance-Second-Edition-master/Python_For_Finance Chap5 Modeling Interest Rates and … 4/17
In [28]:
Populating the interactive namespace from numpy and matplotlib
Out[28]: Text(0.5, 0, 'Maturity in Years')
%pylab inline
fig = plt.figure(figsize=(12,8))
plot(x, y)
title("Zero Curve")
ylabel("Zero Rate (%)")
xlabel("Maturity in Years")
5. 10/13/2019 Python_For_Finance Chap5 Modeling Interest Rates and Derivatives - Jupyter Notebook
localhost:8888/notebooks/Desktop/PythonRelated/Mastering-Python-for-Finance-Second-Edition-master/Python_For_Finance Chap5 Modeling Interest Rates and … 5/17
In [29]:
In [31]:
In [32]:
In [35]:
In [37]:
[10.810999999999998, 10.603, 10.971, 11.189]
0.09369155345239477
#Forward rates
class ForwardRates(object):
def __init__(self):
self.forward_rates = []
self.spot_rates = dict()
def add_spot_rate(self, T, spot_rate):
self.spot_rates[T] = spot_rate
def get_forward_rates(self):
"""
Returns a list of forward rates
starting from the second time period.
"""
periods = sorted(self.spot_rates.keys())
for T2, T1 in zip(periods, periods[1:]):
forward_rate = self.calculate_forward_rate(T1, T2)
self.forward_rates.append(forward_rate)
return self.forward_rates
def calculate_forward_rate(self, T1, T2):
R1 = self.spot_rates[T1]
R2 = self.spot_rates[T2]
forward_rate = (R2*T2-R1*T1)/(T2-T1)
return forward_rate
fr = ForwardRates()
fr.add_spot_rate(0.25, 10.127)
fr.add_spot_rate(0.50, 10.469)
fr.add_spot_rate(1.00, 10.536)
fr.add_spot_rate(1.50, 10.681)
fr.add_spot_rate(2.00, 10.808)
print(fr.get_forward_rates())
#Calculating the yield to maturity(given price)
import scipy.optimize as optimize
def bond_ytm(price, par, T, coup, freq=2, guess=0.05):
freq = float(freq)
periods = T*2
coupon = coup/100.*par
dt = [(i+1)/freq for i in range(int(periods))]
ytm_func = lambda y:
sum([coupon/freq/(1+y/freq)**(freq*t) for t in dt]) +
par/(1+y/freq)**(freq*T) - price
return optimize.newton(ytm_func, guess)
ytm = bond_ytm(95.0428, 100, 1.5, 5.75, 2)
print(ytm)
6. 10/13/2019 Python_For_Finance Chap5 Modeling Interest Rates and Derivatives - Jupyter Notebook
localhost:8888/notebooks/Desktop/PythonRelated/Mastering-Python-for-Finance-Second-Edition-master/Python_For_Finance Chap5 Modeling Interest Rates and … 6/17
In [39]:
In [41]:
In [44]:
In [47]:
In [48]:
95.04280000000004
1.3921935426560885
# Calculating the price of a bond(given ytm)
def bond_price(par, T, ytm, coup, freq=2):
freq = float(freq)
periods = T*2
coupon = coup/100.*par
dt = [(i+1)/freq for i in range(int(periods))]
price = sum([coupon/freq/(1+ytm/freq)**(freq*t) for t in dt]) +
par/(1+ytm/freq)**(freq*T)
return price
price = bond_price(100, 1.5, ytm, 5.75, 2)
print(price)
#Bond duration
def bond_mod_duration(price, par, T, coup, freq, dy=0.01):
ytm = bond_ytm(price, par, T, coup, freq)
ytm_minus = ytm - dy
price_minus = bond_price(par, T, ytm_minus, coup, freq)
ytm_plus = ytm + dy
price_plus = bond_price(par, T, ytm_plus, coup, freq)
mduration = (price_minus-price_plus)/(2*price*dy)
return mduration
mod_duration = bond_mod_duration(95.0428, 100, 1.5, 5.75, 2)
print(mod_duration)
#Bond convexity
def bond_convexity(price, par, T, coup, freq, dy=0.01):
ytm = bond_ytm(price, par, T, coup, freq)
ytm_minus = ytm - dy
price_minus = bond_price(par, T, ytm_minus, coup, freq)
ytm_plus = ytm + dy
price_plus = bond_price(par, T, ytm_plus, coup, freq)
convexity = (price_minus + price_plus - 2*price)/(price*dy**2)
return convexity
7. 10/13/2019 Python_For_Finance Chap5 Modeling Interest Rates and Derivatives - Jupyter Notebook
localhost:8888/notebooks/Desktop/PythonRelated/Mastering-Python-for-Finance-Second-Edition-master/Python_For_Finance Chap5 Modeling Interest Rates and … 7/17
In [49]:
In [50]:
Populating the interactive namespace from numpy and matplotlib
Out[50]: Text(0.5, 0, 'Vasicek model')
#Short-rate modeling
#The Vasicek model
import math
import numpy as np
def vasicek(r0, K, theta, sigma, T=1., N=10, seed=777):
np.random.seed(seed)
dt = T/float(N)
rates = [r0]
for i in range(N):
dr = K*(theta-rates[-1])*dt +
sigma*math.sqrt(dt)*np.random.normal()
rates.append(rates[-1]+dr)
return range(N+1), rates
%pylab inline
fig = plt.figure(figsize=(12,8))
for K in [0.002, 0.02, 0.2]:
x, y = vasicek(0.005, K, 0.15, 0.05, T=10, N=200)
plot(x,y, label='K=%s'%K)
pylab.legend(loc='upper left');
pylab.legend(loc='upper left')
pylab.xlabel('Vasicek model')
8. 10/13/2019 Python_For_Finance Chap5 Modeling Interest Rates and Derivatives - Jupyter Notebook
localhost:8888/notebooks/Desktop/PythonRelated/Mastering-Python-for-Finance-Second-Edition-master/Python_For_Finance Chap5 Modeling Interest Rates and … 8/17
In [52]:
In [53]:
Populating the interactive namespace from numpy and matplotlib
#The Cox-Ingersoll-Ross model
import math
import numpy as np
def CIR(r0, K, theta, sigma, T=1., N=10, seed=777):
np.random.seed(seed)
dt = T/float(N)
rates = [r0]
for i in range(N):
dr = K*(theta-rates[-1])*dt +
sigma*math.sqrt(rates[-1])*
math.sqrt(dt)*np.random.normal()
rates.append(rates[-1] + dr)
return range(N+1), rates
%pylab inline
fig = plt.figure(figsize=(12, 8))
for K in [0.002, 0.02, 0.2]:
x, y = CIR(0.005, K, 0.15, 0.05, T=10, N=200)
plot(x,y, label='K=%s'%K)
pylab.legend(loc='upper left')
pylab.xlabel('CRR model');
9. 10/13/2019 Python_For_Finance Chap5 Modeling Interest Rates and Derivatives - Jupyter Notebook
localhost:8888/notebooks/Desktop/PythonRelated/Mastering-Python-for-Finance-Second-Edition-master/Python_For_Finance Chap5 Modeling Interest Rates and … 9/17
In [55]:
In [56]:
Populating the interactive namespace from numpy and matplotlib
#The Rendleman and Bartter model
import math
import numpy as np
def rendleman_bartter(r0, theta, sigma, T=1., N=10, seed=777):
np.random.seed(seed)
dt = T/float(N)
rates = [r0]
for i in range(N):
dr = theta*rates[-1]*dt +
sigma*rates[-1]*math.sqrt(dt)*np.random.normal()
rates.append(rates[-1] + dr)
return range(N+1), rates
%pylab inline
fig = plt.figure(figsize=(12,8))
for theta in [0.01, 0.05, 0.1]:
x, y = rendleman_bartter(0.005, theta, 0.05, T=10, N=200)
plot(x,y, label='theta=%s'%theta)
pylab.legend(loc='upper left')
pylab.xlabel('Rendleman and Bartter model');
10. 10/13/2019 Python_For_Finance Chap5 Modeling Interest Rates and Derivatives - Jupyter Notebook
localhost:8888/notebooks/Desktop/PythonRelated/Mastering-Python-for-Finance-Second-Edition-master/Python_For_Finance Chap5 Modeling Interest Rates and … 10/17
In [61]:
In [62]:
Populating the interactive namespace from numpy and matplotlib
#The Brennan and Schwartz model
import math
import numpy as np
def brennan_schwartz(r0, K, theta, sigma, T=1., N=10, seed=777):
np.random.seed(seed)
dt = T/float(N)
rates = [r0]
for i in range(N):
dr = K*(theta-rates[-1])*dt +
sigma*rates[-1]*math.sqrt(dt)*np.random.normal()
rates.append(rates[-1] + dr)
return range(N+1), rates
%pylab inline
fig = plt.figure(figsize=(12, 8))
for K in [0.2, 0.02, 0.002]:
x, y = brennan_schwartz(0.005, K, 0.006, 0.05, T=10, N=200)
plot(x,y, label='K=%s'%K)
pylab.legend(loc='upper left')
pylab.xlabel('Brennan and Schwartz model');
11. 10/13/2019 Python_For_Finance Chap5 Modeling Interest Rates and Derivatives - Jupyter Notebook
localhost:8888/notebooks/Desktop/PythonRelated/Mastering-Python-for-Finance-Second-Edition-master/Python_For_Finance Chap5 Modeling Interest Rates and … 11/17
In [65]:
In [66]:
In [67]:
Populating the interactive namespace from numpy and matplotlib
#Pricing a callable bond option
#Pricing a zero-coupon bond by the Vasecek model
import numpy as np
import math
def exact_zcb(theta, kappa, sigma, tau, r0=0.):
B = (1 - np.exp(-kappa*tau)) / kappa
A = np.exp((theta-(sigma**2)/(2*(kappa**2)))*(B-tau) -
(sigma**2)/(4*kappa)*(B**2))
return A * np.exp(-r0*B)
Ts = np.r_[0.0:25.5:0.5]
zcbs = [exact_zcb(0.5, 0.02, 0.03, t, 0.015) for t in Ts]
%pylab inline
fig = plt.figure(figsize=(12,8))
plt.title("Zero Coupon Bond (ZCB) Values by Time")
plt.plot(Ts, zcbs, label='ZCB')
plt.ylabel("Value ($)")
plt.xlabel("Time in years")
plt.legend()
plt.grid(True)
plt.show()
12. 10/13/2019 Python_For_Finance Chap5 Modeling Interest Rates and Derivatives - Jupyter Notebook
localhost:8888/notebooks/Desktop/PythonRelated/Mastering-Python-for-Finance-Second-Edition-master/Python_For_Finance Chap5 Modeling Interest Rates and … 12/17
In [68]:
In [69]:
In [70]:
In [77]:
#Value of early-exercise
import math
def exercise_value(K, R, t):
return K*math.exp(-R*t)
Ts = np.r_[0.0:25.5:0.5]
Ks = [exercise_value(0.95, 0.015, t) for t in Ts]
zcbs = [exact_zcb(0.5, 0.02, 0.03, t, 0.015) for t in Ts]
import matplotlib.pyplot as plt
fig = plt.figure(figsize=(12, 8))
plt.title("Zero Coupon Bond (ZCB) and Strike (K) Values by Time")
plt.plot(Ts, zcbs, label='ZCB')
plt.plot(Ts, Ks, label='K', linestyle="--", marker=".")
plt.ylabel("Value ($)")
plt.xlabel("Time in years")
plt.legend()
plt.grid(True)
plt.show()
#Policy iteration by finite differences
import math
import numpy as np
import scipy.stats as st
13. 10/13/2019 Python_For_Finance Chap5 Modeling Interest Rates and Derivatives - Jupyter Notebook
localhost:8888/notebooks/Desktop/PythonRelated/Mastering-Python-for-Finance-Second-Edition-master/Python_For_Finance Chap5 Modeling Interest Rates and … 13/17
In [81]: #Callable zero-coupon bond by Vasicek
class VasicekCZCB:
def __init__(self):
self.norminv = st.distributions.norm.pdf
self.norm = st.distributions.norm.cdf
def vasicek_czcb_values(self, r0, R, ratio, T, sigma, kappa, theta,
M, prob=1e-6, max_policy_iter=10,
grid_struct_const=0.25, rs=None):
(r_min, dr, N, dtau) =
self.vasicek_params(r0, M, sigma, kappa, theta,
T, prob, grid_struct_const, rs)
r = np.r_[0:N]*dr + r_min
v_mplus1 = np.ones(N)
for i in range(1, M+1):
K = self.exercise_call_price(R, ratio, i*dtau)
eex = np.ones(N)*K
(subdiagonal, diagonal, superdiagonal) =
self.vasicek_diagonals(
sigma, kappa, theta, r_min, dr, N, dtau)
(v_mplus1, iterations) =
self.iterate(subdiagonal, diagonal, superdiagonal,
v_mplus1, eex, max_policy_iter)
return r, v_mplus1
def vasicek_params(self, r0, M, sigma, kappa, theta, T,
prob, grid_struct_const=0.25, rs=None):
if rs is not None:
(r_min, r_max) = (rs[0], rs[-1])
else:
(r_min, r_max) = self.vasicek_limits(
r0, sigma, kappa, theta, T, prob)
dt = T/float(M)
N = self.calculate_N(grid_struct_const, dt, sigma, r_max, r_min)
dr = (r_max-r_min)/(N-1)
return (r_min, dr, N, dt)
def calculate_N(self, max_structure_const, dt, sigma, r_max, r_min):
N = 0
while True:
N += 1
grid_structure_interval =
dt*(sigma**2)/(((r_max-r_min)/float(N))**2)
if grid_structure_interval > max_structure_const:
break
return N
def vasicek_limits(self, r0, sigma, kappa, theta, T, prob=1e-6):
er = theta+(r0-theta)*math.exp(-kappa*T)
variance = (sigma**2)*T if kappa==0 else