Skip to content

Instantly share code, notes, and snippets.

@sharavsambuu
Forked from 18182324/OpenDayRangeSP500
Created May 12, 2024 15:27
Show Gist options
  • Save sharavsambuu/81b76b50808fd1b4bb56e0ab39a6764f to your computer and use it in GitHub Desktop.
Save sharavsambuu/81b76b50808fd1b4bb56e0ab39a6764f to your computer and use it in GitHub Desktop.
Opening Range Breakout OHLC [Python]
from pandas import *
from datetime import *
import pdb as pdb
df = DataFrame.from_csv('aapl_1-2012_5min.csv')
dayCount=0
rangeHigh = -1
rangeLow = 9999
openDayRangeDict = {}
getRange = 1
previousDay = 0
upbreak1 = 0
upbreak2 = 0
downbreak1 = 0
downbreak2 = 0
lastClose = 0
maxClose = -1
minClose = 9999
signalCount=0
entryClose = 0
signalDict = {}
for i in range(2,len(df)):
if dayCount==6:
dayCount==0
row = df[(i-1):i]
currentDay = row.index[0].day
print row.index[0]
curClose = row['close'].values[0]
curOpen = row['open'].values[0]
#if today's date is different from the previous date
if not currentDay == previousDay:
#lastClose was yesterday's final closing price
#store everything: open day range, max close, min close, final close
if maxClose>0 and upbreak2==1: #if it actually broke up
signalDay = {}
signalDay['rangeHigh'] = rangeHigh
signalDay['rangeLow'] = rangeLow
signalDay['signalCount'] = signalCount
signalDay['maxClose'] = maxClose
signalDay['minClose'] = minClose
signalDay['entryClose'] = entryClose
signalDay['finalClose'] = lastClose
signalDay['type'] = 1
signalDict[row.index[0]] = signalDay
if minClose<9999 and downbreak2==1: #if it actually broke down
signalDay = {}
signalDay['rangeHigh'] = rangeHigh
signalDay['rangeLow'] = rangeLow
signalDay['signalCount'] = signalCount
signalDay['maxClose'] = maxClose
signalDay['minClose'] = minClose
signalDay['entryClose'] = entryClose
signalDay['finalClose'] = lastClose
signalDay['type'] = -1
signalDict[row.index[0]] = signalDay
print 'last bar was last bar in that day'
#reset all flags
rangeHigh = -1
rangeLow = 9999
maxClose = -1
minClose = 9999
dayCount = 0
signalCount = 0
getRange = 1
upbreak1 = 0
upbreak2 = 0
downbreak1 = 0
downbreak2 = 0
entryClose = 0
#while we are still in the open day range
if dayCount<6 and getRange==1:
if row['high'].values[0]>rangeHigh:
rangeHigh = row['high'].values[0]
if row['low'].values[0]<rangeLow:
rangeLow = row['low'].values[0]
if dayCount==5:
openDayRangeDict['high']=rangeHigh
openDayRangeDict['low']=rangeLow
getRange=0
#set_trace() #diagnostic
#now we have the open day range
dayCount+=1
#if we already have an open day range, wait for a trade signal
if getRange==0:
#if we've already had second up break, keep track of max close, min close after that
if upbreak2==1 or downbreak2==1:
if curClose>maxClose:
maxClose = curClose
if curClose<minClose:
minClose = curClose
else:
signalCount+=1 #count bars b/w open day range and signal
#UP BREAK
if curClose>openDayRangeDict['high'] and curClose>curOpen:
if upbreak1==1 and curClose>openDayRangeDict['high'] and curClose>curOpen and curClose>lastClose and downbreak2 == 0:
#we've gotten a second up day above the range
upbreak2 = 1
entryClose = curClose
#so start keeping track of highest close, as well as close at EOD
#pdb.set_trace() #diagnostic
#we've broken above the open day range
#wait for one more up day
upbreak1 = 1
else:
upbreak1 = 0
#DOWN BREAK
if curClose<openDayRangeDict['low'] and curClose<curOpen:
if downbreak1==1 and curClose<openDayRangeDict['low'] and curClose<curOpen and curClose<lastClose and upbreak2 == 0:
#we've gotten a second up day above the range
downbreak2 = 1
entryClose = curClose
#so start keeping track of highest close, as well as close at EOD
#pdb.set_trace() #diagnostic
#we've broken above the open day range
#wait for one more up day
downbreak1 = 1
else:
downbreak1 = 0
previousDay = currentDay
lastClose = curClose
odrDF = DataFrame.from_dict(signalDict)
odrDF = odrDF.T
odrDF.to_csv("aapl_odr_1-2012.csv")
from pandas import *
from datetime import *
import pdb as pdb
import pylab
df = DataFrame.from_csv('aapl_odr_all.csv', sep=";")
model = ols(y=df['maxProfit'], x=df.ix[:,'rangeWidth':'type2'])
model2= ols(y=df['minProfit'], x=df.ix[:,'rangeWidth':'type2'])
model3 = ols(y=df['safeMinProfit'], x=df.ix[:,'rangeWidth':'type2'])
#df.ix[:,'maxProfit':'minProfit'].plot()
grouped = df.groupby('type2')
#long short max profit
lsMaxProfitDict = [0,0]
for name, group in grouped:
lsMaxProfitDict[name] = group['maxProfit'].values
pylab.boxplot(lsMaxProfitDict)
pylab.xticks([1, 2], ['short', 'long'])
#long short min profit
lsMaxProfitDict = [0,0]
for name, group in grouped:
lsMaxProfitDict[name] = group['minProfit'].values
pylab.boxplot(lsMaxProfitDict)
pylab.xticks([1, 2], ['short', 'long'])
#histograms of profit vs. rangeWidth, signalCount
#first group by signalCount (discrete)
signalGrouped = df.groupby('signalCountGroup')
signalCount_meanRets = {}
for name, group in signalGrouped:
signalCount_meanRets[name] = [group['maxProfit'].mean(),group['minProfit'].mean()]
signalGrouped = df.groupby('rangeWidthGroup')
rangeWidth_meanRets = {}
for name, group in signalGrouped:
rangeWidth_meanRets[name] = [group['maxProfit'].mean(),group['minProfit'].mean()]
rangeWidthRetsDF = DataFrame.from_dict(rangeWidth_meanRets)
rangeWidthRetsDF = rangeWidthRetsDF.T
rangeWidthRetsDF.columns = ['max profit', 'min profit']
rangeWidthRetsDF.plot(kind='bar', title="Profit vs. Range Width % Quartile")
signalCountRetsDF = DataFrame.from_dict(signalCount_meanRets)
signalCountRetsDF = signalCountRetsDF.T
signalCountRetsDF.columns = ['max profit', 'min profit']
signalCountRetsDF.plot(kind='bar',title="Profit vs. Signal Delay Quartile")
from pandas import *
from datetime import *
df = DataFrame.from_csv('aapl_1-2012.csv')
minutes = 5
aggPrices = {}
cur_open = -1
cur_high = -1
cur_low = 9999
cur_close = -1
last_sec = -1
#loop through trades, getting open, high, low, close for every 5 min interval
for i in range(1,len(df)):
row = df[(i-1):i]
symbol = row.index[0]
time = row['TIME'].values[0]
date = row['DATE'].values[0]
datetimestr = str(date)+" "+str(time)
print str(i)+" "+str(datetimestr)
to_min = int(time.split(':')[1])
to_sec = int(time.split(':')[2])
price = row['PRICE'].values[0]
date_object = datetime.strptime(datetimestr,'%Y%m%d %H:%M:%S')
#if cur open hasn't been set yet, set it
if cur_open==-1:
cur_open = price
if price>cur_high:
cur_high = price
if price<cur_low:
cur_low = price
#if current minute interval is up
if to_min%minutes==0 and to_sec==0 and not last_sec==0:
cur_close = price
#add row to dictionary
row_dict = {}
row_dict['open'] = cur_open
row_dict['high'] = cur_high
row_dict['low'] = cur_low
row_dict['close'] = cur_close
aggPrices[date_object] = row_dict
print "added "+str(row_dict)
cur_open = -1
cur_high = -1
cur_low = 9999
cur_close = -1
last_sec = to_sec
aggPricesDf = DataFrame.from_dict(aggPrices)
aggPricesDf = aggPricesDf.T
aggPricesDf.to_csv('aapl_1-2012_5min.csv')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment