Python For Finance Course Notes PDF
Python For Finance Course Notes PDF
Course Notes
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.
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.
Calculating rates of return
Term Definition
Preferable when you have to deal with multiple assets over the same
timeframe
Preferable when you make calculations about a single asset over time
Portfolios of stocks
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.
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.
Dow Jones Industrial Average The Dow Jones industrial average index uses an 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.
Measuring 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.
2
2
σ 𝑥 − 𝑥ҧ
𝑠 =
𝑛−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.
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.
Business
Jobs
Consumer spending
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.
Calculating Covariance and Correlation
Calculating Covariance:
Calculating Correlation:
Perfect correlation Equal to 1. The entire variability of the second variable is explained by
the first variable
Neutral correlation A correlation of 0 between two variables means they are independent
from each other
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.
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
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.
In order to calculate regression coefficients, we are estimating a best fitting line minimizing the sum of
squared residuals.
Y = 1,000+0.8*x1 Y = 600+0.8*x1+0.4*x2+0.3*x3
2
σ 𝑥 − 𝑥ҧ 2
𝑠2 = TSS= σ 𝑥 − 𝑥ҧ
𝑛−1
𝑆𝑆𝑅
𝑅2 = 1 − 𝑅 2 𝜖[0; 1]
𝑆𝑆𝑇
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).
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%
Standard deviation
Markowitz suggested that through the combination of securities with low correlation, investors
can optimize their returns without assuming additional risk.
The Capital Asset Pricing Model
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
The Capital Asset Pricing Model
𝑟𝑖 = 𝑟𝑓 + β𝑖𝑚 (𝑟𝑚− 𝑟𝑓 )
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
Sharpe Ratio
𝑟𝑖− 𝑟𝑓
Sharpe Ratio =
σ𝑖
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.
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.
Types of Investment Strategies
Passive Investing Consists in buying a portfolio of assets and holding it in the long-run
regardless of short-term macroeconomic 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
Monte Carlo Simulations
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.
Monte Carlo in a Corporate Finance setting
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
𝑒 ln(𝑥) = 𝑥
So, above we have written:
𝑃𝑟𝑖𝑐𝑒 𝑇𝑜𝑑𝑎𝑦
ln( )
𝑃𝑟𝑖𝑐𝑒 𝑇𝑜𝑑𝑎𝑦 = 𝑃𝑟𝑖𝑐𝑒 𝑌𝑒𝑠𝑡𝑒𝑟𝑑𝑎𝑦 ∗ 𝑒 𝑃𝑟𝑖𝑐𝑒 𝑌𝑒𝑠𝑡𝑒𝑟𝑑𝑎𝑦
Which is equal to:
𝑃𝑟𝑖𝑐𝑒 𝑇𝑜𝑑𝑎𝑦
𝑃𝑟𝑖𝑐𝑒 𝑇𝑜𝑑𝑎𝑦 = 𝑃𝑟𝑖𝑐𝑒 𝑌𝑒𝑠𝑡𝑒𝑟𝑑𝑎𝑦 ∗
𝑃𝑟𝑖𝑐𝑒 𝑌𝑒𝑠𝑡𝑒𝑟𝑑𝑎𝑦
𝑃𝑟𝑖𝑐𝑒 𝑇𝑜𝑑𝑎𝑦 = 𝑃𝑟𝑖𝑐𝑒 𝑇𝑜𝑑𝑎𝑦
Asset Pricing with Monte Carlo
1
𝜇 − 𝜎2 𝜎 ∗ 𝑍(𝑅𝑎𝑛𝑑 0; 1 )
2
1
𝜇−2𝜎2 +𝜎∗𝑍(𝑅𝑎𝑛𝑑 0;1 )
𝑃𝑟𝑖𝑐𝑒 𝑇𝑜𝑑𝑎𝑦 = 𝑃𝑟𝑖𝑐𝑒 𝑌𝑒𝑠𝑡𝑒𝑟𝑑𝑎𝑦 ∗ 𝑒
Derivative Instruments
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.
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.
Forward / Future contracts
Contract
Today A B
Side A Side B
Money
t=T A B
Asset
Side A Side B
Forward / Future contracts
Payoff
K St
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
Option contracts
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
t=T A B
Asset
Side A Side B
Option contracts
Scenario 1: Exercise
K
t=T A B
S
t
Side A Side B
Don’t do
t=T A anything B
Side A Side B
Option contracts
Payoff
K St
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.
Option contracts
Payoff
K
St
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.
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 Side B
Asset 1
t=T A B
Asset 2
Side A Side B
Payoff
St
The Black Scholes formula is one of the most widely used tools for derivatives pricing. It can
be written in the following way:
𝐶(𝑆, 𝑡) = 𝑁 𝑑1 S − N 𝑑2 𝐾𝑒 −𝑟(𝑇−𝑡)
1 𝑆 𝑠2
𝑑1 = [ln + 𝑟+ T−t ]
𝑠 (𝑇 − 𝑡) 𝐾 2
𝑑2 = 𝑑1 − 𝑠 𝑇 − 𝑡
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
r Risk-free rate
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:
𝐶(𝑆, 𝑡) = 𝑁 𝑑1 S − N 𝑑2 𝐾𝑒 −𝑟(𝑇−𝑡)
1 𝑆 𝑠2
𝑑1 = [ln + 𝑟+ T−t ]
𝑠 (𝑇 − 𝑡) 𝐾 2
𝑑2 = 𝑑1 − 𝑠 𝑇 − 𝑡
N Normal distribution