Fintrade

import math import sys import string import pygame from operator import itemgetter

class bollinger: def __init__(self,stock): if stock == 'gold': self.file = "gold.txt" self.closelist = [] #with gold.txt for example self.eod = {} #when reading shares.txt into dictionary self.temp = {} self.temp1 = [] self.error = "Error" self.bolarray = [] #clear bollinger array close self.bolarrayLow = [] #clear bollinger array LOW self.bolarrayHigh = [] #clear bollinger array HIGH self.eodlist = []

self.ticklist = [ '10year', '30year', 'copper', 'coffee', 'cotton', 'corn', 'dow', 'eurdol', 'gold', 'nikei', 'plat', 'pald', 'russel', 'silver', 'soybeans', 'soymeal', 'oilnymex', 'oilbrent', 'SP500', 'sugar', 'weat']

def Demarker(self):  #Bollinger on close '''PRE: self.bolarrayHIGH, self.bolarrayLOW has been created. POST: calculations done''' lowlist = self.bolarrayLow highlist = self.bolarrayHigh lowlist.reverse highlist.reverse DeMax = [] DeMin = [] inc = 0 for i in range(9): inc = i + 1 if highlist[inc] > highlist[inc-1]:  #If high today > than high yesterday temp = highlist[inc]-highlist[inc-1] DeMax.append(temp) else: DeMax.append(0) if lowlist[inc] < lowlist[inc-1]: temp = lowlist[inc-1]-lowlist[inc] DeMin.append(temp) else: DeMin.append(0) print DeMax print DeMin average = 0.0 for n in range(9): average = average + DeMax[n] SmaDeMax = float(average/9) # DEMARKER on 9 intervals average = 0.0 for n in range(9): average = average + DeMin[n] SmaDeMin = float(average/9) # DEMARKER on 9 intervals DeMark = SmaDeMax/(SmaDeMax + SmaDeMin) print DeMark return def readvalues(self,ticker): '''		GOLD.TXT Import close prices into closepricelist Format for this is date close files ie "gold.txt" DONE EVERY DAY PRE: gold.txt selected or suitable stock text file selected. textfile must have format DATE, CLOSE in descending order and updated with latest date POST: SELF.BOLARRAY has closes in descending order'''
 * 1) 		highlist = [10,9,8,7,20,5,4,3,2,254] #LIST must be descending
 * 2) 		lowlist = [1,2,35,4,5,6,7,8,9,121]	#list must be descending
 * 1)  DO DEMARKER  				###########
 * 1) problem if first item in list
 * 1) 		DeMin(i) is calculated: #######
 * 2) If low(i) < low(i-1),
 * 3) then DeMin(i) = low(i-1)-low(i), otherwise DeMin(i) = 0
 * 4) 			templow1 = lowlist[inc]
 * 5) 			templow0 = lowlist[i]
 * 1) SMA of DEMAX   ########
 * 1) SMA OF DEMIN ###########
 * 1) DMark[i] = SMA(DeMax, N)/(SMA(DeMax, N)+SMA(DeMin, N)) #####

closedict = {} temp1 = [] self.bolarray = [] ticker = ticker + ".txt" print ticker myfile = open(ticker,"r") while 1: #scan all close prices into clostlist line = myfile.readline if not line: break temp = string.strip(line) if temp <> '':					  #skip blank lines temp = string.split(temp, ' ') #temp contains ticker and close mydate = string.strip(temp[0]) close = string.strip(temp[1]) mydate = int(mydate) close = float(close) closedict[mydate] = close myfile.close #close gold.txt #PRE: closedict{} has date and close temp1 = sorted(closedict.items, reverse = True)  #sorted list,tuples of date, closes in descending order counter = 0 for loop in temp1:  #loop through tuple, list and scan into bollinger array. counter = counter + 1 closeprice = loop[1] self.bolarray.append(closeprice) if counter == 20: break return
 * 1) 				print mydate,close

