Exemplo n.º 1
0
def TableUpdate1(data_timestamp, data, children):
    #### ---- Populating table
    if (data_timestamp != None) & (children != None):
        if len(data) > 0:
            data = pd.DataFrame(data)
            data['Amount'] = data['Amount'].astype(float)
            data['Price'] = data['Price'].astype(float)
            data['Strike'] = data['Strike'].astype(float)
            data['ImpVol'] = data['ImpVol'].astype(float)
            data["Day"] = pd.to_datetime(data["Day"])
            data["Maturity"] = pd.to_datetime(data["Maturity"])
            data["Financial"] = data['Amount'] * data['Price']
            data["Financial"] = data["Financial"].round(2)

            spot = pd.DataFrame(json.loads(json.loads(str(children))['spot']))
            spot["TRADE_DATE"] = pd.to_datetime(spot["TRADE_DATE"])

            days = (data.apply(lambda row: businessDuration(
                startdate=row['Day'], enddate=row['Maturity'], unit='day'),
                               axis=1)).values

            # ImpyVola=[round(Func.ImpliedVola(spot[spot["Instrument"]!="BRSELICD=CBBR"].TRDPRC_1.values[0].astype(float),
            #             data["Strike"].values[j].astype(float),
            #             spot[spot["Instrument"]=="BRSELICD=CBBR"].TRDPRC_1.values[0].astype(float)/100,
            #             .70,
            #             data["Price"].values[j].astype(float),
            #             days[j],
            #             data["type"],a=-12.0, b=12.0, xtol=1e-8)*100,2) for j in range(len(data))]
            ImpyVola = data['ImpVol'].values
            GREEKS = Func.OpitionsPrice(
                spot[spot["Instrument"] != "BRSELICD=CBBR"].TRDPRC_1.values[0].
                astype(float), data["Strike"].values.astype(float),
                spot[spot["Instrument"] ==
                     "BRSELICD=CBBR"].TRDPRC_1.values[0].astype(float) / 100,
                np.array(ImpyVola) / 100, days)

            data[['Valor', 'Delta', 'Gamma', 'Vega', 'Theta', 'Rho',
                  'Etas']] = pd.DataFrame([[0 for i in range(7)]],
                                          columns=[
                                              'Valor', 'Delta', 'Gamma',
                                              'Vega', 'Theta', 'Rho', 'Etas'
                                          ],
                                          index=data.index)

            callGreek = GREEKS[list(GREEKS.columns[GREEKS.columns.str.contains(
                'C', regex=True)])][data.type.str.contains('C',
                                                           regex=True).values]
            putGreek = GREEKS[list(GREEKS.columns[GREEKS.columns.str.contains(
                'P', regex=True)])][data.type.str.contains('P',
                                                           regex=True).values]

            callGreek.columns = [
                'Valor', 'Delta', 'Gamma', 'Vega', 'Theta', 'Rho', 'Etas'
            ]
            putGreek.columns = [
                'Valor', 'Delta', 'Gamma', 'Vega', 'Theta', 'Rho', 'Etas'
            ]

            data.loc[
                list(data.type.str.contains('C', regex=True).values),
                ['Valor', 'Delta', 'Gamma', 'Vega', 'Theta', 'Rho', 'Etas'
                 ]] = round(callGreek, 3).values
            data.loc[
                list(data.type.str.contains('P', regex=True).values),
                ['Valor', 'Delta', 'Gamma', 'Vega', 'Theta', 'Rho', 'Etas'
                 ]] = round(putGreek, 3).values

            data["ImpVol"] = ImpyVola
            data["Delta"] = data.Delta.values
            data["Gamma"] = data.Gamma.values
            data["Vega"] = data.Vega.values
            data["Theta"] = data.Theta.values
            data["Rho"] = data.Rho.values
            return (data[[
                'Financial', 'Delta', 'Gamma', 'Vega', 'Theta', 'Rho'
            ]].to_dict('records'))

        else:
            return []

    else:
        return []
