I'm getting the error:- goog_table not defined in this code. Can anyone solve this?
# region imports
from AlgorithmImports import *
import pandas as pd
from numpy import sqrt,mean,log,diff
# endregion
#goog_table = quandl.get('WIKI/GOOG')
# use the daily data of Google(NASDAQ: GOOG) from 01/2016 to 08/2016
close = goog_table['2016-01':'2016-08']['Adj. Close']
r = diff(log(close))
r_mean = mean(r)
diff_square = [(r[i]-r_mean)**2 for i in range(0,len(r))]
std = sqrt(sum(diff_square)*(1.0/(len(r)-1)))
vol = std*sqrt(252)
class WellDressedTanCoyote(QCAlgorithm):
def bsm_price(option_type, sigma, s, k, r, T, q):
# calculate the bsm price of European call and put options
sigma = float(sigma)
d1 = (np.log(s / k) + (r - q + sigma ** 2 * 0.5) * T) / (sigma * np.sqrt(T))
d2 = d1 - sigma * np.sqrt(T)
if option_type == 'c':
price = np.exp(-r*T) * (s * np.exp((r - q)*T) * stats.norm.cdf(d1) - k * stats.norm.cdf(d2))
return price
elif option_type == 'p':
price = np.exp(-r*T) * (k * stats.norm.cdf(-d2) - s * np.exp((r - q)*T) * stats.norm.cdf(-d1))
return price
else:
print('No such option type %s') %option_type
def implied_vol(option_type, option_price, s, k, r, T, q):
# apply bisection method to get the implied volatility by solving the BSM function
precision = 0.00001
upper_vol = 500.0
max_vol = 500.0
min_vol = 0.0001
lower_vol = 0.0001
iteration = 0
while 1:
iteration +=1
mid_vol = (upper_vol + lower_vol)/2.0
price = bsm_price(option_type, mid_vol, s, k, r, T, q)
if option_type == 'c':
lower_price = bsm_price(option_type, lower_vol, s, k, r, T, q)
if (lower_price - option_price) * (price - option_price) > 0:
lower_vol = mid_vol
else:
upper_vol = mid_vol
if abs(price - option_price) < precision: break
if mid_vol > max_vol - 5 :
mid_vol = 0.000001
break
elif option_type == 'p':
upper_price = bsm_price(option_type, upper_vol, s, k, r, T, q)
if (upper_price - option_price) * (price - option_price) > 0:
upper_vol = mid_vol
else:
lower_vol = mid_vol
if abs(price - option_price) < precision: break
if iteration > 50: break
return mid_vol
implied_vol('c', 0.3, 3, 3, 0.032, 30.0/365, 0.01)
# download option data for all expiry months from Yahoo Finance
# provide a formatted DataFrame with a hierarchical index
opt = Options('spy', 'yahoo')
opt.expiry_dates # list all the available expiration dates
def IV_plot(opt,option_type,expiry_index):
expiry = opt.expiry_dates[expiry_index]
if option_type == 'c':
data = opt.get_call_data(expiry=expiry)
elif option_type == 'p':
data = opt.get_put_data(expiry=expiry)
r = 0.01 # risk free rate
d = 0.01 # continuous devidend yield
s = opt.underlying_price # data_call['Underlying_Price'] undelying price
expiry = data.index.get_level_values('Expiry')[0] # get the expiry
current_date = opt.quote_time # current_date = datetime.datetime.now() # get the current date
time_to_expire = float((expiry - current_date).days)/365 # compute time to expiration
premium = (data['Ask'] + data['Bid'])/2 # option premium
strike = list(data.index.get_level_values('Strike')) # get the strike price
IV = []
for i in range(len(data)):
IV.append(implied_vol(option_type, premium.values[i], s, strike[i], r, time_to_expire, d))
plt.figure(figsize=(16, 7))
a = plt.scatter(strike,IV, c='r', label="IV by solving BSM")
b = plt.scatter(strike,data['IV'],c = 'b', label="IV from Yahoo Finance")
plt.grid()
plt.xlabel('strike')
if option_type == 'c':
plt.ylabel('Implied Volatility for call option')
plt.legend((a,b), ("IV(call) by solving BSM", "IV(call) from Yahoo Finance"))
elif option_type == 'p':
plt.ylabel('Implied Volatility for put options')
plt.legend((a,b), ("IV(put) by solving BSM", "IV(put) from Yahoo Finance"))
return strike,IV
k_call, IV_call = IV_plot(opt,'c',23)
k_put, IV_put = IV_plot(opt,'p',23)
plt.figure(figsize=(16, 7))
e = plt.scatter(k_call,IV_call, c ='red', label="IV(call options)")
f = plt.scatter(k_put,IV_put, c = 'black', label="IV(put options)")
plt.xlabel('strike')
plt.ylabel('Implied Volatility')
plt.legend((e,f), ("IV (call options)", "IV (put options)"))
opt = Options('spy', 'yahoo')
r = 0.01 # risk free rate
d = 0.01 # continuous devidend yield
expiry_dates = [i for i in opt.expiry_dates if i > opt.quote_time.date()]
current_date = opt.quote_time.date() ## get the current date
s = opt.underlying_price # undelying price
num_expiry = len(expiry_dates)
IV = [] # (num_expiry * 3)-dimension list with each row being [time_to_expire, strike, implied_vol]
for expiry_index in range(num_expiry):
data = opt.get_put_data(expiry=expiry_dates[expiry_index])
expiry = expiry_dates[expiry_index] # get the expiry
time_to_expire = float((expiry - current_date).days)/365 # compute time to expiration
premium = (data['Ask'] + data['Bid'])/2.0 # option premium
strike = data.index.get_level_values('Strike') # get the strike price
num_strike = len(data)
for j in range(num_strike):
IV.append([time_to_expire, strike[j], implied_vol('c', premium.values[j], s, strike[j], r, time_to_expire, d)])
x= [IV[i][0] for i in range(len(IV))]
y= [IV[i][1] for i in range(len(IV))]
z= [IV[i][2] for i in range(len(IV))]
fig = plt.figure(figsize=(20,11))
ax = fig.add_subplot(111, projection='3d')
ax.view_init(20,10)
ax.scatter(x,y,z)
def OnData(self, data: Slice):
pass
Vladimir
Manav Trivedi
Google table is Quandl data.
Quandl is now NasdaqDataLink.
You can get that data as described here.
But we can calculate Annualized STD of log returns without Google table using QC native indicators.
If you are satisfied with my answer, please accept it and don't remove it later.
Vladimir
Manav Trivedi
Did you have a chance to try what I recommended on your algorithm problem?
Are you satisfied with my answer to your question?
Manav Trivedi
The material on this website is provided for informational purposes only and does not constitute an offer to sell, a solicitation to buy, or a recommendation or endorsement for any security or strategy, nor does it constitute an offer to provide investment advisory services by QuantConnect. In addition, the material offers no opinion with respect to the suitability of any security or specific investment. QuantConnect makes no guarantees as to the accuracy or completeness of the views expressed in the website. The views are subject to change, and may have become unreliable for various reasons, including changes in market conditions or economic circumstances. All investments involve risk, including loss of principal. You should consult with an investment professional before making any investment decisions.
To unlock posting to the community forums please complete at least 30% of Boot Camp.
You can continue your Boot Camp training progress from the terminal. We hope to see you in the community soon!