Ned Krastev
Python for Finance
365 DATA SCENCE 2
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
Python. You will learn to :
• Calculate and compare rates of return in Python
• Use Monte Carlo simulations as a decision-making tool
• Use regressions for financial analysis
• Apply the Markowitz Portfolio Theory
• Work with multivariate regression analysis
Keywords: Python for Finance, Monte Carlo , financial analyses , regression, Markowitz
Portfolio Theory
365 DATA SCENCE 4
1. Calculating and Comparing Rates of Return in Python
1.1 Upside and Downside
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.
Type of asset Definition
Government bonds Government bonds offer an average rate of return
of 3%, and historically, there have been very few
cases of governments going bankrupt and not
repaying what’s owed to investors. So, some risk
comes with this investment; it isn’t risk-free, but
the risk is very contained.
Equity shares Equity shares have a higher rate of return –
approximately 6%. However, they are associated
with much more frequent fluctuations and
price changes, as different variables influence a
company’s share price.
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
1.2 Calculating Rates of Return
Type of asset Definition
Simple returns (Ending Price – Beginning Price) / (Beginning
Price)
Preferable when you have to deal with multiple
assets over the same timeframe
Log returns Log (Ending Price / Beginning Price)
Preferable when you make calculations about a
single asset over time
1.3 Portfolios of Stocks
Most investors own several stocks, and the set of stocks that an investor owns is called
his investment portfolio.
Investment Portfolio
Stock A Stock B Stock C
Stock 1 Stock 2 Stock 3
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
1.4 Market Indices
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.
Market Index Description
S&P500 Comprises 500 of the largest listed companies.
The diverse constituency of the S&P 500 makes it
a true approximation of the US stock market. It is
a market-cap-weighted index, so companies are
weighted according to their market value
Dow Jones Industrial The Dow Jones industrial average index uses an
Average average of 30 large public stocks traded in the US
market
NASDAQ Most companies that are part of the NASDAQ
index are information technology companies,
and NASDAQ gives us an idea about the general
development of the tech industry
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
2. Measuring Investment Risk
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.
2.1 The Relationship between Securities
It is reasonable to expect the prices of shares in a stock exchange are influenced
by common factors. The most obvious example is the development of the economy.
In general, favorable macroeconomic conditions facilitate the business of all
companies.
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.
There is a relationship between the prices of different companies, and it is
very important to understand what causes this relationship and how to use this
measurement to build optimal investment portfolios.
2.2 Calculating Covariance and Correlation
Calculating
Covariance:
Calculating
Correlation:
Market Index Description
Perfect correlation Equal to 1. The entire variability of the second
variable is explained by the first variable
Negative correlation It can be perfect negative correlation of -1 or
much likelier an imperfect negative correlation of
a value between -1 and 0
Neutral correlation A correlation of 0 between two variables means
they are independent from each other
365 DATA SCENCE 9
2.3 Calculating Portfolio Variance
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.
Type of risk Description
Systematic risk This is the uncertainty that is characteristic of the
entire market. Systematic risk is made of the day
to day changes in stock prices and is caused by
events that affect all companies
Unsystematic risk These are company-specific, even industry-
specific, risks that can be smoothed out through
diversification
365 DATA SCENCE 10
3. Using Regression for Financial Analyses
3.1 Regression Analysis
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.
Type of regression Description
Simple regressions
Regression analysis assumes the existence of a
linear relationship between the two variables. One
straight line is the best fit and can help us describe
the rapport between all the data points we see in
the plot
Multivariate regressions
By considering more variables in the regression
equation, we’ll improve its explanatory power
and provide a better idea of the full picture of
circumstances that determine the development of
the variable we are trying to predict
365 DATA SCENCE 11
In order to calculate regression coefficients, we are estimating a best fitting line
minimizing the sum of squared residuals.
$ 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)
Minimizing residuals (the amount of estimation error) in a simple regression setting
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
Minimizing residuals (the amount of estimation error) in a multivariate regression
setting
Simple regression Multivariate regression
365 DATA SCENCE 12
3.2 How Good is a Regression?
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.
The total variability of the data can also be decomposed as:
where SSE is the sum of the squares that were explained, and SSR is the sum of the
squared residuals (unexplained)
4. Markowitz Portfolio Optimization
Typically, R square is looked at as a percentage value, and it can range from 0% to
100%. The higher it is, the greater the explanatory power of the regression model
(the lower the weight of unexplained squares, the better the model).
365 DATA SCENCE 13
4.1 Efficient Frontier
Markowitz proved the existence of an efficient set of portfolios that optimize
investors’ return for the amount of risk they are willing to accept.
One of the most important highlights of his work is that investments in multiple
securities shouldn’t be analyzed separately, but should be considered in a portfolio,
and financiers must understand how different securities in a portfolio interact with
each other.
Portfolios 1-6 Markowitz Shape
10.0%
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
Markowitz suggested that through the combination of securities with low
correlation, investors can optimize their returns without assuming additional risk.
365 DATA SCENCE 14
5. The Capital Asset Pricing Model
William Sharpe’s Capital Asset Pricing Model contains:
Market Index Description
Market portfolio A bundle of all possible investments in the world
(both bonds and stocks), and the risk-return
combination of this portfolio is superior to the one
of any other portfolio
Risk-free asset An investment with no risk (zero standard
deviation). It has a positive rate of return, but zero
risk associated with it
Beta coefficient It helps us quantify the relationship between a
security and the overall market portfolio
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
Expecter Returns Capital Market Line
Efficient Frontier
Tangency Portfolio
Individual Assets
risk free race
Standart Deviation
• The Tangency portfolio is the Market portfolio
• Individual assets (portfolios of assets) that are not lying on the efficient frontier are
inefficient
• The risk-free rate has a standard deviation of 0
• The tangency portfolio lies on the Capital Market Line
• Once we introduce a risk-free asset, all investors would be interested in buying
only two assets – the risk-free asset and the Market portfolio (the Tangency
portfolio)
The CAPM formula:
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.
Risk-free: The minimum amount of compensation an investor would expect from an
investment
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
5.1 Sharpe Ratio
The Sharpe ratio formula:
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.
5.2 Achieving alpha
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.
5.3 Types of Investment Strategies
Type of correlation Description
Passive Investing Consists in buying a portfolio of assets and holding it in
the long-run regardless of short-term macroeconomic
developments
Active Investing Frequent trading based on expectations regarding
macroeconomic and company-specific developments,
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
6. Monte Carlo Simulations
Simulated Asset Paths
58
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.
6.1 Monte Carlo in a Corporate Finance Setting
Type of correlation Description
Revenues Current revenues = Previous revenues * (1 + growth rate)
Growth rate is the unknown variable. We can simulate its
development if we know its distribution, mean, and standard
deviation. This would allow us to obtain multiple simulations
about the development of revenues
Cost of Cost of goods sold = Percentage of revenues; For each
goods sold “revenue path” Cogs can be simulated as a percentage
of the observed amount of revenues. All we have to do is
simulate the percentage as a random variable with a known
distribution, mean, and standard deviation
Gross profit Revenues – Cost of goods sold = Gross profit
365 DATA SCENCE 18
Type of correlation Description
Revenues Current revenues = Previous revenues * (1 + growth rate)
Growth rate is the unknown variable. We can simulate
its development if we know its distribution, mean, and
standard deviation. This would allow us to obtain multiple
simulations about the development of revenues
Cost of goods sold Cost of goods sold = Percentage of revenues; For each
“revenue path” Cogs can be simulated as a percentage
of the observed amount of revenues. All we have to do is
simulate the percentage as a random variable with a known
distribution, mean, and standard deviation
Gross profit Revenues – Cost of goods sold = Gross profit
6.2 Asset Pricing with Monte Carlo
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
Which is equal to:
365 DATA SCENCE 19
We know yesterday’s stock price. We don’t know r, as it is a random variable. Brownian
motion is a concept that would allow us to model such randomness. The formula we
can use is made of two components:
Drift Random component
365 DATA SCENCE 20
7. Derivative Instruments
Originally, derivatives served as a hedging instrument. Companies interested in
buying these contracts were mostly concerned about protecting their investment.
However, with time, financial institutions introduced a great deal of innovation to the
scene, the so-called financial engineering was applied, and new types of derivatives
appeared.
Type of correlation Description
Forwards A forward contract is used when two parties agree
that one party will sell to the other an underlying
asset at a future point of time. The price of the
asset is agreed beforehand.
Futures Futures are highly standardized forward contracts
typically stipulated in a marketplace. The
difference between futures and forwards is the
level of standardization and the participation of a
clearing house – the transaction goes through the
marketplace, and the counterparties do not know
each other.
Swaps Swap contracts are derivative instruments in which
two parties agree to exchange cash flows, based
on an underlying asset at a future point of time.
The underlying asset can be an interest rate, a
stock price, a bond price, a commodity price, and
so on.
Options An option contract enables its owner to buy or
sell an underlying asset at a price, also known as
strike price. The owner of the option contract may
buy or sell the asset at the given price, but he may
also decide not to do it if the asset’s price isn’t
advantageous.
365 DATA SCENCE 21
7.1 Forward / Future contracts
The two parties enter into an agreement to buy/sell an asset at time T.
Contract
Today A B
Side A Side B
Money
A B
Side A Asset Side B
A forward/future contract has the following payoff:
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
7.2 Option Contracts
There are two main types of options.
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
Side A Asset Side B
At time T, the owner of the option decides whether to exercise it or not:
Scenario 1: Exercise
K
A B
Side A St Side B
Scenario 2: Don’t exercise
Don’t do
A anything B
Side A Side B
365 DATA SCENCE 23
A call option contract has the following payoff:
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.
A put option contract has the following payoff:
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
7.3 Swap Contracts
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
Cash flow = Price of Asset 1 – Price of Asset 2
A swap contract has the following payoff:
Payoff
The payoff of a swap is a function of the price of the underlying asset.
365 DATA SCENCE 25
7.4 Pricing Derivatives
The Black Scholes formula is one of the most widely used tools for derivatives pricing.
It can be written in the following way:
Type of correlation Description
S The stock’s current market price
K The strike price at which the option can be
exercised; if we exercise the option, we can buy
the stock at the strike price K
T-t The option’s time until expiration
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:
Type of correlation Description
S The standard deviation of the underlying asset
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.
Comprehensive training, exams, certificates.
162 hours of video Exams & Certification Portfolio advice
599+ Exercises Personalized support New content
Downloadables Resume Builder & Feedback Career tracks
Join a global community of 1.8 M successful students with an annual subscription
at 60% OFF with coupon code 365RESOURCES.
$432 $172.80/year
Start at 60% Off
Ned Krastev
Email: team@365datascience.com