Notebook
In [30]:
import pandas as pd
import numpy as np
import talib
import matplotlib.pyplot as plt
In [117]:
dfPrices = get_pricing(symbols('AAPL'), start_date='2015-06-03', end_date='2016-02-03')
#dfPrices
plt.plot(dfPrices.index, dfPrices.price)
Out[117]:
[<matplotlib.lines.Line2D at 0x7f49a376bb10>]
In [91]:
dfReturns = dfPrices.price - dfPrices.price.shift(1)
dfReturnsPrc = dfReturns / dfPrices.price.shift(1)*100
dfReturnsPrc.describe()
Out[91]:
count    21.000000
mean     -0.390036
std       2.658573
min      -6.571314
25%      -1.971363
50%      -0.413057
75%       1.451335
max       5.327656
Name: price, dtype: float64
In [118]:
def createZigZagPoints(dfSeries, minSegSize=2, sizeInDevs=1):
    minRetrace = minSegSize
    
    curVal = dfSeries[0]
    curPos = dfSeries.index[0]
    curDir = 1
    #dfRes = pd.DataFrame(np.zeros((len(dfSeries.index), 2)), index=dfSeries.index, columns=["Dir", "Value"])
    dfRes = pd.DataFrame(index=dfSeries.index, columns=["Dir", "Value"])
    #print(dfRes)
    #print(len(dfSeries.index))
    for ln in dfSeries.index:
        if((dfSeries[ln] - curVal)*curDir >= 0):
            curVal = dfSeries[ln]
            curPos = ln
            #print(str(ln) + ": moving curVal further, to " + str(curVal))
        else:      
            retracePrc = abs((dfSeries[ln]-curVal)/curVal*100)
            #print(str(ln) + ": estimating retracePrc, it's " + str(retracePrc))
            if(retracePrc >= minRetrace):
                #print(str(ln) + ": registering key point, its pos is " + str(curPos) + ", value = " + str(curVal) + ", dir=" +str(curDir))
                dfRes.ix[curPos, 'Value'] = curVal
                dfRes.ix[curPos, 'Dir'] = curDir
                curVal = dfSeries[ln]
                curPos = ln
                curDir = -1*curDir
                #print(str(ln) + ": setting new cur vals, pos is " + str(curPos) + ", curVal = " + str(curVal) + ", dir=" +str(curDir))
        #print(ln, curVal, curDir)
    dfRes[['Value']] = dfRes[['Value']].astype(float)
    dfRes = dfRes.interpolate(method='linear')
    return(dfRes)

dfRes = createZigZagPoints(dfPrices.price)
#print(dfRes)
plt.plot(dfPrices['price'])
plt.plot(dfRes['Value'])
Out[118]:
[<matplotlib.lines.Line2D at 0x7f49a38dd110>]
In [ ]: