#! /usr/bin/python2.7

# Rev 2.0 RKN 08/01/2016
# Rev 1.0 RKN 15/12/2015
# Plots highs and lows from the 52s.L.txt file
# Creates temporary csv files for easy import into GnuPlot
# Averages not shown until average period exceeded


import Gnuplot, Gnuplot.funcutils
import numpy as np
from collections import deque

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

av1sum = deque([0,0,0,0,0,0,0,0])
av2sum = deque([0,0,0,0,0,0,0,0])

countindex = 1

savefilename =  base + "52s.L.txt"

result = open(savefilename, 'r')

tempcsvfilename = base + "tempcsv.csv"
    
graphcsvdataprice = open(tempcsvfilename, 'w')

tempcsvfilename2 = base + "tempcsv2.csv"
    
graphcsvdatabuy = open(tempcsvfilename2, 'w')


tempcsvfilename3 = base + "tempcsv3.csv"
    
graphcsvdataav1 = open(tempcsvfilename3, 'w')

tempcsvfilename4 = base + "tempcsv4.csv"
    
graphcsvdataav2 = open(tempcsvfilename4, 'w')





for graphdata in result:

    commapos = graphdata.find(",")
    secondcommapos = graphdata.find(",", commapos+1)
    thirdcommapos = graphdata.find(",", secondcommapos+1)
    fourthcommapos = graphdata.find(",", thirdcommapos+1)
    fifthcommapos = graphdata.find(",", fourthcommapos+1)
    
    
    countindex = countindex + 1

    
    buydata1 = graphdata[0:commapos]
    buydata2 = graphdata[secondcommapos:thirdcommapos]

       

    av1data = graphdata[commapos+1:secondcommapos]
    av2data = graphdata[secondcommapos+1:thirdcommapos]          
    
    av1strval = float(av1data)
    av2strval = float(av2data)

    av1sum.append(av1strval)
    av2sum.append(av2strval)
    av1sum.popleft()
    av2sum.popleft()

    
    av1data2 = sum(av1sum)/8
    
    
    av2data2 = sum(av2sum)/8
    

    graphdata = graphdata[0:secondcommapos]

    buydata = str(buydata1) +str(buydata2)
    
        
    av1data = str(buydata1) + "," + str(av1data2)
    
    
    av2data = str(buydata1) + "," + str(av2data2)
    
    graphcsvdataprice.write(graphdata + "\n")
    graphcsvdatabuy.write(buydata +"\n")
    if countindex >8 :
        graphcsvdataav1.write(av1data +"\n")
    if countindex > 8:
        graphcsvdataav2.write(av2data +"\n")

graphcsvdataprice.close()
graphcsvdatabuy.close()
graphcsvdataav1.close()
graphcsvdataav2.close()



g = Gnuplot.Gnuplot (persist=1)
g.title(savefilename) # Sets the title of the graph
g('set style data lines') # Sets the line style to simple lines
g('set terminal x11 size 1000,600')
g('set terminal x11 position 10,10')

Line1= Gnuplot.Data(np.genfromtxt(str(tempcsvfilename), delimiter = ","))
Line2= Gnuplot.Data(np.genfromtxt(str(tempcsvfilename2), delimiter = ","))
Line3= Gnuplot.Data(np.genfromtxt(str(tempcsvfilename3), delimiter = ","))
Line4= Gnuplot.Data(np.genfromtxt(str(tempcsvfilename4), delimiter = ","))

g.plot(Line1, Line2, Line3, Line4)


g.reset()


### END OF LISTING ###


