Archive for the ‘quantfinance’ Category
TECH: Get a realtime quote from Yahoo Finance
require 'openuri' require 'nokogiri' def getQuote(symbol) q = "" doc = Nokogiri::HTML(open("http://finance.yahoo.com/q?s=#{symbol}&ql=1")) doc.xpath('//*[@class="real_time"]').each do node y = node.xpath("span").first node.xpath("span").each { x q += x.text } end return q end ARGV.each { s print "#{s} = #{getQuote(s)}\n"; }
Another place to get realtime quote: http://batstrading.com/json/bzx/book/WFC
QUANT: Important Stochastic Processes
Geometric Brownian Motion
 It’s SDE is:
or also as
 Solution:
OrnsteinUhlenbeck Process (aka Vasicek Model)
 It is a MeanReverting Process, although random, shows a pronounced tendency toward an equilibrium value.
 It’s SDE is:
– long term mean/equilibrium value/mean value
– volatility to model random shocks
– rate by which the shocks dissipate and variable returns towards equilibrium mean  Solution for this SDE is:
 Useful for modeling interest rates, currency exchange rates, and commodity prices
Bessel Process
 Stochastic Differential Equation:
QUANT: More on Portfolio Theory
 Utility Theory
 Utility
 more is preferred to less (nonsatiation)
 diminishing marginal utility
 Utility Function, U(w). Increasing (U'(w) > 0) => nonsatiation, Concave down (U”(w) < 0) = diminishing marginal utility
 Utility Maximization
 Constrained Optimization
 Certainty Equivalent – amount in riskfree investment that will give the same utility value as expected utility value of investment in risky investments.
 Risk Premium =
Risk Premium rate is or
A Risk Averse investor would expect positive riskpremium
A Risk Seeking investor would expect negative riskpremium
 Risk Aversion
 Absolute Risk Aversion,
 Relative Risk Aversion,
 Utility
 Maximum Variance Portfolio Analysis – Goal
 Maximize return for a given amount of risk
 Given an expected return minimize the amount of risk
 Efficient Frontier
 Combining the assets:
Suppose we have a portfolio of 2 assets (X, Y) with weights (a, 1a), then expected return and variance of the portfolio will be:
 Expected Return:
 Variance:
If we plot Volatility vs Expected Return (obtained from the above formulas) for different possible values of ‘a’, we get the hyperbolic curve that gives us the Efficient Frontier.
R = [.04 .07]; Vol = [.2 .3]; rho=0.5; efficientFrontier(R, Vol, rho) function efficientFrontier(assetReturn, assetVolatility, rho) asset1Weight = 10:0.01:10; asset2Weight = 1asset1Weight; Y=assetReturn(1).*asset1Weight+assetReturn(2).*asset2Weight; X=sqrt((assetVolatility(1)*asset1Weight).^2+(assetVolatility(2)*asset2Weight).^2+2*rho*assetVolatility(1)*assetVolatility(2)*asset1Weight*diag(asset2Weight)); plot(X,Y); xlabel('Volatility'); ylabel('Returns'); end
nAssets Portfolio with
 Weights ,
 Expected Return:
 Variance:
 How do we find Minimum Variance Portfolio? For what weight ‘w’, will the portfolio have minimum variance? Hint: At the minima, d(Var[r])/dw = 0.
,
 Global Minimum Variance Portfolio (the general case – portfolio of nassets).
Given: Covariance Matrix, S, the portfolio with minimum variance is given by (weight vector of the portfolio):
 , where
 Mean Variance Efficient Portfolio/Tangency Portfolio/Optimal Portfolio
 Given Excess Return vector (in excess of risk free return rate)
 Given Covariance Matrix, S
 Efficient Portfolio weight, , where
 Global Minimum Variance Portfolio will be identical to the Tangency Portfolio when all the Assets Returns (hence Excess Returns too) are exactly the same
 Combining the assets:
 Sharpe Ratio: “excess return” per unit volatility of an asset or a portfolio, p
 Sharpe Ratio =
Note: On a “Volatility vs Returns” plot/graph, all portfolios on a straight line have the same Sharpe Ratio. Like all portfolios on the tangent line have the same Sharpe Ratio.
Note: Tangency Portfolio on the Efficient Frontier has the highest possible Sharpe Ratio
Note: Capital Market Line – The Tangency Portfolio line is also called Capital Market Line
 Decomposition of a Security’s Return:
– a constant term for the security, s
– beta term – also a constant for the security, s.
– market’s return. Note: is the Market Specific component of the Security’s return.
– residual return/specific return/idiosyncratic return/unique return of the security, s. It is not a constant, it is a Random Variable and has mean 0.Assumptions:
 Mean of Residual Return is 0,
 Residual Return for any security is independent of the market return
 Residual Return for any security is independent of Residual Return of any other security
Note:
 Expected Return of Security s,
 Variance (of Return) of Security s, (= market part + security specific part)
 Covariance of Securities s, t,
Note: Covariance of 2 securities only depends on the Market Risk and their Betas. How 2 securities move together can be described by their common response to market moves.
 Expected Beta of any security is 1,
 Portfolio Return:
Portfolio Expected Return: , where  Variance of Return of a Portfolio,
Note: In a large diversified portfolio, the impact of residual risk on the portfolio vanishes. .
 Note: is diversifiable or unsystematic risk, is undiversifiable/systematic risk
 Note: Recall . Which means risk that can not be diversified away is due to the covariances of the securities in the portfolio. Combining that with the result above we note that it is proportional to the market’s risk .
 Market Portfolio, p = M, then
 Security Market Line – line on plot. Yaxis intercept is riskfree return and has . The “market portfolio” has
Equation of a “Security Market Line” is

equivalently:
or (Excess Return of Security) = (Security’s Beta) x (Excess Return of Market)

or (Expected Return of Security) = Weighted Average of (RiskFree Rate, Market Expected Return)
Note: SML shows: “Expected Return” of any Security/Portfolio = linear and increasing function of Systematic Risk (beta)
Note: SML shows: Only Risk that effects the “Expected Return” of Security/Portfolio is Market Risk 
 Jensen’s Alpha: any extra expected return above that predicted by SML
 Treynor Ratio: excess return per unit beta of an asset, s
 Treynor Ratio =
 Beta – signifies systemic risk component of the asset
 Capital Asset Pricing Model
 Regression is equivalent to projection on a line
 Beta Hedging a Portfolio
 Tracking Basket, Tracking Error
 Single Index Model
where
Covariance of 2 assets/stocks
 Multi Factor Model
where
In other words
Covariance Matrix in terms of multifactor model:
where
 Principal Component Analysis
 Regression of X on Y
 Marginal Contribution of an asset on portfolio risk
 Optimal Portfolio when you change currency
QUANT: Portfolio Theory Topics
Topics in Portfolio Theory
 Risk is relative. Finance can not be risk free.
 Markets – bring buyer and seller together. They facilitate trade: provide a mechanism (called “price discovery”) for mutually beneficial exchanges.
 Price Discovery – markets discover price as buyers and sellers BID and OFFER to buy and sell
 BID – tell a price at which you are willing to BUY
 OFFER/ASK – tell a price at which are willing to SELL
 Correct/Market Price – what clears the market, i.e., leaves no excess quantity demanded or supplied
 Spread – difference of BID price and OFFER price in a market. Indication of liquidity. Narrow spread implies easy liquidity
 Liquidity – ability to do a transaction at a price similar to the last traded price. There should be willing Buyers and Sellers at all times.
 Liquidity is correlated with Volume. Higher Volume implies Higher Liquidity and vice versa.
 Market Depth – the volume/quantity that can be Bought or Sold at a given price
 Risk – we know probability distribution of the outcomes, but we do not know the outcome
 Uncertainty – we do not know the outcome and we also do not know the probability distribution
 Decision Criteria to decide under Uncertainty – Way to pick a strategy when there is no knowledge of probabilities of outcomes. Example: Maximax, Maximin, Minimax Regret Criterion
 Measure risk – Variance, Mean/Variance
 Price – exchange rate. Ratio of quantities.
 Return – measure of change in a price
 Given time series of prices:
 Simple Return/Percent Return,
 Gross Return,
 Log Return,
 Simple Return is to Simple Compounding:
 Log Return is to Continuous Compounding:
 Effect of dividend on returns calculation.
 Effect of m:n stock split on returns calculation.
 Stochastic Processes:
 ,
 Average Returns: Given a time series of returns
 Arithmetic Average:
 Geometric Average:
 Statistics:
 Expectation
 Variance
 Standard Deviation
 CoVariance
 Correlation
 Mean (Log) Return:
 Total Holding Period Return:
 Annualized Mean Return:
 num of observations per year
 Annual returns = 1
 Monthly returns = 12
 Weekly returns = 52.177
 Daily returns = 252 (# of trading days in 1 year for volatility calculations), for interest rate related calculations, use calendar days 365
 Volatility (always annualized):
 Historic Annualized Volatility/Standard Deviation
 Zero Mean Assumption Volatility:
 Expected Return Assumption Volatility: .
is the expected/desired return for the period t.
 Rolling window – showing historical volatility over time. Calculate volatility for time t by using returns over the window period before and up to time t, i.e.,
 Weighted windows: weighting function: equal weight, linear weight, exponential weight, truncated exponential weight
 Correlation – related to regression
 Covariance Matrix, S: let Y be T x N matrix of observations of returns (T returns observations for each of N assets), Covariance matrix is a N x N matrix given by:
 Covariance matrix is symmetric. Diagonal elements are variances.
 When the assets are uncorrelated, then the Covariance matrix becomes a diagonal matrix (since all the covariance terms are 0).
Inverse of a diagonal matrix is easy
 Correlation matrix:
Correlation matrix is also symmetric. Diagonal elements are 1.
 Correlation matrix to Covariance matrix conversion
here,
 Covariance matrix to Correlation matrix conversion
 Vector of returns:
 Portfolio – a vector of weights of assets,
 Portfolio Returns – total return of all the assets in a portfolio,
 Portfolio Volatility – total volatility of all the assets in a portfolio,
 Diversification – invest in all assets. Example, put (1/n) in each asset. Portfolio Volatility of a well diversified portfolio is driven by Mean of Covariances only, individual asset volatilities do not matter. Why? To calculate portfolio volatility, we add all the Variance and Covariance terms, there are n Variance terms (along the diagonal) and [(n1) x n] Covariance terms. So Covariances dominate the contribution.
 Covariance between two Portfolios (of the same assets): It is a number (not a matrix),
 A Covariance Matrix must be Positive SemiDefinite (i.e. ). Which means all eigenvalues of S are positive. A condition for that is .
 A valid Correlation Matrix must also be positive semidefinite. A 2 x 2 matrix (for 2 assets) is valid if .
For a 3 x 3 correlation matrix a necessary condition is:
 Simulate Sample price movements:
Stochastic Process: , Discrete Version:
Log S Process: , Discrete Version:  Generating Independent Random Numbers in MATLAB:
% m x n matrix of independent random numbers randn(m,n)
Generating Correlated Random Normal Variables. Want to generate N x n matrix of random variables Y.
These random variables should be correlated normal, and must have covariance matrix equal to S (given)Method 1: Cholesky Decomposition
 Generate Independent Random Variables, U
 Take Cholesky Decomposition of the Covariance Matrix (S), call it C. Then C‘C = S.
 The Correlated Random Variables will then be, Y = U C
U = randn(T,N); C = chol(S); Y = UC;
Ponder on what is the correlation matrix of Y? It is . Remember U is independent standard normal, so it’s mean is 0 and variance is 1, i.e., .
In fact, any matrix B such that can be used to generate the correlated random variables.
Method 2: Spectral Decomposition
 Given an S, take it’s eigenvalues λ and eigenvectors V. Then
 Define Y = UB