#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#**************************************************************************
#*   Copyright (C) 2017 by S. MANKOWSKI / G. DE BURE support@mankowski.fr
#*   Redistribution and use in source and binary forms, with or without
#*   modification, are permitted provided that the following conditions
#*   are met:
#*   
#*   1. Redistributions of source code must retain the above copyright
#*      notice, this list of conditions and the following disclaimer.
#*   2. Redistributions in binary form must reproduce the above copyright
#*      notice, this list of conditions and the following disclaimer in the
#*      documentation and/or other materials provided with the distribution.
#*   
#*   THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
#*   IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
#*   OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
#*   IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
#*   INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
#*   NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
#*   DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
#*   THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
#*   (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
#*   THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#**************************************************************************

"""
Created on Thu May 18 22:58:12 2017
@author: c0redumb
"""

# To make print working for Python2/3
from __future__ import print_function

# Use six to import urllib so it is working for Python2/3
from six.moves import urllib
# If you don't want to use six, please comment out the line above
# and use the line below instead (for Python3 only).
#import urllib.request, urllib.parse, urllib.error

import time
import sys

'''
Starting on May 2017, Yahoo financial has terminated its service on
the well used EOD data download without warning. This is confirmed
by Yahoo employee in forum posts.
Yahoo financial EOD data, however, still works on Yahoo financial pages.
These download links uses a "crumb" for authentication with a cookie "B".
This code is provided to obtain such matching cookie and crumb.
'''

# Build the cookie handler
cookier = urllib.request.HTTPCookieProcessor()
opener = urllib.request.build_opener(cookier)
urllib.request.install_opener(opener)

# Cookie and corresponding crumb
_cookie = None
_crumb = None

def _get_cookie_crumb(ticker):
	'''
	This function perform a query and extract the matching cookie and crumb.
	'''
	# Perform a Yahoo financial lookup
	url = 'https://finance.yahoo.com/quote/' + ticker
	f = urllib.request.urlopen(url)
	alines = f.read().decode('utf-8')

	# Extract the crumb from the response
	global _crumb
	cs = alines.find('CrumbStore')
	cr = alines.find('crumb', cs + 10)
	cl = alines.find(':', cr + 5)
	q1 = alines.find('"', cl + 1)
	q2 = alines.find('"', q1 + 1)
	crumb = alines[q1 + 1:q2]
	_crumb = crumb

	# Extract the cookie from cookiejar
	global cookier, _cookie
	for c in cookier.cookiejar:
		if c.domain != '.yahoo.com':
			continue
		if c.name != 'B':
			continue
		_cookie = c.value

def load_yahoo_quote(ticker, begindate, enddate, interval):
	'''
	This function load the corresponding history from Yahoo.
	'''
	# Check to make sure that the cookie and crumb has been loaded
	global _cookie, _crumb
	if _cookie == None or _crumb == None:
		_get_cookie_crumb(ticker)
		
	begindate = begindate.replace('-', '')
	enddate = enddate.replace('-', '')

	# Prepare the parameters and the URL
	tb = int(time.mktime((int(begindate[0:4]), int(begindate[4:6]), int(begindate[6:8]), 0, 0, 0, 0, 0, 0)))
	te = int(time.mktime((int(enddate[0:4]), int(enddate[4:6]), int(enddate[6:8]), 0, 0, 0, 0, 0, 0)))
	if te == tb:
		tb = tb -1 

	param = dict()
	param['period1'] = tb
	param['period2'] = te
	param['interval'] = interval
	param['events'] = 'history'
	param['crumb'] = _crumb
	params = urllib.parse.urlencode(param)
	url = 'https://query1.finance.yahoo.com/v7/finance/download/{}?{}'.format(ticker, params)

	# Perform the query
	# There is no need to enter the cookie here, as it is automatically handled by opener
	try:
		f = urllib.request.urlopen(url)
		alines = f.read().decode('utf-8')
		return sorted(alines.split('\n'), reverse=True)
	except IOError:
		return ["Date,Open,High,Low,Close,Adj Close,Volume"]


for l in load_yahoo_quote(sys.argv[1], sys.argv[2], sys.argv[3], sys.argv[4]):
	print(l)