def getMostRecentDateFrom5minTickFile(self, ticker): myfile = open(ticker,"r") #Open say nymexRLT.txt and look for  "Crude" line = myfile.readline #Read first line while 1: line = myfile.readline if not line:  #IF EOF found then break but does so prematurely. break temp = string.strip(line) # Date;Open;High;Low;Close; format # change to Date;Time;Open;High;Low;Close;  format

if temp <> '':					   #skip blank lines temp = string.split(temp, ';') #temp has date,time,open,high,low,close  6/17/2008;133.87; mydate = string.strip(temp[0]) #Contains date in month/day/year format

mydate = self.returnMonthDayYearFormat_in_YearMonthDay_format(mydate) mydate = int(mydate) myfile.close return mydate

def dobollinger(self):  #Bollinger on close '''PRE: self.bolarray descending order' POST: self.upperbol updated''' templist = [] xjlist = [] lenofarray = len(self.bolarray) if lenofarray <> 20: print "array not right" raise self.error average = 0.0 for n in range(20): #get the average average = average + self.bolarray[n] daymov20 = average/20 #919.56 avtemp = 0.0 for n in range(20): temp1 = daymov20 - self.bolarray[n] temp = pow(temp1,2) avtemp = avtemp + temp avtemp = avtemp/20 avtemp = math.sqrt(avtemp) self.upperbol = (daymov20) + (2*avtemp) self.lowerbol = daymov20 - 2*avtemp print "Upper bollinger = ", self.upperbol print "Lower bollinger = ", self.lowerbol print "Mov average = ", daymov20

return

def eodupdate(self): '''		SHARES.TXT format is eod updates with all tickers and close prices DONE EVERY DAY PRE:shares.txt has close prices and tickers and the date must be first line POST: eod{} dictionary has key values of tickers and close '''		sharesfile = open("shares.txt",'r') self.eod = {} line = sharesfile.readline #Get date which must be first line mydate = string.strip(line) lengthOfDate = len(mydate) if lengthOfDate == 8: mydate = int(mydate) self.eod["thedate"] = mydate else: while 1: print "date string wrong" while 1: #read shares.txt line = sharesfile.readline if not line: break temp = string.strip(line) temp = string.split(temp, ' ') #temp contains ticker and close ticker = string.strip(temp[0]) close = string.strip(temp[1]) self.eod[ticker] = close sharesfile.close return

def dobollinger2(self,temp):  #Bollinger on close '''PRE: self.bolarray descending order' POST: self.upperbol updated''' templist = [] xjlist = [] flag = False if temp == 'bolarrayLOW': mylist = self.bolarrayLow print "Bollinger array of LOW values" flag = True

if temp == 'bolarrayCLOSE': mylist = self.bolarray print "Bollinger array of CLOSE values" flag = True

if temp == 'bolarrayHIGH': mylist = self.bolarrayHigh print "Bollinger array of HIGH values" flag = True if flag == False: raise self.error lenofarray = len(mylist) if lenofarray <> 20: print "array not right" raise self.error average = 0.0 daymov20 = 0.0 for n in range(20): #get the average average = float(average) + float(mylist[n]) daymov20 = float(average/20) #919.56 avtemp = 0.0 for n in range(20): temp1 = daymov20 - float(mylist[n]) temp = float(pow(temp1,2)) temp = float(temp/20) avtemp = float(avtemp) + float(temp) avtemp = math.sqrt(avtemp) self.upperbol = float(daymov20 + (2*avtemp)) self.lowerbol = float(daymov20 - (2*avtemp)) print "Upper bollinger = ", self.upperbol print "Lower bollinger = ", self.lowerbol print "Mov average = ", daymov20 print "###########################" print "           " return

def updateSharefiles(self): '''PRE: self.eod {} dict has date, tickers and close POST: i.e. gold.txt,copper, plat updated with date, close ASSERT: no double date entries in text file It wont if you write and not append' {'copper': '3', 'gold': '954.32', 'soybeans': '66', 'oilnymex': '89', 'russel': '34', 'pald': '33', 'cotton': '4', 'sugar': '12', 'SP500': '66', 'coffee': '4', 'nikei': '34', 'corn': '5', 'plat': '33', 'thedate': 20080724, 'oilbrent': '78', 'soymeal': '66', '30year': '2', '10year': '123.24', 'weat': '87', 'eurdol': '7', 'dow': '6', 'silver': '44'} '''		mydate = self.eod["thedate"] #Use key to get value

