コード例 #1
0
ファイル: q4fns.py プロジェクト: shrikannth/NSEQuant
def qntdaily(symbol):
    eqsdbdf = p4fns.readhdr_csv(NSEEQSDBDIR + symbol + CSV)
    eqsdb = p4fns.filterdf(p4fns.read_csv(NSEEQSDBDIR + symbol + CSV), PQS,
                           'SERIES', REGEQSERIES)[-252:]
    eqsdbdf = eqsdbdf + eqsdb
    inputdf = p4fns.rearrange(eqsdbdf, PQS, JSONCOL)
    p4fns.write_json(JSONDLYDIR + symbol + JSON, inputdf, EQCOLTYP)
コード例 #2
0
ファイル: q4fns.py プロジェクト: shrikannth/NSEQuant
def qntresult(symbol, resdf):
    techtitle = ['SYMBOL']
    techtable = []
    result = [
        dp.parse(row[PRES['TIMESTAMP']]).strftime('%Y-%m-%d') for row in resdf
        if row[PRES['SYMBOL']] == symbol
    ][-8:]
    srow = []
    srow.append(symbol)
    eqsdb = p4fns.filterdf(p4fns.read_csv(NSEEQSDBDIR + symbol + CSV), PQS,
                           'SERIES', REGEQSERIES)
    for res in result:
        backmean = p4fns.smean([
            float(row[PQS['CLOSE']])
            for row in p4fns.blockdf(eqsdb, PQS, res, 21, 'be')
        ])
        fronmean = p4fns.smean([
            float(row[PQS['CLOSE']])
            for row in p4fns.blockdf(eqsdb, PQS, res, 21, 'fe')
        ])
        effect = round(math.log(fronmean / backmean) * 100, 2)
        srow.append(effect)
        techtitle.append(res)
    techtable.append(srow)
    techtable = [techtitle] + techtable
    p4fns.write_json(JSONRESDIR + symbol + JSON, techtable, TECHCOLTYP)
コード例 #3
0
ファイル: q4fns.py プロジェクト: shrikannth/NSEQuant
def qntperf(symbol, name):
    perftable = []
    eqsdb = p4fns.filterdf(p4fns.read_csv(NSEEQSDBDIR + symbol + CSV), PQS,
                           'SERIES', REGEQSERIES)

    ## Price Values
    ## ============================================== ##
    price = [float(row[PQS['CLOSE']]) for row in eqsdb]
    perf1w = round(math.log(price[-1] / price[-5]) *
                   100, 2) if len(price) > 5 else '-'
    perf1m = round(math.log(price[-1] / price[-21]) *
                   100, 2) if len(price) > 21 else '-'
    perf3m = round(math.log(price[-1] / price[-63]) *
                   100, 2) if len(price) > 63 else '-'
    perf6m = round(math.log(price[-1] / price[-126]) *
                   100, 2) if len(price) > 126 else '-'
    perf1y = round(math.log(price[-1] / price[-252]) *
                   100, 2) if len(price) > 252 else '-'
    perf2y = round(math.log(price[-1] / price[-504]) *
                   100, 2) if len(price) > 504 else '-'
    perf4y = round(math.log(price[-1] / price[-1008]) *
                   100, 2) if len(price) > 1008 else '-'

    ## Volatility Values
    ## ============================================== ##
    gain = [float(row[PQS['GAIN']]) for row in eqsdb]
    stdd1w = round(p4fns.sstdd(gain[-5:]) *
                   math.sqrt(252), 2) if len(price) > 5 else '-'
    stdd1m = round(p4fns.sstdd(gain[-21:]) *
                   math.sqrt(252), 2) if len(price) > 21 else '-'
    stdd3m = round(p4fns.sstdd(gain[-63:]) *
                   math.sqrt(252), 2) if len(price) > 63 else '-'
    stdd6m = round(p4fns.sstdd(gain[-126:]) *
                   math.sqrt(252), 2) if len(price) > 126 else '-'
    stdd1y = round(p4fns.sstdd(gain[-252:]) *
                   math.sqrt(252), 2) if len(price) > 252 else '-'
    stdd2y = round(p4fns.sstdd(gain[-504:]) *
                   math.sqrt(252), 2) if len(price) > 504 else '-'
    stdd4y = round(p4fns.sstdd(gain[-1008:]) *
                   math.sqrt(252), 2) if len(price) > 1008 else '-'
    perftable.append([symbol,name,perf1w,perf1m,perf3m,perf6m,perf1y,perf2y,perf4y,\
                      stdd1w,stdd1m,stdd3m,stdd6m,stdd1y,stdd2y,stdd4y])
    p4fns.write_csv(NSETECHDIR + 'NSEPerf' + CSV, perftable, 'a')
