Ejemplo n.º 1
0
def range_volatility(ticker, components): 
	# Parse and check: find components matching dates, ensure start and end are present, ensure dates are valid
	today, dates = current_date(), []
	for each in components: 
		if PATTERNS['valid_date'].match(each):
			dates.append(each)
	if len(dates)!=2:
		return {"message": Response.vol_required_dates(ticker)}
	for each in dates: 
		if each > today: 
			return {"message": Response.invalid_date(each)}
		try: 
			date = datetime.datetime.strptime(each, '%Y-%m-%d')
		except ValueError: 
			return {"message": Response.invalid_date(each)}

	# Volatility Calculation
	dates = sorted(dates)
	start, end = dates[0], dates[1]
	try:
		quotes = data.DataReader(ticker, 'google')['Close'].loc[start:end]
		if len(quotes) < 10: 
			return {"message": Response.vol_range_size(ticker)}
	except Exception:
		return {"message": Response.data_notfound(ticker)}
	logreturns = np.log(quotes / quotes.shift(1))
	vol = round(np.sqrt(252*logreturns.var()), 5)
	return {"message" : Response.range_vol(ticker, start, end, vol)}