#!/usr/bin/python2.7
# -*- coding: utf-8 -*-
#
# GetHistoical.py.
# Prog collects share Close price for each Friday between srart date and current date.
# RKN 17/01/2016 Rev 5
# Unable to  run program on a Friday before markets Close.
# RKN 04/01/2016 Rev 4
# If 25th Dec or 26th Dec or 31st Dec are a Friday then the share price is
# collected for the last available day but saved with the Friday date.
# RKN 07/11/2015 Rev 3
# Requests start date
# RKN 17/10/2015  Rev 2.0
# A file histsharestoget.txt lists what files are to be monitored.
# Stores data in txt file
# Adds share to sharestoget file if not already present.
# DOES NOT UPDATE INDEX
# Use reorder to generate correct index numbers

import ystockquote
import shutil
import datetime
import calendar
from datetime import date


indexpointer = "1"

base = "SharesData/"
#base = "TestSharesData/"

filename = base + "histsharestoget.txt"
tempfile = base + "tempfile.txt"

tempdate = base + "tempdate.txt"



now = str(datetime.datetime.now())
#now = "2016-01-15 14:14"
print "Date today is " + now[0:10]

endyear = now[0:4]
endyear = int(endyear)

endmonth = now[5:7]
endmonth = int(endmonth)

endday = now[8:10]
endday = int(endday)


if date(endyear, endmonth, endday).weekday() == 4:
    if int(now[11:13] + now[14:16]) < 1800:
        print "It is Friday before close of markets.  Todays prices will be collected by GetRegular later tonight"
        revisedenddate = raw_input("Enter Yesterday's date as the End date e.g 2015-06-30.....")
        if revisedenddate == "" :
            quit()    


        endyear = revisedenddate[0:4]
        endyear = int(endyear)

        endmonth = revisedenddate[5:7]
        endmonth = int(endmonth)

        endday = revisedenddate[8:10]
        endday = int(endday)

        #print endyear,endmonth,endday

        print " "


startdate = raw_input("Enter the start date e.g 2015-06-30.....")
if startdate == "" :
    startdate = "2013-01-01"

startyear = int(startdate[0:4])
startmonth = int(startdate[5:7])
startday = int(startdate[8:10])

tempdat = open(tempdate, 'w')

for yearNum in range(startyear, endyear + 1):

    if yearNum == startyear:
        startmonthrange = startmonth
    else:
        startmonthrange = 1

    if yearNum == endyear:
        endmonthrange = endmonth + 1
    else:
        endmonthrange = 13

    for monthNum in range(startmonthrange,endmonthrange):


        if monthNum == 4 or monthNum == 6 or monthNum == 9 or monthNum == 11:
            days = 31
        else:
            days = 32


        if calendar.isleap(yearNum):
            if monthNum == 2:
                days = 30
        else:
            if monthNum ==2:
                days = 29
    

        if yearNum == startyear and monthNum == startmonth:
            startdayrange = startday
        else:
            startdayrange = 1

        
        if yearNum == endyear and monthNum == endmonth:
            enddayrange = endday + 1
        else:
            enddayrange = days   


        for dayNum in range(startdayrange,enddayrange):

                
            if date(yearNum, monthNum, dayNum).weekday() == 4:
                
                if len(str(monthNum)) == 1:
                    monthNumber  = "0" + str(monthNum)
                else:
                    monthNumber = str(monthNum)


                if len(str(dayNum)) == 1:
                    dayNumber  = "0" + str(dayNum)
                else:
                    dayNumber = str(dayNum)

                datetowrite = str(yearNum)+ "-" + monthNumber + "-" + dayNumber + "\n"

                tempdat.write(datetowrite)

tempdat.close()
        
print "Date file created"


print filename
print tempfile

def copyFile(srcf, destf):
    try:
        shutil.copy(srcf, destf)
    except shutil.Error as e:
        print ('Error: %s' %e)
    except IOError as e:
        print('Error: %s' %e.strerror)


savedshareslist = open(filename, 'r')

sharesToGet = []

for line in savedshareslist:
    
    lengthofline = len(line)
    
    commapos = line.find(",")
    commapos2= line.find(",",commapos+ 1)
    
    indexpoint = line[commapos2 + 1:(lengthofline-1)]

    buyprice = str(line[commapos + 1 :commapos2])
    #print "watch/bought/sold price", buyprice
    line = line[0:(commapos-1)]
    
    sharesToGet=(str(line))

    print "share to get" , sharesToGet
    #print " "

    tempdate = open(base+ "tempdate.txt" , 'r')

    for dateline in tempdate:

        start = dateline[0:(len(dateline)-1)]

        dateofprice =" "
        
        if start[5:len(start)] == "12-25":
            dateofprice = start
            start = start[0:5] + "12-24"
            

        if start[5:len(start)] == "12-26":
            dateofprice = start
            start = start[0:5] + "12-24"
            

        if start[5:len(start)] == "01-01":
            dateofprice = start
            start = str(int(start[0:4])-1) + "-" + "12-31"

        if dateofprice == " ":
            dateofprice = start
        
        end = start 

                
        tickerSymbol = line
        tickerSymbol = sharesToGet
        histdata= ystockquote.get_historical_prices(tickerSymbol, start, end)
    
        #print str(histdata)
        
        #print dateofprice
        begstr = str(histdata).find("'Close'")
        endstr = str(histdata).find("'Open'")
        historicstr = str(histdata)
        closeprice= historicstr[(begstr + 10):(endstr - 3)]
        #print closeprice
    
        av1 = " "
        av2 = " "
    
        savefilename = base + line + ".txt"
        
        result = open(savefilename, 'a')
            
        indexpointer = int(indexpoint) + 1
        datatowrite = str(indexpointer) + ", " + closeprice + "," +  str(buyprice) + ", " + str(av1)+ ", " + str(av2) + ", " + dateofprice + ", " + str(line) 
        print datatowrite
        result.write(datatowrite + "\n")
        result.close()
        
        indexpoint = indexpointer
        #print indexpoint
                
    datafortemp = str(line) +" ," + str(buyprice)+ "," + str(indexpointer)

    histtoget = base + "sharestoget.txt"
    histupdate = open(histtoget, 'r')

    textfound = 0

    for textline in histupdate:
        #print "info to match" , line
        if textline.find(str(line)) != -1:
            textfound = 1
                
    if textfound != 1:
        histupdate.close()
        histupdate = open(histtoget, 'a')
        histupdate.write(datafortemp + "\n")
        histupdate.close()
    else:
        histupdate.close() 


savedshareslist.close()

print "Process Complete"

### END OF LISTING  ###