コード例 #4
0
ファイル: q4fns.py プロジェクト: shrikannth/NSEQuant
def qntpair(symbol, period, deltaP, deltaN, rwindow, mwindow, pairlist):
    title = ['PAIR', 'NORM', 'DWSTAT']
    maxper = period + rwindow + mwindow - 1
    table = []

    datadb = p4fns.filterdf(p4fns.read_csv(NSEEQSDBDIR + symbol + CSV), PQS,
                            'SERIES', REGEQSERIES)[-maxper:]
    pclose = [math.log(float(row[PQS['CLOSE']])) for row in datadb]
    pvwap = [math.log(float(row[PQS['VWAP']])) for row in datadb]
    dsize = len(pclose)
    if (dsize >= rwindow + mwindow + 40):
        for pair in pairlist:
            reffdb = p4fns.read_csv(NSEEQSDBDIR + pair + CSV)[-maxper:]
            pvwapR = [math.log(float(row[PQS['VWAP']])) for row in reffdb]

            regr = p4fns.rolling_regress(pvwap[-dsize:], pvwapR[-dsize:],
                                         rwindow)
            rlen = len(regr)
            error = [
                round((a / b - 1) * 100, 2)
                for a, b in zip(pclose[-rlen:], regr[-rlen:])
            ]
            mu = p4fns.rolling_smean(error, mwindow)
            sg = p4fns.rolling_sstdd(error, mwindow)
            mlen = len(sg)
            error = error[-mlen:]
            normdist = int(
                p4fns.cumnormdist((error[-1] - mu[-1]) / sg[-1]) * 100)
            et_t1 = sum([
                math.pow((error[i] - error[i - 1]), 2) for i in range(1, mlen)
            ])
            et_sq = sum([math.pow(error[i], 2) for i in range(0, mlen)])
            dwstat = round(et_t1 / et_sq, 2)
            table.append([pair, normdist, dwstat])

        p4fns.write_csv(NSEPAIRDIR + symbol + CSV, [title] + table, 'w')
        p4fns.write_json(JSONPAIRDIR + symbol + JSON, [title] + table, [])
コード例 #5
0
ファイル: q4fns.py プロジェクト: shrikannth/NSEQuant
def qnttech(symbol, name):
    techtable = []
    eqsdb = p4fns.filterdf(p4fns.read_csv(NSEEQSDBDIR + symbol + CSV), PQS,
                           'SERIES', REGEQSERIES)

    ## Price Bands
    ## ============================================== ##
    price = [float(row[PQS['CLOSE']]) for row in eqsdb]
    vwap = [float(row[PQS['VWAP']]) for row in eqsdb]
    pb1m = int((price[-1] - min(price[-21:])) /
               (max(price[-21:]) - min(price[-21:])) *
               100) if len(price) > 21 else '-'
    pb3m = int((price[-1] - min(price[-63:])) /
               (max(price[-63:]) - min(price[-63:])) *
               100) if len(price) > 63 else '-'
    pb6m = int((price[-1] - min(price[-126:])) /
               (max(price[-126:]) - min(price[-126:])) *
               100) if len(price) > 126 else '-'
    pb1y = int((price[-1] - min(price[-252:])) /
               (max(price[-252:]) - min(price[-252:])) *
               100) if len(price) > 252 else '-'

    ## Bollinger Bands
    ## ============================================== ##
    dsize = len(price)
    period = [21, 63, 126, 252]
    bb = ['-'] * 4
    for i in range(0, 4):
        if (dsize > period[i] + 1):
            mu = p4fns.rolling_emean(vwap[-(period[i] + 1):], period[i])[-1]
            sg = p4fns.rolling_sstdd(vwap[-(period[i] + 1):], period[i])[-1]
            bb[i] = int(p4fns.cumnormdist((price[-1] - mu) / sg) * 100)

    techtable.append(
        [symbol, name, pb1m, pb3m, pb6m, pb1y, bb[0], bb[1], bb[2], bb[3]])
    p4fns.write_csv(NSETECHDIR + 'NSETech' + CSV, techtable, 'a')
