Fandom

Scratchpad

Fintrade

216,094pages on
this wiki
Add New Page
Discuss this page0 Share

Ad blocker interference detected!


Wikia is a free-to-use site that makes money from advertising. We have a modified experience for viewers using ad blockers

Wikia is not accessible if you’ve made further modifications. Remove the custom ad blocker rule(s) and the page will load as expected.

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

  1. global constants

FREQ = 44100 # same as audio CD BITSIZE = -16 # unsigned 16 bit CHANNELS = 2 # 1 == mono, 2 == stereo BUFFER = 1024 # audio buffer size in no. of samples FRAMERATE = 30 # how often to check if playback has finished


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 playsound(self,soundfile): """Play sound through default mixer channel in blocking manner. This will load the whole sound into memory before playback """ sound = pygame.mixer.Sound(soundfile) clock = pygame.time.Clock() sound.play() while pygame.mixer.get_busy(): clock.tick(FRAMERATE)


def initializeSound(self,soundfile): try: pygame.mixer.init(FREQ, BITSIZE, CHANNELS, BUFFER) except pygame.error, exc: print "Could not initialize sound system: %s" % exc raise self.error self.playmusic(soundfile) return 0


def playmusic(self,soundfile): """Stream music with mixer.music module in blocking manner. This will stream the sound from disk while playing. """ clock = pygame.time.Clock() pygame.mixer.music.load(soundfile) pygame.mixer.music.play() while pygame.mixer.music.get_busy(): clock.tick(FRAMERATE)

def playmusic2(self,soundfile): """Stream music with mixer.music module using the event module to wait until the playback has finished. This method doesn't use a busy/poll loop, but has the disadvantage that you neet to initialize the video module to use the event module. Also, interrupting the playback with Ctrl-C does not work :-( Change the call to 'playmusic' in the 'main' function to 'playmusic2' to use this method. """ pygame.init() pygame.mixer.music.load(soundfile) pygame.mixer.music.set_endevent(pygame.constants.USEREVENT) pygame.event.set_allowed(pygame.constants.USEREVENT) pygame.mixer.music.play() pygame.event.wait()

def Demarker(self): #Bollinger on close PRE: self.bolarrayHIGH, self.bolarrayLOW has been created. POST: calculations done

lowlist = self.bolarrayLow highlist = self.bolarrayHigh

  1. lowlist.reverse()
  2. highlist.reverse()
  3. print lowlist
  4. print highlist

DeMax = [] DeMin = []

                1. DO DEMARKER ###########

inc = 0 temp = 0.0 for i in range(9): inc = i + 1 if float(highlist[inc]) > float(highlist[inc-1]): #If high today > than high yesterday temp = float(highlist[inc])- float(highlist[inc-1]) DeMax.append(temp) else: DeMax.append(0.0)

                      1. DeMin(i) is calculated: #######

if float(lowlist[inc]) < float(lowlist[inc-1]): temp = float(lowlist[inc-1])- float(lowlist[inc]) DeMin.append(temp) else: DeMin.append(0.0) print DeMax print DeMin

                      1. SMA of DEMAX ########

average = 0.0 for n in range(9): average = average + DeMax[n] SmaDeMax = float(average/9) # DEMARKER on 9 intervals

                    1. SMA OF DEMIN ###########

average = 0.0 for n in range(9): average = average + DeMin[n] SmaDeMin = float(average/9) # DEMARKER on 9 intervals

                      1. DMark[i] = SMA(DeMax, N)/(SMA(DeMax, N)+SMA(DeMin, N)) #####

DeMark = float(SmaDeMax/(SmaDeMax + SmaDeMin)) return DeMark


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

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)

  1. print mydate,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


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 "ASSERTION FAILURE: 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

  1. print temp

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

def returnMonthDayYearFormat_in_YearMonthDay_format(self,dateformat): #month/day/year format

  1. print dateformat

temp = string.split(dateformat, '/') #temp contains ticker and close

  1. print temp

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


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

  1. print temp1

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



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()

  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

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 loop in self.ticklist:
  2. self.readvalues(loop) #POST: self.bollinger list has closes in date descending order.
  3. self.dobollinger()

