Python for Finance: Analyze Big Financial Data

(Elle) #1
Figure 11-11. Stock prices over time

Mean-variance refers to the mean and variance of the (log) returns of the different


securities, which are calculated as follows:


In  [ 37 ]: rets    =   np.log(data /   data.shift( 1 ))

Over the period of the time series data, we see significant differences in the annualized


performance. We use a factor of 252 trading days to annualize the daily returns:


In  [ 38 ]: rets.mean() *    252
Out[38]: AAPL 0.266036
MSFT 0.114476
YHOO 0.196165
DB -0.125170
GLD 0.016054
dtype: float64

The covariance matrix for the assets to be invested in is the central piece of the whole


portfolio selection process. pandas has a built-in method to generate the covariance


matrix:


In  [ 39 ]: rets.cov()  *    252
Out[39]: AAPL MSFT YHOO DB GLD
AAPL 0.072813 0.020426 0.023254 0.041044 0.005234
MSFT 0.020426 0.049384 0.024247 0.046100 0.002105
YHOO 0.023254 0.024247 0.093349 0.051528 -0.000864
DB 0.041044 0.046100 0.051528 0.177477 0.008775
GLD 0.005234 0.002105 -0.000864 0.008775 0.032406

The Basic Theory


“In what follows, we assume that an investor is not allowed to set up short positions in a


security. Only long positions are allowed, which means that 100% of the investor’s wealth


has to be divided among the available assets in such a way that all positions are long


(positive) and that the positions add up to 100%. Given the five securities, you could for


example invest equal amounts into every security (i.e., 20% of your wealth in each). The


following code generates five random numbers between 0 and 1 and then normalizes the


values such that the sum of all values equals 1:


In  [ 40 ]: weights =   np.random.random(noa)
weights /= np.sum(weights)
In [ 41 ]: weights
Out[41]: array([ 0.0346395 , 0.02726489, 0.2868883 , 0.10396806, 0.54723926])
Free download pdf