コード例 #6
0
ファイル: algo_bb_sf.py プロジェクト: shrikannth/NSEQuant
years = int(sys.argv[6])
dur = int(sys.argv[7]) * 252

ixlist = ['NIFTY', 'BANKNIFTY']
cnx500 = [row[2] for row in p4fns.read_csv(NSEEQDIR + 'CNX500.csv')]
cnx100 = [row[2] for row in p4fns.read_csv(NSEEQDIR + 'CNX100.csv')]
cnx50 = [row[2] for row in p4fns.read_csv(NSEEQDIR + 'CNX50.csv')]
cnxlist = cnx500
days = 252 * years + mwindow

result = []
# ============================================================================================= ##
# Bollinger Band
# ============================================================================================= ##
if symbol1 in cnxlist:
    datadb = p4fns.filterdf(p4fns.read_csv(NSEEQSDBDIR + symbol1 + CSV), PQS,
                            'SERIES', REGEQSERIES)[-days:]
    price1 = [math.log(float(row[PQS['CLOSE']])) for row in datadb]
    vwap1 = [math.log(float(row[PQS['VWAP']])) for row in datadb]
    instrm1 = 'EQ'
else:
    datadb = p4fns.read_csv(NSEIXSDBDIR + symbol1 + CSV)[-days:]
    price1 = [math.log(float(row[PXS['CLOSE']])) for row in datadb]
    vwap1 = price1
    instrm1 = 'IX'
if symbol2 in cnxlist:
    datadb = p4fns.filterdf(p4fns.read_csv(NSEEQSDBDIR + symbol2 + CSV), PQS,
                            'SERIES', REGEQSERIES)[-days:]
    price2 = [math.log(float(row[PQS['CLOSE']])) for row in datadb]
    instrm2 = 'EQ'
else:
    datadb = p4fns.read_csv(NSEIXSDBDIR + symbol2 + CSV)[-days:]
コード例 #7
0
#       srow.append(eqsdb[i][PQS['OPEN']])
#       srow.append(eqsdb[i][PQS['HIGH']])
#       srow.append(eqsdb[i][PQS['LOW']])
#       srow.append(eqsdb[i][PQS['CLOSE']])
#       srow.append(round(float(eqsdb[i][PQS['TURNOVER']])/10000000, 2))
#       srow.append(avgiv[i] if avgiv[i] != 0 else volatility[i])
#       genldata.append(srow)
#
#    p4fns.write_csv(NSEDIR+'TECHNICAL/GENL/'+symbol+CSV, genldata, 'w')

# Bollinger Bands + AutoRegression + Nifty Regression
# =================================================== ##
#for symbol in cnxlist:
for symbol in ['HDFCBANK']:

    eqsdb = p4fns.filterdf(p4fns.read_csv(NSEEQSDBDIR + symbol + CSV), PQS,
                           'SERIES', REGEQSERIES)
    eqsize = len(eqsdb)
    dsize = 252
    #    # Bollinger Bands
    #    # --------------------------------------------------- #
    #    genldata       = p4fns.read_csv(NSEDIR+'TECHNICAL/GENL/'+symbol+CSV)
    #    title          = ['TIMESTAMP','CLOSE','MEAN','SIGMA']
    #    dsize          = min(252, len(genldata))
    #    vwap           = [float(row[PQS['VWAP']]) for row in eqsdb]
    #    emean          = p4fns.rolling_emean(vwap, 21)[-dsize:]
    #    eqdata         = eqsdb[-dsize:]
    #    genldata       = genldata[-dsize:]
    #    vwap           = vwap[-dsize:]
    #    table          = []
    #    sigma          = [round(float(genldata[i][6])*vwap[i]/(math.sqrt(252)*100),2) for i in range(dsize)]
    #
