Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
The code in https://github.com/virtualizedfrog/blog_code/blob/master/PSAR/psar.py was modified to match value of PSAR given in tradingview
#######################################################################
# Author : Arun B
#
# Purpose : Calculate Parabolic SAR
############################################################################
def psar(barsdata, iaf = 0.02, inc=0.02,maxaf = 0.2):
length = len(barsdata)
dates = list(barsdata['date'])
high = list(barsdata['high'])
low = list(barsdata['low'])
close = list(barsdata['close'])
psar = close[0:len(close)]
cpsar = close[0:len(close)]
bb = close[0:len(close)]
EP =close[0:len(close)]
AF=close[0:len(close)]
rev =close[0:len(close)]
#psarbull = [None] * length
#psarbear = [None] * length
bull = True
af = iaf
ep = low[0]
hp = high[0]
lp = low[0]
for i in range(2,length):
if bull:
psar[i] = psar[i - 1] + af * (hp - psar[i - 1])
else:
psar[i] = psar[i - 1] + af * (lp - psar[i - 1])
cpsar[i]=psar[i]
reverse = False
if bull:
if low[i] < psar[i]:
bull = False
reverse = True
psar[i] = max(hp,high[i])
lp = low[i]
EP[i]=lp
af = iaf
AF[i]=af
else:
if high[i] > psar[i]:
bull = True
reverse = True
psar[i] = min(lp,low[i])
hp = high[i]
EP[i]=hp
af = iaf
AF[i]=af
if not reverse:
if bull:
if high[i] > hp:
hp = high[i]
af = min(af + inc, maxaf)
EP[i] =hp
AF[i]=af
#psar[i] = psar[i - 1] + af * (hp - psar[i - 1])
else:
AF[i]=AF[i-1]
EP[i]=EP[i-1]
if low[i - 1] < psar[i]:
psar[i] = low[i - 1]
if low[i - 2] < psar[i]:
psar[i] = low[i - 2]
else:
if low[i] < lp:
lp = low[i]
af = min(af + inc, maxaf)
EP[i]=lp
AF[i]=af
#psar[i] = psar[i - 1] + af * (lp - psar[i - 1])
else:
AF[i]=AF[i-1]
EP[i]=EP[i-1]
if high[i - 1] > psar[i]:
psar[i] = high[i - 1]
if high[i - 2] > psar[i]:
psar[i] = high[i - 2]
bb[i]=bull
rev[i]=reverse
return {"dates":dates, "high":high, "low":low, "close":close, "psar":psar,"bb":bb,"cpsar":cpsar,"ep":EP,"af":AF,"rev":rev}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment