예제 #1
0
def logkey(n_clicks, value):
    if n_clicks != None:
        ek.set_app_key(value)
        ek.set_timeout(60 * 5)
        return 'Confirm: "{}"'.format(value)
예제 #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) + "%")]
import sys

sys.path.append("..")
from database import model_mongodb
import eikon as ek
import eikonLib as ekLib
import collections, math, copy
from datetime import datetime

ek.set_app_key('80a60244246c4c139ea016a0c9dde616194983de')
ek.set_timeout(120)


def retrieve_eikon_file(iFileName):
    with open('./Tickers/' + iFileName, 'r') as f:
        tickers = f.readlines()
    tickers = [x.strip() for x in tickers]
    return tickers


def FloatOrZero(value):
    try:
        if math.isnan(value):
            return 0.0
        else:
            return float(value)
    except:
        return 0.0


def update_ticker_function(iModel, iEikonFunction, aEikonTickers):