def Beta_graph(ticker, start_date, end_date):
    if start_date is not None and end_date is not None:
        stock = func.getPrices(collection_price, ticker, start_date, end_date,
                               "close")
        stock = stock.drop_duplicates()
        stock = stock['close'].pct_change()[1:].values
        SPY = func.getPrices(collection_price, "SPY", start_date, end_date,
                             "close")
        SPY = SPY.drop_duplicates()
        SPY = SPY['close'].pct_change()[1:].values
        try:
            p = func.linreg(stock, SPY)

            pts = go.Scatter(x=SPY, y=stock, mode='markers', showlegend=False)

            line = go.Scatter(x=SPY,
                              y=p[0] + p[1] * SPY,
                              showlegend=False,
                              mode='lines')

            data = [pts, line]
            layout = dict(xaxis=dict(zeroline=False, linewidth=1, mirror=True),
                          yaxis=dict(zeroline=False, linewidth=1, mirror=True),
                          title='Beta to SPY')

            fig = dict(data=data, layout=layout)
        except:
            fig = {}
    else:
        fig = {}
    return fig
def returnDist_graph(start_date, end_date, accountType):
    if start_date is not None and end_date is not None:
        if accountType == 'paperAccount':
            df = func.getAccoutValue(collection_account, "NetLiquidation")
        elif accountType == 'liveAccount':
            df = func.getAccoutValue(collection_account_real, "NetLiquidation")
        df = df[df['date'] >= start_date]

        spy = func.getPrices(collection_price, 'SPY', start_date, end_date,
                             'close')
        spy = spy.drop_duplicates()
        spy = spy['close'].pct_change()[1:]

        violin = dict(type='violin',
                      y=pd.to_numeric(df['value']).pct_change()[1:],
                      box=dict(visible=True),
                      meanline=dict(visible=True),
                      name='Portfolio')
        violin_spy = dict(type='violin',
                          y=spy,
                          box=dict(visible=True),
                          meanline=dict(visible=True),
                          name='SPY')

        data = [violin, violin_spy]
        layout = dict(xaxis=dict(zeroline=False, linewidth=1, mirror=True),
                      yaxis=dict(zeroline=False, linewidth=1, mirror=True),
                      title='Violin Plot of Return')

        fig = dict(data=data, layout=layout)
    else:
        fig = {}
    return fig
def update_correlation_map(start_date, end_date):
    df = func.getPassedPortfolio(collection_portfolio)

    result = pd.DataFrame()
    for index, row in df.iterrows():
        lst = {}
        symbol = row['Ticker']
        price = func.getPrices(collection_price, symbol, start_date, end_date,
                               'close')
        price = price.drop_duplicates()

        try:
            lst[symbol] = price['close'].tolist()
            result = pd.concat([result, pd.DataFrame(lst)], axis=1)
        except:
            result = pd.DataFrame(lst)

    cor = result.corr()
    arr = cor.values

    trace = go.Heatmap(z=arr, x=cor.columns, y=cor.columns)

    layout = dict(height=800, title='Stock Correlation')
    data = [trace]
    fig = dict(data=data, layout=layout)

    return fig
def QQ_graph(ticker, start_date, end_date):
    if start_date is not None and end_date is not None:
        X_lognorm = func.getPrices(collection_price, ticker, start_date,
                                   end_date, "close")
        X_lognorm = X_lognorm['close'].tolist()
        qq = stats.probplot(X_lognorm, dist='norm', sparams=(1))
        x = np.array([qq[0][0][0], qq[0][0][-1]])
        pts = go.Scatter(x=qq[0][0],
                         y=qq[0][1],
                         mode='markers',
                         showlegend=False)
        line = go.Scatter(x=x,
                          y=qq[1][1] + qq[1][0] * x,
                          showlegend=False,
                          mode='lines')

        data = [pts, line]
        layout = dict(xaxis=dict(zeroline=False, linewidth=1, mirror=True),
                      yaxis=dict(zeroline=False, linewidth=1, mirror=True),
                      title='QQ Plot')

        fig = dict(data=data, layout=layout)
    else:
        fig = {}
    return fig
def equity_graph(start_date, end_date, accountType):
    if start_date is not None and end_date is not None:
        if accountType == 'paperAccount':
            df = func.getAccoutValue(collection_account, "NetLiquidation")
        elif accountType == 'liveAccount':
            df = func.getAccoutValue(collection_account_real, "NetLiquidation")
        df = df[df['date'] >= start_date]

        df_2 = func.getPrices(collection_price, 'SPY', start_date, end_date,
                              'close')

        amount = float(df.iloc[0]['value'])
        price = float(df_2.iloc[0]['close'])
        shares = amount / price

        #extract the date only, and row back one day becoz account value is today, price is yesterday
        line = go.Scatter(x=df['date'].apply(
            lambda x: x.date() - timedelta(days=1)).tolist(),
                          y=df['value'],
                          showlegend=True,
                          mode='lines',
                          name='Equity Curve')

        line_spy = go.Scatter(x=df_2['date'],
                              y=df_2['close'] * shares,
                              showlegend=True,
                              mode='lines',
                              name='SPY')

        data = [line, line_spy]
        layout = dict(xaxis=dict(zeroline=False, linewidth=1, mirror=True),
                      yaxis=dict(
                          zeroline=False,
                          linewidth=1,
                          mirror=True,
                          type='log',
                      ),
                      title='Equity Curve')

        fig = dict(data=data, layout=layout)
    else:
        fig = {}
    return fig
def returnVSSPY_graph(start_date, end_date, accountType):
    if start_date is not None and end_date is not None:
        if accountType == 'paperAccount':
            df = func.getAccoutValue(collection_account, "NetLiquidation")
        elif accountType == 'liveAccount':
            df = func.getAccoutValue(collection_account_real, "NetLiquidation")
        df = df[df['date'] >= start_date]
        """
        start_date = df['date'].tolist()
        start_date.sort()
        start_date = start_date[-5].strftime('%Y-%m-%d %H:%M:%S.%f')
        start_date = start_date.split(" ")[0]
        #print(start_date)
        """

        spy = func.getPrices(collection_price, 'SPY', start_date, end_date,
                             'close')
        spy = spy.drop_duplicates()

        #extract the date only, and row back one day becoz account value is today, price is yesterday
        bar = go.Bar(
            x=df['date'].apply(
                lambda x: x.date() - timedelta(days=1)).tolist()[1:],
            y=pd.to_numeric(df['value']).pct_change()[1:],
            name='Equity',
        )

        bar_spy = go.Bar(x=spy['date'].tolist()[1:],
                         y=spy['close'].pct_change()[1:],
                         name='SPY')

        data = [bar, bar_spy]

        layout = dict(title='Return V.S SPY')

        fig = dict(data=data, layout=layout)

    else:
        fig = {}
    return fig