Python For Finance - Course Notes
Python For Finance - Course Notes
Table of Contents
Abstract .................................................................................................................................... 3
1. Calculating and Comparing Rates of Return in Python .................................................. 4
1.1 Upside and Downside ................................................................................................. 4
1.2 Calculating Rates of Return ..........................................................................................5
1.3 Portfolios of Stocks ....................................................................................................... 5
1.4 Market Indices ............................................................................................................... 6
2. Measuring Investment Risk ................................................................................................ 7
2.1 The Relationship between Securities ........................................................................ 7
2.2 Calculating Covariance and Correlation ................................................................... 8
2.3 Calculating Portfolio Variance .................................................................................... 9
3. Using Regression for Financial Analyses ........................................................................ 10
3.1 Regression Analysis ...................................................................................................11
3.2 How Good is a Regression? ....................................................................................... 12
4. Markowitz Portfolio Optimization ..................................................................................12
4.1 Efficient Frontier ..............................................................................................................13
5.The Capital Asset Pricing Model .......................................................................................... 14
5.1 Sharpe Ratio ...................................................................................................................16
5.2 Achieving Alpha .........................................................................................................16
5.3 Types of Investment Strategies ...................................................................................16
6.Monte Carlo Simulations ................................................................................................... 17
6.1 Monte Carlo in Corporate Financial Setting ............................................................ 17
6.2 Asset Pricing with Monte Carlo ................................................................................. 18
7. Derivative Instruments .........................................................................................................20
7.1 Future/Forward Contracts ..........................................................................................21
7.2 Option Contracts ........................................................................................................22
7.3 Swap Contracts ..........................................................................................................24
7.4 Pricing Derivatives ......................................................................................................25
365 DATA SCENCE 3
Abstract
Python for Finance is the crossing point where programming in Python blends
with financial theory. Together, they give you the know-how to apply that theory
into practice and real-life scenarios. In a world where individuals and companies are
aiming to become more and more autonomous, your ability to combine programming
skills with financial data will allow you to create independent analyses. And that
competency will give you an edge over your competitors or in your personal
investments. To prepare you for these multi-faceted challenges, these course notes
provides the relevant topics in financial theory and their hands-on application in
Keywords: Python for Finance, Monte Carlo , financial analyses , regression, Markowitz
Portfolio Theory
365 DATA SCENCE 4
When we think of an investment, we have to remember two things – its upside and
its downside. In other words, we should consider the profit that will be made if
everything goes well and the risk of losses if the investment is unsuccessful.
The art of finance isn’t about maximizing an investor’s returns in a year. It is about
making informed decisions that consider both dimensions, risk and return, and
optimizing the risk-return combination of an investment portfolio.
365 DATA SCENCE 5
Most investors own several stocks, and the set of stocks that an investor owns is called
his investment portfolio.
Investment Portfolio
Calculating the rate of return of a portfolio is an easy and intuitive task. We have the
rates of return of individual securities, and we only have to multiply each security’s rate
of return by the weight it has in the overall portfolio.
365 DATA SCENCE 6
A market index provides an idea about how a given stock market is performing. It
represents a large enough sample of the overall number of stocks in that market and
can be considered a good enough proxy of the overall development of the market.
A stock index gives you a sense of the type of return you can expect if you invest in
a well-diversified portfolio in a given market.
365 DATA SCENCE 7
Variability plays an important role in the world of finance. It is the best measure of risk
we have. A volatile stock is much more likely to deviate from its historical returns and
surprise investors negatively.
s2 = ∑ (x-x)2 / n-1
Sample variance Standard deviation
Commonly used statistical measures, such as variance and standard deviation, can
help us a great deal when we try to quantify risk associated with the dispersion in the
likely outcome. Such dispersion is measured by a security’s variance and standard
deviation.
Busines
Jobs
Consumer spending
365 DATA SCENCE 8
Companies’ shares are influenced by the state of the economy. However, different
industries are influenced in a different way. Some industries do better than others in
times of crisis.
Calculating
Covariance:
Calculating
Correlation:
If a portfolio contains two stocks, its risk will be a function of the variances of the two
stocks and of the correlation between them.
Regression analysis is one of the most frequently used tools in the world of finance.
It quantifies the relationship between a variable, called dependent variable, and one
or more explanatory variables, also called independent variables.
Simple regressions
Multivariate regressions
$ 1,400,000
$ 1,200,000
$ 1,000,000
Price (y)
$ 800,000
$ 600,000
Estimation
$ 400,000 error
$ 200,000
50
0 200 400 600 800 1000 1200
Size (x)
240
210
200
180
Y1 160
140
120
50
70 60 90
50 40 70 80
30 20 40 50 60
10 20 30 X3
X1
Statisticians have come up with a tool that’s easy to understand. It is called R2.
To understand R2, we need to think of the total variability of the data. TSS provides a
sense of the variability of the data. The formula for the variance of x is the same,
but N – 1 is omitted.
where SSE is the sum of the squares that were explained, and SSR is the sum of the
squared residuals (unexplained)
9.5%
9.0%
8.5%
Return
8.0%
7.5%
7.0%
6.5%
6.0%
4.0% 5.0% 6.0% 7.0% 8.0% 9.0%
Standart deviation
Capital Market Line The line that connects the risk-free rate and
is tangent to the efficient frontier is called the
Capital Market Line. The point where the Capital
Market Line is tangent to the efficient frontier is
the market portfolio
365 DATA SCENCE 15
Efficient Frontier
Tangency Portfolio
Individual Assets
Standart Deviation
A security’s expected return is equal to the return of the risk-free asset plus beta times
the expected return of the market minus the return of the risk-free asset.
Beta coefficient: How risky is the specific asset with respect to the market
Market Risk Premium: The amount of compensation an investor would expect when
buying the Market portfolio
365 DATA SCENCE 16
Rational investors want to maximize their rate of return and minimize the risk of their
investment, so they need a measure of risk-adjusted return, a tool that would allow
them to compare different securities, as they will be interested in investing in the ones
that will provide the highest return for a given amount of risk.
This is how William Sharpe came up with his famous Sharpe ratio. It is a great way to
make a proper comparison between stocks and portfolios and decide which one is
preferable in terms of risk and return.
What is alpha?
In the world of finance and investments, alpha is often thought of as a measure of how
good (or poor) the performance of a fund manager has been. The standard CAPM
setting assumes efficient financial market and an alpha of 0. Given that beta multiplied
by the equity risk premium gives us the compensation for risk that’s been taken with
the investment, alpha shows us how much return we get without bearing extra risk. A
great portfolio manager, someone who outperforms the market, can achieve a high
alpha. And conversely, a poor investment professional may even obtain a negative
alpha, meaning he underperformed the market.
Arbitrage Trading Find pricing discrepancies on the market and exploit these
discrepancies in order to make a profit without assuming risk
Value Investing Invest in specific companies, hoping they will outperform
their peers
365 DATA SCENCE 17
56
54
Asset Price
53
50
48
46
44
50 45 40 35 30 25 20 15 10 5 0
Time to Expiry
When we run a Monte Carlo simulation, we are interested in observing the different
possible realizations of a future event. What happens in real life is just one of the
possible outcomes of any event.
And that’s where a Monte Carlo simulation comes in handy. We can use past data,
something we already know, to create a simulation – a new set of fictional but sensible
data. These realizations are generated by observing the distribution of the historical
data and calculating its mean and variance.
Such information is valuable, as it allows us to consider a good proxy of the probability
of different outcomes and can help us make an informed decision.
The price of a share today is equal to the price of the same share yesterday multiplied
by the log return of the share (r). Remember that:
e in(x) = x
So, above we have written:
Price Today
in ( )
Price Yesterday
7. Derivative Instruments
Contract
Today A B
Side A Side B
Money
A B
Payoff
The payoff of a forward/future contract is a function of the agreed price when the
contract is signed (K), and the price of the asset at time t
365 DATA SCENCE 22
Call Options – the holder has the right to buy an asset at an agreed strike price.
Put Options – the holder has the right to sell an asset at an agreed strike price
Contract
Today A B
Side A Side B
Money
A B
Scenario 1: Exercise
K
A B
Side A St Side B
Don’t do
A anything B
Side A Side B
365 DATA SCENCE 23
Payoff
The payoff of an option is a function of the agreed strike price when the contract
is signed (K), and the price of the asset at the time of maturity of the option (St). In
addition, there are two types of options – European and American. European options
can be exercised only at maturity, while American options can be exercised at any time
and are hence more valuable.
Payoff
The payoff of an option is a function of the agreed strike price when the contract
is signed (K), and the price of the asset at the time of maturity of the option (St). In
addition, there are two types of options – European and American. European options
can be exercised only at maturity, while American options can be exercised at any time
and are hence more valuable.
365 DATA SCENCE 24
In a swap contract, the two parties agree to exchange cash flows based on an
underlying asset.
Contract
Today A B
Side A St Side B
Asset 1
t=T A B
Asset 2
Side A Side B
Payoff
The Black Scholes formula is one of the most widely used tools for derivatives pricing.
It can be written in the following way:
r Risk-free rate
The Black Scholes formula is one of the most widely used tools for derivatives pricing.
It can be written in the following way:
N Normal distribution
Copyright 2022 365 Data Science Ltd. Reproduction is forbidden unless authorized. All rights reserved.
Learn DATA SCIENCE
anytime, anywhere, at your own pace.
If you found this resource useful, check out our e-learning program. We have
everything you need to succeed in data science.
Learn the most sought-after data science skills from the best experts in the field!
Earn a verifiable certificate of achievement trusted by employers worldwide and
future proof your career.
$432 $172.80/year
Email: team@365datascience.com