for ticker in self.ticklist:  #iterating over ticker list close = self.eod[ticker] #PRE: self.eod{} self.shareDatesAndCloseintoDict(ticker,mydate,close) #POST: self.temp1[] has all dates, closes in list tuple format #update i.e. gold.txt with correct values #get gold.txt into a dictionary #self.temp1[] list of ordered tuples date and close for ticker ticker = ticker + ".txt" myfile = open(ticker,"w") for loop in self.temp1: #iterate over list,tuple dates in descending order writing it to ie gold.txt, plat.txt ect. temp = str(loop[0]) + ' ' + str(loop[1]) myfile.write(temp + '\r\n') #write date close to ie. gold.txt myfile.close return

def shareDatesAndCloseintoDict(self,sharefile,thedate,close): '''Get dates and close of specific stock ie. gold.txt into a dictionary POST: list temp1[] has tuples with date,close sorted hight to low''' tempdict = {} self.temp1 = [] tempdict[thedate] = close sharefile = sharefile + ".txt" myfile = open(sharefile, "r")     #open ie gold.txt file for reading only while 1: line = myfile.readline if not line: break temp = string.strip(line) if temp == '':  # if blank line read continue back to beginning of loop continue temp = string.split(temp, ' ') #temp contains ticker and close mydate = int(string.strip(temp[0])) close = float(string.strip(temp[1])) if mydate <> thedate:   #so that new date is not replaced if date is in textfile. tempdict[mydate] = close self.temp1 = sorted(tempdict.items, reverse = True) return
 * 1) 			print temp

def returnMonthDayYearFormat_in_YearMonthDay_format(self,dateformat): #month/day/year format temp = string.split(dateformat, '/') #temp contains ticker and close year = temp[2] month = temp[0] day = temp[1] year = string.zfill(year,4) month = string.zfill(month,2) day = string.zfill(day,2) mydate = year + month + day return mydate
 * 1) 		print dateformat
 * 1) 		print temp

def getTheTimeInIntegerFormat(self,timeformat): #2:10:00 AM # WHAT ABOUT AM / PM TRANSITION ? #questions: What happens at PM/AM transition temp1 = string.split(timeformat, ' ') #temp contains ticker and close if temp1[1] == 'PM': AMorPM = 'PM' else: AMorPM = 'AM' timeOnly = temp1[0]  #  2:10:00  stripped out the AM		timeOnly = string.split(timeOnly, ':') #temp contains ticker and close hour = timeOnly[0] minute = timeOnly[1] seconds = timeOnly[2] hour = string.zfill(hour,2) minute = string.zfill(minute,2) seconds = string.zfill(seconds,2) mytimeStrFormat = hour + minute + seconds return mytimeStrFormat, AMorPM
 * 1) 		print temp1

def main(self): self.eodupdate  #Uses shares.txt  done everyday self.updateSharefiles #PRE: self.eod {} dict has date, tickers and close self.readvalues("gold") #POST: self.bollinger list has closes in date descending order. self.dobollinger self.readvalues("oilnymex") #POST: self.bollinger list has closes in date descending order. self.dobollinger		 #POST: upperbol, lowerbol value calculated self.readvalues("sp500") #POST: self.bollinger list has closes in date descending order. self.dobollinger self.readvalues("pald") #POST: self.bollinger list has closes in date descending order. self.dobollinger self.readvalues("eurdol") #POST: self.bollinger list has closes in date descending order. self.dobollinger
 * 1) for gold put trade at 0.5% above or below bollinger band about $4,00
 * 2) For nymex oil trade 1% above bollinger or about $1.45 above upper bollinger

return
 * 1) 		for loop in self.ticklist:
 * 2) 			self.readvalues(loop) #POST: self.bollinger list has closes in date descending order.
 * 3) 			self.dobollinger


 * 1) 		while 1:
 * 2) 			self.myfile = open("gold.txt","a")
 * 3) 			self.myfile.write("this asdlfkj \r\n")
 * 4) 			self.myfile.close

