Archive for the ‘maths’ 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:
MATH: Latex Cheatsheet
Editors for Latex documents:
The cheatsheet
 General Purpose template
\documentclass[12pt]{article} \usepackage{amsmath,amssymb,amsfonts} \def\E{\mathbb{E}} \def\bS{\mathbb{S}} \def\R{\mathbb{R}} \pagestyle{plain} \begin{document} \end{document}
 My favorite template for notes (with 2 columns)
\documentclass[8pt,twocolumn]{extarticle} \usepackage[top=0.25in,bottom=.5in,left=0.3in,right=0.3in]{geometry} \usepackage{amsmath, amssymb, amsthm} \usepackage{framed} \usepackage{color,soul} \usepackage{verbatim} \usepackage{multirow} \usepackage{picture} \usepackage{tikz} \usetikzlibrary{shapes,arrows,snakes,backgrounds} \usepackage{bbm} % for indicator \usepackage{listings} \lstset{language=Matlab,breaklines=true} \setlength{\columnseprule}{.2pt} % will put a line between columns \setlength{\parindent}{0in} %\setlength{\parskip}{3mm} \newtheorem*{thm}{Theorem} \newtheorem*{cor}{Corollary} \newcommand{\bm}[1]{\boldsymbol{#1}} \newcommand{\Var}{\text{Var}} \newcommand{\Cov}{\text{Cov}} \newcommand{\E}{\mathbb{E}} \usepackage{units, datetime, fancyhdr, lastpage} \pagestyle{fancy} \fancyhf{} \cfoot{\thepage\ of \pageref{LastPage}} \rfoot{\mmddyyyydate\today\ \currenttime} \begin{document} \end{document}
 A Template for Beamer Slides (Reference: Beamer User Guide at CTAN)
\documentclass[10pt]{beamer} \title{TODO: My Slides} \subtitle{TODO: Subtitle for slides} \author[T. Author]{TODO Author} \date{January 1, 2012} % TODO \begin{document} % titlepage % \begin{frame}[plain] \titlepage \end{frame} % slide % \begin{frame} \frametitle{TODO: Title of Slide} \begin{itemize} \item Itemized list entry \end{itemize} % Useful stuff % \pause % \medskip % \bigskip % \includegraphics[height=25mm]{something.pdf} % \begin{columns} % \begin{column}{0.3\textwidth} % bla bla % \end{column} % \begin{column}{0.3\textwidth} % bla bla % \end{column} % \end{columns} % \begin{displaybox}{60mm} \end{displaybox} % \[ \] \end{frame} \end{document}
 Options for drawing in Latex: pstricks, pgf/tikz, xypic
 pgf/tikz — simpler than pstricks. Here is an example
\documentclass{article} \usepackage{tikz} \begin{document} \begin{tikzpicture}[scale=1.5] % Draw axes \draw [<>,thick] (0,2) node (yaxis) [above] {$y$}  (3,0) node (xaxis) [right] {$x$}; % Draw two intersecting lines \draw (0,0) coordinate (a_1)  (2,1.8) coordinate (a_2); \draw (0,1.5) coordinate (b_1)  (2.5,0) coordinate (b_2); % Calculate the intersection of the lines a_1  a_2 and b_1  b_2 % and store the coordinate in c. \coordinate (c) at (intersection of a_1a_2 and b_1b_2); % Draw lines indicating intersection with y and x axis. Here we use % the perpendicular coordinate system \draw[dashed] (yaxis  c) node[left] {$y'$}  (xaxis  c) node[below] {$x'$}; % Draw a dot to indicate intersection point \fill[red] (c) circle (2pt); \end{tikzpicture} \end{document}
Reference: Manual, Examples, Resources, Minimal
Some useful code:
 Scaling a picture
\begin{tikzpicture}[scale=0.5] \end{tikzpicture} \begin{tikzpicture}[xscale=2.5,yscale=0.5] \end{tikzpicture}
 Draw a line from (x0,y0) to (x1,y1):
\draw (x0,y0)  (x1,y1);
A path of straight lines
\draw (x0,y0)  (x1,y1)  (x2,y2)  (x3,y3);
Arrows
\draw[>] (x0,y0)  (x1,y1); \draw[<] (x0,y0)  (x1,y1); \draw[>] (x0,y0)  (x1,y1);
Thicker lines: ultra thin, very thin, thin, semithick, thick, very think, ultra thick
\draw[thick] (x0,y0)  (x1,y1); \draw[line width=3] (x0,y0)  (x1,y1); % 3pt wide
Dashes and dots: dashed, dotted, thinly dotted
Colors: red, green, blue, cyan, magenta, yellow, black, gray, darkgray, lightgray, brown, lime, olive, orange, pink, purple, teal, violet, white
 Draw a line from (x0,y0) to point with polar coordinates (a1:r1) a1 = angle, r1 = radius
\draw[color=green] (x0,y0)  (a1:r1);
 Draw an arc with center at (x0,y0) starting at startAngle=a1, ending at angle, e1 and radius=r1
\draw (x0,y0) arc [radius=r1, start angle=a1, end angle=e1]; \draw (x0,y0) arc (a1:e1:r1);
 Draw a green rectangle between coordinates (x0,y0) to (x1,y1):
\draw[color=green] (x0,y0) rectangle (x1,y1);
 Draw a filled ellipse with center at (x0,y0) and (r1, r2):
\draw[fill=color!shade] (x0,y0) ellipse (r1 and r2);
Draw a dotted circle with center at (x0,y0) and radius r0:
\draw[style=dashed] (x0,y0) circle (r1);
 Draw a bezier curve
\draw (x0,y0) .. controls (px1,py1) and (px2,py2) .. (x1,y1);
 Draw a grid
\draw[help lines] (0,0) grid (3,2);
 Draw (x,y) axis
\draw[<>] (0,10.1)  (0,0)  (10.1,0); \draw[snake=ticks,segment length=1cm] (0,10)  (0,0)  (10,0); \foreach \x/\xtext in {1/0.1,0/0.0,1/0.1,2/0.2,3/0.3} \draw[shift={(\x,0)},thick,color=gray!40,dashed] (0,2.5)  (0,0) node[color=black,below] {\scriptsize $\xtext$}; \foreach \y/\ytext in {1/0.1,0/0.0,1/0.1,2/0.2,3/0.3} \draw[shift={(0,\y)},thick,color=gray!40,dashed] (2.5,0)  (0,0) node[color=black,left] {\scriptsize $\ytext$}; \foreach \x in {0,1,2,3,4,5} \draw (\x,3)  (\x,3); \draw[help lines] (0,0) grid (8,5); \draw[>] (0,0)  (8,0) node[right] {x}; \draw[>] (0,0)  (0,5) node[above] {y}; \foreach \x in {0,...,7} \draw (\x,1pt)  (\x,3pt) node[anchor=north] {\x}; \foreach \y in {0,...,4} \draw (1pt,\y)  (3pt,\y) node[anchor=east] {\y};
 Aliases
\draw = \path[draw] \fill = \path[fill] \clip = \path[clip] \filldraw = \path[fill,draw] \shade = \path[shade]
 Draw a curve from (x0,y) to (x1,y1) leaves at angle a1, arrives at an angle e1
\draw (x0,y0) to [out=a1,in=e1] (x1,y1); \draw (x0,y0) to [out=a1,in=e1] (x1,y1) to [out=a2,in=e2] (x2,y2) to [out=a3,in=e3] (x3,y3) ;
Plot from (x0:x1) curve f(x)=x^3+2x
\draw [domain=x0:x1] plot(\x, {\x*\x*\x+2*\x}); \draw [domain=x0:x1] plot(\x, {sin(\x r) * ln(\x+1)/2 + exp(2*pi)});
other functions: factorial, sqrt, pow, exp, ln, log10, log2, abs, mod, round, floor, sin(degrees), sin(radian r), cos, tan min, max, rnd, e, pi
 A closed figure
\path[draw] (x0,y0)  (x1,y1)  (x2,y2)  cycle; \path[draw] (x0,y0)  (x1,y1)  (x2,y2)  (x0,y);
 Text at some position
\node at (x0,y0) {text}; \node (label1) at (x0,y0) {text}; \node (label2) at (x1,y1) {text}; \draw (label1)  (label2);
 Scaling a picture
 xypic — simplest way to draw
\documentclass{article} \usepackage[all]{xy} \begin{document} \xymatrix{ A \ar@<1ex>[dr]^a_{.} \\ & B \ar@<1ex>[ul]^b \ar@<1ex>[r]^c & C \ar@<1ex>[l]^d_{.} } \end{document}
 pstricks — run the latex file through ps2pdf. Example:
$> cat f1.tex \documentclass{article} \usepackage{pstricks} \begin{document} \begin{figure} \psset{gridcolor=green,subgridcolor=yellow} \begin{pspicture}(4,5) \psgrid \psframe[linecolor=blue, fillcolor=red, fillstyle=solid](0.7,2)(3.3,3) \rput(2,2.5){First Example} \end{pspicture} \end{figure} \end{document} $> ps2pdf f1.tex
 Picture environment
\usepackage{picture} % begin{picture}(xDim,yDim)(leftBottomCoordX,leftBottomCoordY) \begin{picture}(110,110)(10,10) \put(0,0){\vector(1,0){100}} % xaxis \put(0,0){\vector(0,1){100}} % yaxis \multiput(10,2)(10,0){9}{\line(0,1){2}} % markers (x) \multiput(2,10)(0,10){9}{\line(1,0){2}} % markers (y) \put(0,5){\makebox(0,0){0}} % origin \put(100,5){\makebox(0,0){x}} % label xaxis \put(10,100){\makebox(0,0){y}} % label yaxis \qbezier(55,0)(0,0)(1,80) % draw a curve between (55,0) and (1,80) \multiput(0,30)(2,0){25}{\line(1,0){1}} % draw a horizontal dotted line \multiput(50,0)(2,0){15}{\line(0,1){1}} % draw a vertical dotted line \end{picture}
 Flowcharting
\documentclass{article} \usepackage[latin1]{inputenc} \usepackage{tikz} \usetikzlibrary{shapes,arrows} \begin{document} \pagestyle{empty} % Define block styles \tikzstyle{decision} = [diamond, draw, fill=blue!20, text width=4.5em, text badly centered, node distance=2.5cm, inner sep=0pt] \tikzstyle{block} = [rectangle, draw, fill=blue!20, text width=5em, text centered, rounded corners, minimum height=4em] \tikzstyle{line} = [draw, very thick, color=black!50, latex'] \tikzstyle{cloud} = [draw, ellipse,fill=red!20, node distance=2.5cm, minimum height=2em] \tikzstyle{decision answer}=[near start,color=black] \begin{tikzpicture}[scale=2, node distance = 2cm, auto] % Place nodes \node [block] (init) {initialize model}; \node [cloud, left of=init] (expert) {expert}; \node [cloud, right of=init] (system) {system}; \node [block, below of=init] (identify) {identify candidate models}; \node [block, below of=identify] (evaluate) {evaluate candidate models}; \node [block, left of=evaluate, node distance=2.5cm] (update) {update model}; \node [decision, below of=evaluate] (decide) {is best candidate better?}; \node [block, below of=decide, node distance=2.5cm] (stop) {stop}; % Draw edges \path [line] (init)  (identify); \path [line] (identify)  (evaluate); \path [line] (evaluate)  (decide); \path [line] (decide)  node [decision answer] {yes} (update); \path [line] (update)  (identify); \path [line] (decide)  node [decision answer] {no}(stop); \path [line,dashed] (expert)  (init); \path [line,dashed] (system)  (init); \path [line,dashed] (system)  (evaluate); \end{tikzpicture} \end{document}
 pgf/tikz — simpler than pstricks. Here is an example
 Adding pdf pages to your document
As an image
\usepackage{graphicx} \begin{figure*}[h] \centering \includegraphics[width=1.0\textwidth]{pg1.pdf} \caption{Test} \end{figure*}
Selective pages
\usepackage{pdfpages} \includepdf[pages={1}]{pg1.pdf} % page 1 \includepdf[pages={3last}]{pg1.pdf} % all pages \includepdf[pages={3,{},5,7}]{pg1.pdf} % page 3, empty page, 5, 7 \includepdf[pages=]{pg1.pdf} % all pages
 Def equal:
A \stackrel{\rm def}{=} B
 Binomial coefficient
\binom{n}{r} or \newcommand{\bc}[2]{\genfrac{(}{)}{0pt}{}{#1}{#2}} ... \bc{n}{r} # equivalently (gives a warning) {n \choose r} \dbinom{n}{r}
 Two columns:
 Use: \documentclass[11pt,twocolumn]{article}
Distance between columns: \setlength{\columnsep}{distance}
A line at the bottom of column: \setlength{\columnseprule}{thickness}  Use:
\usepackage{multicol} \begin{multicols}{2} ... \end{multicols}
 Use: \documentclass[11pt,twocolumn]{article}
 Adjust margins
\usepackage[top=0.5in,bottom=0.5in,left=0.5in,right=0.5in]{geometry}
 Putting today’s date in your document. Just use \today.
To get current date+time, use datetime package. \currenttime.\usepackage{datetime} ... \begin{document} Printed: \today\ at \currenttime Printed: {\tiny \ddmmyyyydate\today\ at \currenttime}
 Indicator function:
\usepackage{mathbbm} ... \mathbbm{1}_A
 Need page numbers in the style “1 of 10”
\usepackage{fancyhdr} \pagestyle{fancy} \lfoot{Left Side of footer} \cfoot{\thepage\ of \pageref{LastPage}} \rfoot{Right Side of footer} ... \begin{document} ...
 Underline: \underline{}, Underbrace: \underbrace{}
 Overline: \overline{}, Overbrace: \overbrace{}
 Emphasize: \emph{}
 Strike out: \sout{}, needs package ulem. say \usepackage[normalem]{ulem}
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