Exemplo n.º 2
0
def CalcNetChart(row_ids, data, children, value):
    if (row_ids != None) & (data != None):
        if (len(row_ids) > 0) & (len(data) > 0):

            ek.set_app_key(value)
            ek.set_timeout(60 * 5)

            data = pd.DataFrame(data)
            data = data[data.index.isin(row_ids)]
            data['Amount'] = data['Amount'].astype(float)
            data['Price'] = data['Price'].astype(float)
            data['Strike'] = data['Strike'].astype(float)
            data["Day"] = pd.to_datetime(data["Day"])
            data["Maturity"] = pd.to_datetime(data["Maturity"])

            data["Financial"] = data['Amount'] * data['Price']
            data["Financial"] = data["Financial"].round(2)

            spot = pd.DataFrame(json.loads(json.loads(str(children))['spot']))
            spot['TRDPRC_1'] = spot['TRDPRC_1'].astype(float)
            spot["TRADE_DATE"] = pd.to_datetime(spot["TRADE_DATE"])
            ssp = spot[
                spot["Instrument"] != "BRSELICD=CBBR"].TRDPRC_1.values[0]

            days = (data.apply(lambda row: businessDuration(
                startdate=row['Day'], enddate=row['Maturity'], unit='day'),
                               axis=1)).values
            days = list(set(days))

            vola, err = ek.get_data([
                spot[
                    spot["Instrument"] != "BRSELICD=CBBR"].Instrument.values[0]
            ], [
                'TR.Volatility5D', 'TR.Volatility10D', "TR.Volatility20D",
                "TR.Volatility30D", "TR.Volatility60D", "TR.Volatility90D"
            ])

            volaV = (sum((
                vola.T[0].values[1:] *
                (abs(np.array([5, 10, 20, 30, 60, 90]) - 15) + 1) /
                (sum(abs(np.array([5, 10, 20, 30, 60, 90]) - 15) + 1))))) / 100

            vola.columns = ['Instrument', 5, 10, 20, 30, 60, 90]
            vola[[5, 10, 20, 30, 60, 90]] = vola[[5, 10, 20, 30, 60, 90]] / 100
            days = list(np.unique(days))
            dists = []
            vollist = []
            for d in days:
                y_interp = scipy.interpolate.interp1d(
                    vola.columns[1:].astype(float),
                    vola.T[0].values[1:].astype(float))
                volaV = y_interp(d)
                Distrib = 1 - np.random.normal(0,
                                               (volaV / (252**0.5) * (d**0.5)),
                                               size=5000)
                Distrib = Distrib * ssp

                vollist.append(volaV)
                dists.append(Distrib)

            Price = dists[pd.DataFrame(dists).max(1).argmax()]
            Price.sort()
            net = []
            for k in range(len(data)):
                if data['Amount'].iloc[k] >= 0:
                    if "C" in data['type'].iloc[k]:
                        Rt = -data['Strike'].iloc[k] - data['Price'].iloc[
                            k] + Price
                        Rt[Rt <=
                           -data['Price'].iloc[k]] = -data['Price'].iloc[k]
                        Rt = Rt * abs(data['Amount'].iloc[k])
                        net.append(list(Rt))
                    else:
                        Rt = data['Strike'].iloc[k] - data['Price'].iloc[
                            k] - Price
                        Rt[Rt <=
                           -data['Price'].iloc[k]] = -data['Price'].iloc[k]
                        Rt = Rt * abs(data['Amount'].iloc[k])
                        net.append(list(Rt))

                else:
                    if "C" in data['type'].iloc[k]:
                        Rt = data['Strike'].iloc[k] + data['Price'].iloc[
                            k] - Price
                        Rt[Rt >= data['Price'].iloc[k]] = data['Price'].iloc[k]
                        Rt = Rt * abs(data['Amount'].iloc[k])
                        net.append(list(Rt))
                    else:
                        Rt = -data['Strike'].iloc[k] + data['Price'].iloc[
                            k] + Price
                        Rt[Rt >= data['Price'].iloc[k]] = data['Price'].iloc[k]
                        Rt = Rt * abs(data['Amount'].iloc[k])
                        net.append(list(Rt))

            pay = pd.DataFrame(net)
            pay.columns = Price
            pays = pay
            # print(pays.values)
            pay = pay.sum()

            tempTT = []
            for j in range(len(set(days))):
                tempT = []
                for s in range(len(data["Strike"])):
                    temp = Func.OpitionsPrice(
                        Price, data["Strike"].values.astype(float)[s],
                        spot[spot["Instrument"] == "BRSELICD=CBBR"].TRDPRC_1.
                        values[0].astype(float) / 100,
                        np.array(data['ImpVol'].values[j]) / 100, days[j])

                    if "C" in data["type"].values[s]:
                        temp = list(
                            (temp.ValorC.values - data['Price'].values[s]) *
                            data['Amount'].values[s])
                    else:
                        temp = list(
                            (temp.ValorP.values - data['Price'].values[s]) *
                            data['Amount'].values[s])

                    tempT.append(temp)

                tempTT.append(tempT)

            fig = go.FigureWidget(
                make_subplots(shared_xaxes=True,
                              specs=[[{
                                  "secondary_y": True
                              }]],
                              print_grid=False))
            trace3 = go.Scatter(name="0 line",
                                x=pay.index,
                                y=np.array([0 for i in Distrib]),
                                xaxis='x1',
                                yaxis='y2',
                                line=dict(color='black', width=2, dash='dash'))
            fig.add_trace(trace3, secondary_y=False)

            trace1 = go.Scatter(name="Payoff",
                                x=pay.index,
                                y=pay.values,
                                xaxis='x1',
                                yaxis='y2',
                                mode='lines',
                                fill='tozeroy')
            fig.add_trace(trace1, secondary_y=False)

            for i in range(len(tempTT)):
                trace5 = go.Scatter(name="Price - " + str(days[i]) + ' Days',
                                    x=pay.index,
                                    y=pd.DataFrame(tempTT[i]).sum().values,
                                    xaxis='x1',
                                    yaxis='y2',
                                    mode='lines')
                fig.add_trace(trace5, secondary_y=False)

            for lin, i in zip(pays.values, pays.index):
                trace4 = go.Scatter(name=data.Instrument.values[i],
                                    x=pay.index,
                                    y=lin,
                                    xaxis='x1',
                                    yaxis='y2',
                                    line=dict(width=2, dash='dash'))
                fig.add_trace(trace4, secondary_y=False)

            for i, j in zip(days, dists):
                trace2 = ff.create_distplot([j],
                                            [str(i) + " Days - Probabilidade"],
                                            bin_size=.5,
                                            curve_type='normal',
                                            show_hist=False,
                                            show_rug=False)
                fig.add_trace(trace2['data'][0], secondary_y=True)

            prob = round(sum(pay.values > 0) / len(Distrib) * 100, 2)
            return [fig, html.H6("Profit probability: " + str(prob) + "%")]

        else:
            fig = go.FigureWidget(
                make_subplots(shared_xaxes=True,
                              specs=[[{
                                  "secondary_y": True
                              }]],
                              print_grid=False))

            trace3 = go.Scatter(name="0 line",
                                x=[0],
                                y=[0],
                                xaxis='x1',
                                yaxis='y2',
                                line=dict(color='black', width=2, dash='dash'))

            fig.add_trace(trace3, secondary_y=False)

            return [fig, html.H6(str(0) + "%")]

    else:

        fig = go.FigureWidget(
            make_subplots(shared_xaxes=True,
                          specs=[[{
                              "secondary_y": True
                          }]],
                          print_grid=False))

        trace3 = go.Scatter(name="0 line",
                            x=[0],
                            y=[0],
                            xaxis='x1',
                            yaxis='y2',
                            line=dict(color='black', width=2, dash='dash'))

        fig.add_trace(trace3, secondary_y=False)

        return [fig, html.H6(str(0) + "%")]