コード例 #8
0
ファイル: q4fns.py プロジェクト: shrikannth/NSEQuant
def qntgenl(symbol, name, sector, industry, mktcap, mcpercent):
    techtitle      = ['SYMBOL','PRICE','GAIN','NAME','SECTOR','INDUSTRY','MKT_CAP','MC_PERCENT',\
                      'VOLATILITY','MAX_VTY','MIN_VTY','VOLUME','MAX_VOL','MIN_VOL']
    techtable = []
    srow = []
    srow.append(symbol)
    eqsdb = p4fns.filterdf(p4fns.read_csv(NSEEQSDBDIR + symbol + CSV), PQS,
                           'SERIES', REGEQSERIES)

    ## Current Values
    ## ============================================== ##
    curprice = eqsdb[-1][PQS['CLOSE']]
    srow.append(curprice)
    change = round(float(eqsdb[-1][PQS['GAIN']]), 2)
    srow.append(change)
    srow.append(name)
    srow.append(sector)
    srow.append(industry)
    srow.append(mktcap)
    srow.append(mcpercent)

    ## Volatility
    ## ============================================== ##
    if path.isfile(NSEDVSDBDIR + symbol + CSV):
        dvsdb      = p4fns.filterdf(p4fns.filterdf(p4fns.filterdf(p4fns.read_csv(NSEDVSDBDIR+symbol+CSV),\
                                                   PDS, 'INSTRUMENT', ['OPTSTK']),\
                                                   PDS, 'TIMESTAMP', [today]),\
                                                   PDS, 'T2E', [str(x) for x in range(1,50)])
        ivlist = [float(row[PDS['IV']]) for row in dvsdb]
        wtlist = [float(row[PDS['VAL_INLAKH']]) for row in dvsdb]
        if sum(wtlist) >= 100:
            avgiv = round(p4fns.wmean(ivlist, wtlist), 2)
        else:
            avgiv = 0
    else:
        avgiv = 0
    eqdata = eqsdb[-756:]
    gain = [float(row[PQS['GAIN']]) for row in eqdata]
    cum_gain = p4fns.rolling_sum(gain, 21)
    rol_stdd = p4fns.rolling_sstdd(cum_gain, 21)
    if (avgiv == 0):
        stdd1m = round(p4fns.sstdd(cum_gain) * math.sqrt(12), 2)
        volatility = stdd1m
    else:
        volatility = avgiv
    max_stdd = max([volatility, round(max(rol_stdd) * math.sqrt(12), 2)])
    min_stdd = min([volatility, round(min(rol_stdd) * math.sqrt(12), 2)])
    srow.append(volatility)
    srow.append(max_stdd)
    srow.append(min_stdd)

    ## Volume
    ## ============================================== ##
    eqdata = eqsdb[-252:]
    turnover = [
        round(float(row[PQS['TURNOVER']]) / 10000000, 2) for row in eqdata
    ]
    volume = p4fns.rolling_emean(turnover, 3)
    max_vol = max(volume)
    min_vol = min(volume)
    srow.append(turnover[-1])
    srow.append(max_vol)
    srow.append(min_vol)

    ## Create JSON File
    ## ============================================== ##
    techtable.append(srow)
    p4fns.write_csv(NSEGENLDIR + symbol + CSV, [techtitle] + techtable, 'w')
    p4fns.write_json(JSONGENLDIR + symbol + JSON, [techtitle] + techtable,
                     TECHCOLTYP)
    genltable = []
    grow = []
    grow.append(symbol)
    grow.append(name)
    grow.append(sector)
    grow.append(industry)
    grow.append(curprice)
    grow.append(change)
    grow.append(mktcap)
    grow.append(turnover[-1])
    grow.append(volatility)
    genltable.append(grow)
    p4fns.write_csv(NSETECHDIR + 'NSEGenl' + CSV, genltable, 'a')
