def calc_stocks_feat(dreturn, dstocks, dquote, assets, industry):
    # join dfs
    dfull = dreturn.join(dstocks.set_index('Ticker'), on='Ticker', how='inner')
    dfull['Price'] = dquote[str(dt.date.today().year)]

    # distribution
    dfull['Geo'] = dfull[assets].idxmax(axis=1)
    dfull['Domain'] = dfull[industry].idxmax(axis=1)
    dfull['Asset'] = dfull[assets].idxmax(axis=1).apply(lambda x: x if (
        x == 'Bonds' or x == 'Commod' or x == 'Cash') else 'Equity')

    # risk and return
    dfull['Risk'] = dfull['Volatility'].apply(lambda x: d.int2pct(x / 100))
    dfull['Tax'] = dfull['TER'].apply(lambda x: d.int2pct(x / 100))
    dfull['Return'] = dfull['Predicted'].apply(d.int2pct)
    dfull['YTD'] = dfull[str(dt.date.today().year)].apply(d.int2pct)

    # score
    weights = [0.05, 0.5, 0.35, 0.1]
    dfull['Score'] = (10 + (30 - dfull['Price']) / 27) * weights[0] + dfull[
        'Predicted'] / 0.3 * 10 * weights[1] + (
            10 + (7 - dfull['Volatility']) / 2.3) * weights[2] + (
                10 - dfull['TER'] / 0.2) * weights[3]

    return dfull
def calc_flows(df):
    # read values
    open_val = df.head(1)['Valor'].item()
    final_val = df.tail(1)['Valor'].item()
    open_date = df.head(1)['Data'].item()
    final_date = df.tail(1)['Data'].item()
    status = df.tail(1)['Status'].item()
    itype = df.tail(1)['Tipo'].item()

    # compute metrics
    active = False if status == 'Fechado' else True
    gain = final_val - open_val
    duration = (final_date - open_date).days
    total_yield = gain / open_val
    daily_yield = (1 + total_yield)**(1 / duration) - 1 if duration > 0 else 0
    monthly_yield = (1 + daily_yield)**30.5 - 1
    annual_yield = (1 + daily_yield)**365 - 1
    year_profit = final_val * annual_yield

    # structure dataframe
    dr = pd.DataFrame({
        'Valor inicial': [open_val],
        'Ganho': [gain],
        'Meses': [duration / 30.5],
        'Rendimento': [d.int2pct(total_yield)],
        'Rendimento mensal': [d.int2pct(monthly_yield)],
        'Rendimento anual': [d.int2pct(annual_yield)],
        'Ganho em 1 ano': [year_profit],
        'Ativo': [active],
        'Tipo': [itype]
    })
    return dr
def calc_port_perfo(dport):
    dport['Return'] = dport['Predicted'] * dport['Value'] / dport['Value'].sum(
    )
    dport['Risk'] = dport['Volatility'] * dport['Value'] / dport['Value'].sum()
    dcurrent = pd.DataFrame({
        'Value': [dport['Value'].sum()],
        'Profit': [dport['Profit'].sum()],
        'Return': [d.int2pct(dport['Return'].sum())],
        'Risk': [d.int2pct(dport['Risk'].sum())],
    })
    dcurrent['Yield'] = (dcurrent['Profit'] / dcurrent['Value']).apply(
        d.int2pct)
    return dcurrent
def calc_flows_overview(df):
    gain = df['Ganho'].sum()
    value = df[df['Ativo']]['Valor inicial'].sum() + df[
        df['Ativo']]['Ganho'].sum()
    total_yield = gain / df['Valor inicial'].sum()
    year_profit = df[df['Ativo']]['Ganho em 1 ano'].sum()
    annual_yield = year_profit / value
    doverview = pd.DataFrame([[
        value, gain,
        d.int2pct(total_yield), year_profit,
        d.int2pct(annual_yield)
    ]],
                             columns=[
                                 'Valor base', 'Ganho atual',
                                 'Rendimento atual', 'Ganho em 1 ano',
                                 'Rendimento anual'
                             ])
    return doverview
def calc_bonds_portfolio(dflow, assets):
    profit = dflow['Ganho'].sum()
    value = dflow[dflow['Ativo']]['Valor inicial'].sum() + dflow[
        dflow['Ativo']]['Ganho'].sum()
    yields = profit / dflow['Valor inicial'].sum()
    di = pd.DataFrame([[
        'NU', value, 1, value, 0, 0.03, profit, yields,
        d.int2pct(yields), 0, 0, 0, 0, 100, 0, 0
    ]],
                      columns=[
                          'Ticker', 'Buy', 'Shares', 'Value', 'Volatility',
                          'Predicted', 'Profit', 'Yield', 'Yield %'
                      ] + assets)
    return di