class bollingerGCI(bollinger): #Extend bollinger class def __init__(self,stock): if stock == 'nymexgci': self.file = "oilnymex.txt" self.closelist = [] #with gold.txt for example self.eod = {} #when reading shares.txt into dictionary self.temp = {} self.temp1 = [] self.bolarray = [] self.ticklist = ['nymexcgi'] self.eodlist = [] self.error = "Error: Date keyword not found in GCI text file" self.EofReachedAndShouldNotHave = "Eof reached to early should not have done so, means there is no data in file" self.bolarray = [] #clear bollinger array close self.bolarrayLow = [] #clear bollinger array LOW self.bolarrayHigh = [] #clear bollinger array HIGH

def readvalues(self,ticker): #overload way EOD data is imported '''		GOLD.TXT Import close prices into closepricelist Format for this is date close files ie "gold.txt" DONE EVERY DAY PRE: nymexgci.txt selected for example in GCI format textfile must have format DATE, CLOSE in any order and updated with latest date POST: SELF.bolarray	 has closes in descending order SELF.bolarrayLow has closes in descending order SELF.bolarrayHigh has closes in descending order '''

# Date;Open;High;Low;Close; closedict = {} # LOW, HIGH OR CLOSE lowdict = {} highdict = {} temp1 = [] self.bolarray = []    # clear bollinger array CLOSE self.bolarrayLow = [] #clear bollinger array LOW self.bolarrayHigh = [] #clear bollinger array HIGH ticker = ticker + ".txt" print ticker myfile = open(ticker,"r") #Open say nymexgci.txt and look for  "Crude" line = myfile.readline #Read first line temp = string.strip(line) #strip trailing leading spaces temp = string.split(temp, ' ') #temp contains ticker and close Crude = string.strip(temp[0]) # Must contain "Crude" if Crude <> "Crude": pass for x in range(10): line = myfile.readline temp = string.strip(line) #strip trailing leading spaces if temp == '': continue #Skip all blank lines if not line: raise self.EofReachedAndShouldNotHave temp = string.split(temp, ';') #temp contains ticker and close if temp[0] == "Date":  #if date found break out of loop, next data will be dates and close,high,low,open break if temp[0] <> "Date": raise self.error lastDateInTextFileFoundFLAG = False while 1: #scan all close prices into clostlist line = myfile.readline if not line:  #IF EOF found then break but does so prematurely. break temp = string.strip(line) # Date;Open;High;Low;Close; format # change to Date;Time;Open;High;Low;Close;  format
 * 1)   testIfCorrectTickerIsBeingProcessed(ticker): ##########
 * 1) 		print "This should be crude", line
 * 1) 		print temp
 * 1) 			print "Crude not found"
 * 2) 			raise self.error
 * 1) 			print line

