0

enter image description here

from matplotlib.finance import quotes_historical_yahoo_ochl as getData
import scipy as sp 
ticker='IBM' 
begdate=(2013,9,1) 
enddate=(2013,11,11) 
data= getData(ticker, begdate, enddate,asobject=True, adjusted=True) 
p=data.aclose 
d=sp.diff(p)
cov_=sp.cov(d[:-1],d[1:]) 
if cov_[0,1]<0: 
    print("Roll spread for ", ticker, 'is', round(2*sp.sqrt(-cov_[0,1]),3)) 
else: 
    print("Cov is positive for ",ticker, 'positive', round(cov_[0,1],3)) 

My effort is to calculate the above code in Python but since matplotlib.finance has been deprecated I tried another road using pandas_datareader.data.

Doing so I made this one :

import pandas_datareader.data as web
end = '2013-11-11'
start = '2013-09-01'
get_px = lambda x: web.DataReader(x, 'yahoo', start=start, end=end)['Adj Close']

symbols = ['IBM']
data = pd.DataFrame({sym:get_px(sym) for sym in symbols})
data = data.rename({'IBM': 'Adj Close'}, axis=1)
p1 = data.dropna()
p = np.asarray(p1);p
d = np.diff(p);d
cov_= np.cov(d[:-1],d[1:])
cov_

I receive an error

/opt/anaconda3/lib/python3.8/site-packages/numpy/lib/function_base.py:380: RuntimeWarning: Mean of empty slice.
  avg = a.mean(axis)
RuntimeWarning: Mean of empty slice.
if cov_[0,1]<0:
    print("Roll spread for ", symbols, 'is', round(2*sp.sqrt(-cov_[0,1]),3))
else:
    print("Cov is positive for ",symbols, 'positive', round(cov_[0,1],3)

What is my mistake ? I don’t know in the first code what type of object the data object is.And probably there is where the problem starts.

Updated

The line code

d = np.diff(p);d 

is empty.The result is :

 array([], shape=(50, 0), dtype=float64) 

The needed result is the 1.136

Homer Jay Simpson
  • 1,043
  • 6
  • 19

1 Answers1

1

Using your code, the shape of p is wrong:

p.shape
Out[8]: (50, 1)

When you apply np.diff() onto this, it applies the difference on every entry, instead of across the vector as you intended, hence the error.

You can do something like this:

p = p1['Adj Close'].ravel()
d = np.diff(p)
cov_= np.cov(d[:-1],d[1:])
cov_

array([[ 3.12100146, -0.15854027],
       [-0.15854027,  3.20098506]])

Not very sure how you define the roll, I think:

np.sqrt(abs(cov_))
 
array([[1.76663563, 0.39817116],
       [0.39817116, 1.78912969]])

What you need to get 1.766 is:

np.sqrt(abs(cov_))[0,0]
StupidWolf
  • 45,075
  • 17
  • 40
  • 72