コード例 #9
0
ファイル: q4fns.py プロジェクト: shrikannth/NSEQuant
def qntevent(symbol, bonuspst, bonusfut, splitpst, splitfut, rightpst,
             rightfut, divdnpst, divdnfut, resltpst, resltfut):
    eventsum = []
    bpst = p4fns.filterdf(bonuspst, PBON, 'SYMBOL', [symbol])
    bfut = p4fns.filterdf(bonusfut, PBON, 'SYMBOL', [symbol])
    spst = p4fns.filterdf(splitpst, PSPL, 'SYMBOL', [symbol])
    sfut = p4fns.filterdf(splitfut, PSPL, 'SYMBOL', [symbol])
    gpst = p4fns.filterdf(rightpst, PRGT, 'SYMBOL', [symbol])
    gfut = p4fns.filterdf(rightfut, PRGT, 'SYMBOL', [symbol])
    dpst = p4fns.filterdf(divdnpst, PDIV, 'SYMBOL', [symbol])
    dfut = p4fns.filterdf(divdnfut, PDIV, 'SYMBOL', [symbol])
    rpst = p4fns.filterdf(resltpst, PRES, 'SYMBOL', [symbol])
    rfut = p4fns.filterdf(resltfut, PRES, 'SYMBOL', [symbol])
    for row in bpst:
        eventsum.append([
            dp.parse(row[PBON['EXDATE']]), 'Bonus Shares', row[PBON['RATIO']],
            'P'
        ])
    for row in bfut:
        eventsum.append([
            dp.parse(row[PBON['EXDATE']]), 'Bonus Shares', row[PBON['RATIO']],
            'F'
        ])
    for row in spst:
        eventsum.append([
            dp.parse(row[PSPL['EXDATE']]), 'Stock Split', row[PSPL['RATIO']],
            'P'
        ])
    for row in sfut:
        eventsum.append([
            dp.parse(row[PSPL['EXDATE']]), 'Stock Split', row[PSPL['RATIO']],
            'F'
        ])
    for row in gpst:
        eventsum.append([
            dp.parse(row[PRGT['EXDATE']]), 'Rights Issue', row[PRGT['RATIO']],
            'P'
        ])
    for row in gpst:
        eventsum.append([
            dp.parse(row[PRGT['EXDATE']]), 'Rights Issue', row[PRGT['RATIO']],
            'F'
        ])
    for row in dpst:
        eventsum.append([
            dp.parse(row[PDIV['EXDATE']]), 'Dividend Declaration',
            row[PDIV['DIVIDEND']] + ' Rs', 'P'
        ])
    for row in dfut:
        eventsum.append([
            dp.parse(row[PDIV['EXDATE']]), 'Dividend Declaration',
            row[PDIV['DIVIDEND']] + ' Rs', 'F'
        ])
    for row in rpst:
        eventsum.append(
            [dp.parse(row[PRES['TIMESTAMP']]), 'Result Declaration', '-', 'P'])
    for row in rfut:
        eventsum.append(
            [dp.parse(row[PRES['TIMESTAMP']]), 'Result Declaration', '-', 'F'])
    eventsum.sort(key=lambda x: x[0])
    eventsum = [[row[0].strftime('%Y-%m-%d')] + row[1:] for row in eventsum]
    fname = JSONEVNTDIR + symbol + JSON
    with open(fname, 'w') as fjson:
        json.dump(eventsum, fjson)