if temp <> '':					   #skip blank lines temp = string.split(temp, ';') #temp has date,time,open,high,low,close  6/17/2008;133.87; mydate = string.strip(temp[0]) #Contains date in month/day/year format mytime = string.strip(temp[1]) myopen = string.strip(temp[2]) #temp1 - open high = string.strip(temp[3])	#temp2 - high low = string.strip(temp[4])		#temp3 - low close = string.strip(temp[5])	#temp4 - close mydate = self.returnMonthDayYearFormat_in_YearMonthDay_format(mydate) mydate = int(mydate) close = float(close) myopen = float(myopen) high = float(high) low = float(low) closedict[mydate] = close # LOW, HIGH OR CLOSE lowdict[mydate] = low highdict[mydate] = high myfile.close #close relevant file such as nymexGCI.txt #PRE: closedict{} has date and close temp1close = sorted(closedict.items, reverse = True)  #sorted list,tuples of date, closes in descending order temp1low = sorted(lowdict.items, reverse = True)  #sorted list,tuples of date, closes in descending order temp1high = sorted(highdict.items, reverse = True)  #sorted list,tuples of date, closes in descending order counter = 0 self.bolarray = [] #clear bollinger array close for loop in temp1close:  #loop through tuple, list and scan into bollinger array. counter = counter + 1 self.bolarray.append(loop[1]) #For close if counter == 20: break print self.bolarray # CLOSE print " " counter = 0 self.bolarrayLow = [] #clear bollinger array LOW for loop in temp1low:  #loop through tuple, list and scan into bollinger array. counter = counter + 1 self.bolarrayLow.append(loop[1]) #For close if counter == 20: break print self.bolarrayLow print " " counter = 0 self.bolarrayHigh = [] #clear bollinger array HIGH for loop in temp1high:  #loop through tuple, list and scan into bollinger array. counter = counter + 1 self.bolarrayHigh.append(loop[1]) #For close if counter == 20: break print self.bolarrayHigh print "Must be descending order procudure readvalues" print "  " print "The date is:", mydate return
 * 1) 				if mydate == 20080718: lastDateInTextFileFoundFLAG == True
 * 1) 		if lastDateInTextFileFoundFLAG == False:
 * 2) 			print " LAST DATE IN TEXTFILE NOT READ IN, ASSERTION FAILURE"
 * 3) 			raise self.error
 * 1) READ THE CLOSE VALUES ###################
 * 1) READ THE LOW VALUES ###################
 * 1) READ THE HIGH VALUES ###################

def main(self): #Overloaded virtual main function y.readvalues('nymexgci') #overload way EOD data is imported y.dobollinger2('bolarrayLOW')  #Bollinger on close y.dobollinger2('bolarrayCLOSE')  #Bollinger on close y.dobollinger2('bolarrayHIGH')  #Bollinger on close

class bollingerRLT(bollingerGCI): #Extend bollinger class def __init__(self,stock): self.closelist = [] #with gold.txt for example self.eod = {} #when reading shares.txt into dictionary self.temp = {} self.temp1 = [] self.bolarray = [] self.ticklist = ['nymexRLT'] self.eodlist = [] self.error = "Error: Date keyword not found in GCI text file" self.EofReachedAndShouldNotHave = "Eof reached to early should not have done so, means there is no data in file" self.bolarray = [] #clear bollinger array close self.bolarrayLow = [] #clear bollinger array LOW self.bolarrayHigh = [] #clear bollinger array HIGH

def readvalues(self,ticker): #overload way EOD data is imported '''		GOLD.TXT Import close prices into closepricelist Format for this is date close files ie "gold.txt" DONE EVERY DAY PRE: nymexgci.txt selected for example in GCI format textfile must have format DATE, CLOSE in any order and updated with latest date POST: SELF.bolarray	 has closes in descending order SELF.bolarrayLow has closes in descending order SELF.bolarrayHigh has closes in descending order '''

# Date;Open;High;Low;Close; closedict = {} # LOW, HIGH OR CLOSE lowdict = {} highdict = {} temp1 = [] self.bolarray = []    # clear bollinger array CLOSE self.bolarrayLow = [] #clear bollinger array LOW self.bolarrayHigh = [] #clear bollinger array HIGH ticker = ticker + ".txt" recentDate = self.getMostRecentDateFrom5minTickFile(ticker) #recentDate in integer format myfile = open(ticker,"r") #Open say nymexRLT.txt and look for  "Crude" line = myfile.readline #Read first line for x in range(10): line = myfile.readline temp = string.strip(line) #strip trailing leading spaces if temp == '': continue #Skip all blank lines if not line: raise self.EofReachedAndShouldNotHave temp = string.split(temp, ';') #temp contains ticker and close if temp[0] == "Date":  #if date found break out of loop, next data will be dates and close,high,low,open break if temp[0] <> "Date": raise self.error lastDateInTextFileFoundFLAG = False while 1: #scan all close prices into clostlist line = myfile.readline if not line:  #IF EOF found then break but does so prematurely. break temp = string.strip(line) # Date;Open;High;Low;Close; format # change to Date;Time;Open;High;Low;Close;  format
 * 1) 		print ticker
 * 1)   testIfCorrectTickerIsBeingProcessed(ticker): ##########
 * 1) 			print line