return

  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

                            1. testIfCorrectTickerIsBeingProcessed(ticker): ##########

myfile = open(ticker,"r") #Open say nymexgci.txt and look for "Crude" line = myfile.readline() #Read first line

  1. print "This should be crude", line

temp = string.strip(line) #strip trailing leading spaces temp = string.split(temp, ' ') #temp contains ticker and close

  1. print temp

Crude = string.strip(temp[0]) # Must contain "Crude" if Crude <> "Crude": pass

  1. print "Crude not found"
  2. raise self.error

for x in range(10):

  1. print line

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

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)

  1. if mydate == 20080718: lastDateInTextFileFoundFLAG == True

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

  1. if lastDateInTextFileFoundFLAG == False:
  2. print " LAST DATE IN TEXTFILE NOT READ IN , ASSERTION FAILURE"
  3. raise self.error

#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

                                        1. READ THE CLOSE VALUES ###################

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 " "

                                        1. READ THE LOW VALUES ###################

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 " "

                                        1. READ THE HIGH VALUES ###################

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

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"

  1. print ticker

recentDate = self.getMostRecentDateFrom5minTickFile(ticker) #recentDate in integer format

                            1. testIfCorrectTickerIsBeingProcessed(ticker): ##########

myfile = open(ticker,"r") #Open say nymexRLT.txt and look for "Crude" line = myfile.readline() #Read first line

for x in range(10):

  1. print line

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

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)

  1. print mytime
  2. raise self.error
  3. if mydate == 20080718: lastDateInTextFileFoundFLAG == True

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

  1. if AMorPM == 'PM': raise self.error
  2. print temp
  3. raise self.error

if '12' in temp:

  1. print temp
  2. raise self.error

print " om 12 te skip is nie reg, fix in code: LINE 680 "

  1. continue #skip all 12 occurances

closedict[mytime] = close # LOW, HIGH OR CLOSE

  1. print mytime, close

lowdict[mytime] = low highdict[mytime] = high myfile.close() #close relevant file such as nymexGCI.txt

  1. if lastDateInTextFileFoundFLAG == False:
  2. print " LAST DATE IN TEXTFILE NOT READ IN , ASSERTION FAILURE"
  3. raise self.error

#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

                                        1. READ THE CLOSE VALUES ###################

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

  1. print self.bolarray # CLOSE
  2. print " "
  3. raise self.error
                                        1. READ THE LOW VALUES ###################

counter = 0 self.bolarrayLow = [] #clear bollinger array LOW for loop in temp1low: #loop through tuple , list and scan into bollinger array.

  1. print loop

counter = counter + 1 self.bolarrayLow.append(loop[1]) #For close if counter == 20: break

  1. print self.bolarrayLow

print " "

                                        1. READ THE HIGH VALUES ###################

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

  1. print self.bolarrayHigh
  2. print "Must be descending order procudure readvalues"

print " " print "The date is:", mydate return


def readval(self,ticker): # do calculatoins on most recent data USED with RLT most recent calc 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 bolling ticker = ticker + ".txt" recentDate = self.getMostRecentDateFrom5minTickFile(ticker) #recentDate in integer format

                            1. testIfCorrectTickerIsBeingProcessed(ticker): ##########

myfile = open(ticker,"r") #Open say nymexRLT.txt and look for "Crude" while 1: #scan all close prices into clostlist line = myfile.readline() if not line: 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 temp1.append(temp) myfile.close() #close relevant file such as nymexGCI.txt temp1.reverse() for x in range(20): #TODAYS BOLLINGER VALUE. temp = temp1[x] 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 close = float(close) myopen = float(myopen) high = float(high) low = float(low)

self.bolarray.append(close) #For close self.bolarrayLow.append(low) #For close self.bolarrayHigh.append(high) #For close print "The date is:", mydate return


def readvalPrevious(self,ticker): # do calculatoins on PREVIOUS data 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 bolling ticker = ticker + ".txt" recentDate = self.getMostRecentDateFrom5minTickFile(ticker) #recentDate in integer format

                            1. testIfCorrectTickerIsBeingProcessed(ticker): ##########

