#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#***************************************************************************
#* SPDX-FileCopyrightText: 2022 S. MANKOWSKI stephane@mankowski.fr
#* SPDX-FileCopyrightText: 2022 G. DE BURE support@mankowski.fr
#* SPDX-License-Identifier: GPL-3.0-or-later
#***************************************************************************

"""
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
	hdr = { 'User-Agent' : 'Mozilla/5.0 (Windows NT 6.1; Win64; x64)',
		'content-type': 'text/html; charset=utf-8'}
	req = urllib.request.Request(url, headers=hdr)
	f = urllib.request.urlopen(req)
	alines = f.read()
	alines = alines.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)