if temp <> '':					   #skip blank lines temp = string.split(temp, ';') #temp has date,time,open,high,low,close  6/17/2008;133.87; mydate = string.strip(temp[0]) #Contains date in month/day/year format mytime = string.strip(temp[1]) myopen = string.strip(temp[2]) #temp1 - open high = string.strip(temp[3])	#temp2 - high low = string.strip(temp[4])		#temp3 - low close = string.strip(temp[5])	#temp4 - close mytime,AMorPM = self.getTheTimeInIntegerFormat(mytime) mytime = int(mytime) close = float(close) myopen = float(myopen) high = float(high) low = float(low) mydate = self.returnMonthDayYearFormat_in_YearMonthDay_format(mydate) mydate = int(mydate) if recentDate == mydate: #Process time temp = str(mytime) #convert time to string if '12' in temp: print " om 12 te skip is nie reg, fix in code: LINE 680	" closedict[mytime] = close # LOW, HIGH OR CLOSE lowdict[mytime] = low highdict[mytime] = high myfile.close #close relevant file such as nymexGCI.txt #PRE: closedict{} has date and close temp1close = sorted(closedict.items, reverse = True)  #sorted list,tuples of date, closes in descending order temp1low = sorted(lowdict.items, reverse = True)  #sorted list,tuples of date, closes in descending order temp1high = sorted(highdict.items, reverse = True)  #sorted list,tuples of date, closes in descending order counter = 0 self.bolarray = [] #clear bollinger array close for loop in temp1close:  #loop through tuple, list and scan into bollinger array. print loop counter = counter + 1 self.bolarray.append(loop[1]) #For close if counter == 20: break counter = 0 self.bolarrayLow = [] #clear bollinger array LOW for loop in temp1low:  #loop through tuple, list and scan into bollinger array. counter = counter + 1 self.bolarrayLow.append(loop[1]) #For close if counter == 20: break print " " counter = 0 self.bolarrayHigh = [] #clear bollinger array HIGH for loop in temp1high:  #loop through tuple, list and scan into bollinger array. counter = counter + 1 self.bolarrayHigh.append(loop[1]) #For close if counter == 20: break print "  " print "The date is:", mydate return
 * 1) 				print mytime
 * 2) 				raise self.error
 * 3) 				if mydate == 20080718: lastDateInTextFileFoundFLAG == True
 * 1) 					if AMorPM == 'PM': raise self.error
 * 2) 					print temp
 * 3) 					raise self.error
 * 1) 						print temp
 * 2) 						raise self.error
 * 1) 						continue     #skip all 12 occurances
 * 1) 					print mytime, close
 * 1) 		if lastDateInTextFileFoundFLAG == False:
 * 2) 			print " LAST DATE IN TEXTFILE NOT READ IN, ASSERTION FAILURE"
 * 3) 			raise self.error
 * 1) READ THE CLOSE VALUES ###################
 * 1) 		print self.bolarray # CLOSE
 * 2) 		print " "
 * 3) 		raise self.error
 * 4) READ THE LOW VALUES ###################
 * 1) 			print loop
 * 1) 		print self.bolarrayLow
 * 1) READ THE HIGH VALUES ###################
 * 1) 		print self.bolarrayHigh
 * 2) 		print "Must be descending order procudure readvalues"

def main(self): #Overloaded virtual main function y.readvalues('nymexRLT') #overload way EOD data is imported y.dobollinger2('bolarrayLOW')  #Bollinger on close y.dobollinger2('bolarrayCLOSE')  #Bollinger on close y.dobollinger2('bolarrayHIGH')  #Bollinger on close

if __name__ == '__main__':
 * 1) 	y = bollingerGCI('nymexgci') #Extend bollinger class EOD update.
 * 2) 	y.main
 * 3) 	y.Demarker

y = bollingerRLT('nymexRLT') #Extend bollinger class on 5min data. y.readvalues('nymexRLT') y.Demarker
 * 1) 	y.main
 * 1) 	y.test
 * 2) 	y.main