myfile = open(ticker,"r") #Open say nymexRLT.txt and look for "Crude" while 1: #scan all close prices into clostlist line = myfile.readline() if not line: 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 temp1.append(temp) myfile.close() #close relevant file such as nymexGCI.txt temp1.reverse() temp = temp1[0] temp = string.split(temp, ';') #temp has date,time,open,high,low,close 6/17/2008;133.87; low = string.strip(temp[4]) #temp3 - low high = string.strip(temp[3]) #temp2 - high low1 = float(low) high1 = float(high)

for x in range(21): # GET YESTERDAYS BOLLINGER VALUE. if x == 0: continue #Skip most recent data for previous data. temp = temp1[x] 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 close = float(close) myopen = float(myopen) high = float(high) low = float(low)

self.bolarray.append(close) #For close self.bolarrayLow.append(low) #For close self.bolarrayHigh.append(high) #For close print "The date is:", mydate return low1 , high1



def rltBollingerCalcWithRltClose(self): #PRE: self.bolarray and self.upperbol done on the close #PROBLEM is that close is determined in realtime #should calculate the bollinger value for yesterday and see if todays rltclose is < or >

                            1. IF VALUE IS LARGER THAN UPPERBOLLINGER ON THE CLOSE #######

print "USE PREVIOUS CLOSE TO DETERMINE BOLLINGER VALUE" scalefactor = self.upperbol #3% scale factor down to trigger alert if self.bolarray[0] >= scalefactor: # UPPER BOLLINGER ON previous day's CLOSE WRONG FIXXXXX!!!!!!!!!!!!! print "Upper bollinger scaled 3%", scalefactor print "RLT close", self.bolarray[0] y.initializeSound(soundfile = 'onestop.mid') else: print self.upperbol print self.bolarray[0]

                            1. IF VALUE IS SMALLER THAN UPPERBOLLINGER ON THE CLOSE ######

scalefactor = self.lowerbol #3% scale factor down to trigger alert if scalefactor >= self.bolarray[0]: # LOWER BOLLINGER ON previous day's CLOSE yesterdays bollinger band WRONG FORMULA print "Lower bollinger", self.lowerbol print "CLOSE less than lower bollinger of YESTERDAY", self.bolarray[0] y.initializeSound(soundfile = 'onestop.mid') else: print "self.lowerbol" , self.lowerbol print "self.bolarray[0]" , self.bolarray[0]


def IsLowLessThanBollingerOnCloseOfPreviousData(self,low): scalefactor = self.lowerbol #3% scale factor down to trigger alert if scalefactor >= low: # LOWER BOLLINGER ON previous day's CLOSE yesterdays bollinger band WRONG FORMULA print "Lower bollinger on CLOSE", scalefactor print "LOW of RLT less than lower bollinger on close of previous bar", low y.initializeSound(soundfile = 'onestop.mid') else: print "self.lowerbol" , self.lowerbol print "self.bolarray[0]" , low

return


def main(self): #Overloaded virtual main function

  1. y.readvalues('nymexRLT') #overload way EOD data is imported

y.readval('nymexRLT') #overload way EOD data is imported

  1. y.dobollinger2('bolarrayLOW') #Bollinger on close sorted high to low ???? what order

y.dobollinger2('bolarrayCLOSE') #Bollinger on close

  1. y.dobollinger2('bolarrayHIGH') #Bollinger on close

temp = y.Demarker() #PRE: bolarray sorted high to low temp = 100*temp print "The Demarker is:", temp if temp > 80: pass

  1. y.initializeSound(soundfile = 'onestop.mid')

y.rltBollingerCalcWithRltClose()

def main2(self): low,high = y.readvalPrevious('nymexRLT') # do calculatoins on PREVIOUS data y.dobollinger2('bolarrayCLOSE') #Bollinger on close self.IsLowLessThanBollingerOnCloseOfPreviousData(low)




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

  1. y = bollingerRLT('nymexRLT') #Extend bollinger class on 5min data.
  2. y.main2()

Also on Fandom

Random wikia