コード例 #10
0
ファイル: m4fns.py プロジェクト: shrikannth/NSEQuant
def pltcrosregres(symbol, period, deltaP, deltaN, rwindow, mwindow):
    maxper = period + rwindow + mwindow - 1
    datadb = p4fns.filterdf(p4fns.read_csv(NSEEQSDBDIR + symbol + CSV), PQS,
                            'SERIES', REGEQSERIES)[-maxper:]
    ptimestamp = [
        date2num(datetime.strptime(row[PQS['TIMESTAMP']], '%Y-%m-%d'))
        for row in datadb
    ]
    pclose = [math.log(float(row[PQS['CLOSE']])) for row in datadb]
    pvwap = [math.log(float(row[PQS['VWAP']])) for row in datadb]
    dsize = len(ptimestamp)
    if (dsize >= rwindow + mwindow + 40):
        #        pairlist   = [row[0] for row in p4fns.read_csv(NSEPAIRDIR+symbol+CSV)]+['NIFTY']
        pairlist = ['NIFTY']
        for pair in pairlist:
            if pair in ixlist:
                reffdb = p4fns.read_csv(NSEIXSDBDIR + pair + CSV)[-maxper:]
                pvwapR = [math.log(float(row[PXS['CLOSE']])) for row in reffdb]
            else:
                reffdb = p4fns.read_csv(NSEEQSDBDIR + pair + CSV)[-maxper:]
                pvwapR = [math.log(float(row[PQS['VWAP']])) for row in reffdb]

            regr = p4fns.rolling_regress(pvwap[-dsize:], pvwapR[-dsize:],
                                         rwindow)
            rlen = len(regr)
            error = [
                round((a / b - 1) * 100, 2)
                for a, b in zip(pclose[-rlen:], regr[-rlen:])
            ]
            stimestamp = ptimestamp[-rlen:]
            mu = p4fns.rolling_smean(error, mwindow)
            sg = p4fns.rolling_sstdd(error, mwindow)
            mlen = len(sg)
            error = error[-mlen:]
            stimestamp = stimestamp[-mlen:]
            mu = mu[-mlen:]
            sg = sg[-mlen:]
            upl = [mu[i] + sg[i] * deltaP for i in range(mlen)]
            lwl = [mu[i] - sg[i] * deltaN for i in range(mlen)]

            majorl = MonthLocator()
            xformat = DateFormatter('%b')

            fig = plt.figure(figsize=(6, 3))
            gs = gridspec.GridSpec(1, 1)

            ax1 = plt.subplot(gs[0])
            plt.title(symbol, loc='left', color=textc, weight='bold')
            plt.title('StatArb [' + symbol + ' vs ' + pair + ']',
                      loc='left',
                      color=textc,
                      weight='bold',
                      size='small')
            ax1.xaxis.set_major_locator(majorl)
            ax1.xaxis.set_major_formatter(xformat)
            ax1.yaxis.tick_right()
            ax1.grid(b=True, which='major', color=gridc, linestyle=':')
            ax1.patch.set_facecolor(backc)
            ax1.spines['bottom'].set_color(labelc)
            ax1.spines['top'].set_color(backc)
            ax1.spines['right'].set_color(labelc)
            ax1.spines['left'].set_color(backc)
            ax1.tick_params(axis='x', colors=labelc)
            ax1.tick_params(axis='y', colors=labelc)
            for label in (ax1.get_xticklabels() + ax1.get_yticklabels()):
                label.set_fontsize(6)
            ax1.plot(stimestamp, error, color='deepskyblue', linewidth=1.5)
            ax1.xaxis_date()
            ax1.autoscale_view()
            ax1.set_aspect('auto')
            plt.setp(ax1.get_xticklabels(),
                     horizontalalignment='center',
                     fontsize=8)

            ax2 = plt.subplot(gs[0])
            ax2.plot(stimestamp, mu, color='royalblue', linewidth=1.5)

            ax3 = plt.subplot(gs[0])
            ax3.plot(stimestamp, upl, color='yellowgreen')

            ax4 = plt.subplot(gs[0])
            ax4.plot(stimestamp, lwl, color='orangered')

            plt.figtext(0.94,
                        0.94,
                        '$\copyright$ piby4.com ' + today,
                        color=sitec,
                        size='xx-small',
                        ha='right')
            gs.tight_layout(fig)
            #            plt.savefig(IMGCRRDIR+symbol+'_'+pair+'.png', facecolor=(backc))
            plt.savefig('aaa.png', facecolor=(backc))
            plt.close(fig)
コード例 #11
0
ファイル: nse2dvx.py プロジェクト: shrikannth/NSEQuant
#!/usr/bin/env python
from p4defs import *
import p4fns
import math
import os.path as path

cnxlist = [row[PCAT['SYMBOL']] for row in p4fns.read_csv(NSEEQCatalog)]
ixclist = ['NIFTY', 'BANKNIFTY']
count = 0

for symbol in cnxlist + ixclist:
    count += 1
    print count
    if path.isfile(NSEDVSDBDIR + symbol + CSV):
        dvxdata = [['TIMESTAMP', 'AVGIV']]
        eqsdb = p4fns.filterdf(p4fns.read_csv(NSEEQSDBDIR + symbol + CSV), PQS,
                               'SERIES', REGEQSERIES)

        ## Volatility
        ## ============================================== ##
        dvsdb = p4fns.read_csv(NSEDVSDBDIR + symbol + CSV)

        for row in eqsdb:
            timestamp = row[PQS['TIMESTAMP']]
            dvtdb      = p4fns.filterdf(p4fns.filterdf(p4fns.filterdf(dvsdb,\
                                                                      PDS, 'INSTRUMENT', ['OPTSTK']),\
                                                                      PDS, 'TIMESTAMP', [timestamp]),\
                                                                      PDS, 'T2E', [str(x) for x in range(1,50)])
            ivlist = [float(row[PDS['IV']]) for row in dvtdb]
            wtlist = [float(row[PDS['VAL_INLAKH']]) for row in dvtdb]
            if sum(wtlist) >= 100:
                avgiv = round(p4fns.wmean(ivlist, wtlist), 2)