days=(data.apply(lambda row: businessDuration(startdate=row['TRADE_DATE'],enddate=row['EXPIR_DATE'],unit='day'), axis=1)).values

j=0
ImpyVola=[round(Func.ImpliedVola(spot[spot["Instrument"]!="BRSELICD=CBBR"].TRDPRC_1.values[0].astype(float),
            data["STRIKE_PRC"].values[j].astype(float),
            spot[spot["Instrument"]=="BRSELICD=CBBR"].TRDPRC_1.values[0].astype(float)/100,
            .70,
            data["TRDPRC_1"].values[j].astype(float),
            days[j],
            # (((data["EXPIR_DATE"].values[j])-(data["TRADE_DATE"].values[j])).astype('timedelta64[D]').astype(int)),
            data["PUTCALLIND"],a=-12.0, b=12.0, xtol=1e-8)*100,2) for j in range(len(data))]


GREEKS=Func.OpitionsPrice(spot[spot["Instrument"]!="BRSELICD=CBBR"].TRDPRC_1.values[0].astype(float),
                            data["STRIKE_PRC"].values.astype(float),
                            spot[spot["Instrument"]=="BRSELICD=CBBR"].TRDPRC_1.values[0].astype(float)/100,
                            np.array(ImpyVola)/100,
                            days)


data[['Valor','Delta','Gamma','Vega','Theta','Rho','Etas']]=pd.DataFrame([[0 for i in range(7)]], columns=['Valor','Delta','Gamma','Vega','Theta','Rho','Etas'],index=data.index)

callGreek=GREEKS[list(GREEKS.columns[GREEKS.columns.str.contains('C', regex=True)])][data.PUTCALLIND.str.contains('C', regex=True).values]
putGreek=GREEKS[list(GREEKS.columns[GREEKS.columns.str.contains('P', regex=True)])][data.PUTCALLIND.str.contains('P', regex=True).values]

callGreek.columns=['Valor','Delta','Gamma','Vega','Theta','Rho','Etas']
putGreek.columns=['Valor','Delta','Gamma','Vega','Theta','Rho','Etas']

data.loc[list(data.PUTCALLIND.str.contains('C', regex=True).values),['Valor','Delta','Gamma','Vega','Theta','Rho','Etas']]=callGreek.values
data.loc[list(data.PUTCALLIND.str.contains('P', regex=True).values),['Valor','Delta','Gamma','Vega','Theta','Rho','Etas']]=putGreek.values