コード例 #12
0
ファイル: p8fns.py プロジェクト: shrikannth/NSEQuant
def updateledger(ledgerin, timestamp, operator):
    ledgerdf = ledgerin
    ledger = p4fns.filterdf(ledgerin[1:], PLS, 'INSTRUMENT',
                            ['OPTIDX', 'OPTSTK', 'FUTIVX', 'FUTSTK', 'FUTIDX'])
    ledger = p4fns.filterts(ledger, PLS, 'EXPIRY_DT', timestamp, operator)
    appenddf = []
    for row in ledger:
        instrument = row[PLS['INSTRUMENT']]
        symbol = row[PLS['SYMBOL']]
        optiontyp = row[PLS['OPTION_TYP']]
        expirydt = row[PLS['EXPIRY_DT']]
        strikepr = row[PLS['STRIKE_PR']]
        idf = p4fns.filterdf(ledger, PLS, 'INSTRUMENT', [instrument])
        idf = p4fns.filterdf(idf, PLS, 'SYMBOL', [symbol])
        idf = p4fns.filterdf(idf, PLS, 'OPTION_TYP', [optiontyp])
        idf = p4fns.filterdf(idf, PLS, 'EXPIRY_DT', [expirydt])
        idf = p4fns.filterdf(idf, PLS, 'STRIKE_PR', [strikepr])
        cumvol = 0
        for irow in idf:
            cumvol = cumvol + irow[PLS['VOLUME']]
        adf = p4fns.filterdf(appenddf, PLS, 'INSTRUMENT', [instrument])
        adf = p4fns.filterdf(adf, PLS, 'SYMBOL', [symbol])
        adf = p4fns.filterdf(adf, PLS, 'OPTION_TYP', [optiontyp])
        adf = p4fns.filterdf(adf, PLS, 'EXPIRY_DT', [expirydt])
        adf = p4fns.filterdf(adf, PLS, 'STRIKE_PR', [strikepr])
        appvol = 0
        for prow in adf:
            appvol = appvol + prow[PLS['VOLUME']]
        if (appvol + cumvol != 0):
            expvalue = float(
                p4fns.findvalue(expirydt, instrument, symbol, optiontyp,
                                expirydt, strikepr, 'CLOSE'))
            appenddf   = appendledger(appenddf, expirydt, symbol, instrument, optiontyp, expirydt,\
                          strikepr, (-appvol-cumvol), expvalue)
    ledgerdf = ledgerdf + appenddf
    return ledgerdf
コード例 #13
0
ファイル: nsedvdb.py プロジェクト: shrikannth/NSEQuant
## Calculate Time to Expiry
## ============================================================================================= ##
    srow[PDS['T2E']] = (dp.parse(trow[PDT['EXPIRY_DT']]) -
                        dp.parse(trow[PDT['TIMESTAMP']])).days

    ## Calculate Implied Volatility
    ## ============================================================================================= ##
    instrument = trow[PDT['INSTRUMENT']]
    strikepr = float(trow[PDT['STRIKE_PR']])
    optyp = trow[PDT['OPTION_TYP']]
    expirydt = trow[PDT['EXPIRY_DT']]
    opprice = float(trow[PDT['CLOSE']])
    days2exp = srow[PDS['T2E']]
    if (instrument == 'OPTSTK') and (symbol in eqclist):
        ulprice                    = float(p4fns.filterdf(p4fns.filterdf(p4fns.read_csv(NSEEQSDBDIR+symbol+CSV),\
                                     PQS, 'SERIES', REGEQSERIES), PQS, 'TIMESTAMP', [timestamp])[-1][PQS['CLOSE']])
        impvol = p4fns.ivcalc(optyp, ulprice, strikepr, opprice, days2exp)
    elif (instrument == 'OPTIDX') and (symbol in ixclist):
        ulprice                    = float(p4fns.filterdf(p4fns.read_csv(NSEIXSDBDIR+symbol+CSV),\
                                     PXS, 'TIMESTAMP', [timestamp])[-1][PXS['CLOSE']])
        impvol = p4fns.ivcalc(optyp, ulprice, strikepr, opprice, days2exp)
    else:
        impvol = 0
    srow[PDS['IV']] = impvol

    ## Calculate Option Distance
    ## ============================================================================================= ##
    if ((instrument == 'OPTSTK') and (symbol in eqclist)) or \
       ((instrument == 'OPTIDX') and (symbol in ixclist)):
        subdf = []
        for xrow in dvdf: