Portfolio Analyzer#

The Portfolio Analysis App demonstrates the powerful Tabulator table that ships with Panel.

This app is heavily inspired by the Dash AG Grid App here. Having both enables you to compare pros and cons of Panel w. Tabulator versus Dash w. AG Grid.

import pandas as pd
import panel as pn
import plotly.express as px
import plotly.graph_objects as go

pn.extension('plotly', 'tabulator')
ACCENT = "#BB2649"
RED = "#D94467"
GREEN = "#5AD534"

LINK_SVG = (
    '<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" '
    'class="bi bi-arrow-up-right-square" viewBox="0 0 16 16"><path fill-rule="evenodd" '
    'd="M15 2a1 1 0 0 0-1-1H2a1 1 0 0 0-1 1v12a1 1 0 0 0 1 1h12a1 1 0 0 0 1-1V2zM0 2a2 2 0 0 1 2-2h12a2 2 0 0 1 2 2v12a2 2 0 0 1-2 2H2a2 2 0 0 1-2-2V2z'
    'm5.854 8.803a.5.5 0 1 1-.708-.707L9.243 6H6.475a.5.5 0 1 1 0-1h3.975a.5.5 0 0 1 .5.5v3.975a.5.5 0 1 1-1 0V6.707l-4.096 4.096z"/></svg>'
)

CSV_URL = "https://datasets.holoviz.org/equities/v1/equities.csv"

Lets define our list of equities

EQUITIES = {
    "AAPL": "Apple",
    "MSFT": "Microsoft",
    "AMZN": "Amazon",
    "GOOGL": "Alphabet",
    "TSLA": "Tesla",
    "BRK-B": "Berkshire Hathaway",
    "UNH": "United Health Group",
    "JNJ": "Johnson & Johnson",
}
EQUITY_LIST = tuple(EQUITIES.keys())

Extract the data#

The historical prices are a static CSV snapshot. Loading it through pn.cache means it is downloaded once and shared between sessions.

@pn.cache
def load_historical_data():
    """Loads the daily price history of all equities"""
    return pd.read_csv(CSV_URL, index_col=[0, 1], parse_dates=['Date'])

historical_data = load_historical_data()
historical_data.head(3).round(2)
Adj Close Close High Low Open Volume
Equity Date
AAPL 2021-01-28 05:00:00 135.46 137.09 141.99 136.70 139.52 142621100.0
2021-01-29 05:00:00 130.39 131.96 136.74 130.21 135.83 177523800.0
2021-02-01 05:00:00 132.55 134.14 135.38 130.93 133.75 106239800.0

Transform the data#

Let us calculate the summary_data to show in the Table.

def last_close(data, ticker):
    """Returns the last close price for the given ticker"""
    return data.loc[ticker]["Close"].iloc[-1]

last_close(historical_data, "AAPL")
145.92999267578125
summary_data = pd.DataFrame({
    "ticker": EQUITY_LIST,
    "company": EQUITIES.values(),
    "info": [
        f"""<a href='https://finance.yahoo.com/quote/{ticker}' target='_blank'>
        <div title='Open in Yahoo'>{LINK_SVG}</div></a>"""
        for ticker in EQUITIES
    ],
    "quantity": [75, 40, 100, 50, 40, 60, 20, 40],
    "price": [last_close(historical_data, ticker) for ticker in EQUITIES],
    "action": ["buy", "sell", "hold", "hold", "hold", "hold", "hold", "hold"],
    "notes": [""] * len(EQUITIES),
})
summary_data.insert(5, "value", summary_data["quantity"] * summary_data["price"])
summary_data.head(2)
ticker company info quantity price value action notes
0 AAPL Apple <a href='https://finance.yahoo.com/quote/AAPL' target='_blank'>\n        <div title='Open in Yahoo'><svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-arrow-up-right-square" viewBox="0 0 16 16"><path fill-rule="evenodd" d="M15 2a1 1 0 0 0-1-1H2a1 1 0 0 0-1 1v12a1 1 0 0 0 1 1h12a1 1 0 0 0 1-1V2zM0 2a2 2 0 0 1 2-2h12a2 2 0 0 1 2 2v12a2 2 0 0 1-2 2H2a2 2 0 0 1-2-2V2zm5.854 8.803a.5.5 0 1 1-.708-.707L9.243 6H6.475a.5.5 0 1 1 0-1h3.975a.5.5 0 0 1 .5.5v3.975a.5.5 0 1 1-1 0V6.707l-4.096 4.096z"/></svg></div></a> 75 145.929993 10944.749451 buy
1 MSFT Microsoft <a href='https://finance.yahoo.com/quote/MSFT' target='_blank'>\n        <div title='Open in Yahoo'><svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-arrow-up-right-square" viewBox="0 0 16 16"><path fill-rule="evenodd" d="M15 2a1 1 0 0 0-1-1H2a1 1 0 0 0-1 1v12a1 1 0 0 0 1 1h12a1 1 0 0 0 1-1V2zM0 2a2 2 0 0 1 2-2h12a2 2 0 0 1 2 2v12a2 2 0 0 1-2 2H2a2 2 0 0 1-2-2V2zm5.854 8.803a.5.5 0 1 1-.708-.707L9.243 6H6.475a.5.5 0 1 1 0-1h3.975a.5.5 0 0 1 .5.5v3.975a.5.5 0 1 1-1 0V6.707l-4.096 4.096z"/></svg></div></a> 40 248.160004 9926.400146 sell

Define the Summary Table#

We define the configuration of the Tabulator below.

titles = {
    "ticker": "Stock Ticker",
    "company": "Company",
    "info": "Info",
    "quantity": "Shares",
    "price": "Last Close Price",
    "value": "Market Value",
    "action": "Action",
    "notes": "Notes",
}
frozen_columns = ["ticker", "company"]
editors = {
    "ticker": None,
    "company": None,
    "quantity": {"type": "number", "min": 0, "step": 1},
    "price": None,
    "value": None,
    "action": {
        "type": "list",
        "values": {"buy": "buy", "sell": "sell", "hold": "hold"},
    },
    "notes": {
        "type": "textarea",
        "elementAttributes": {"maxlength": "100"},
        "selectContents": True,
        "verticalNavigation": "editor",
        "shiftEnterSubmit": True,
    },
    "info": None,
}

widths = {"notes": 400}
formatters = {
    "price": {"type": "money", "decimal": ".", "thousand": ",", "precision": 2},
    "value": {"type": "money", "decimal": ".", "thousand": ",", "precision": 0},
    "info": {"type": "html", "field": "html"},
}

text_align = {
    "price": "right",
    "value": "right",
    "action": "center",
    "info": "center",
}
base_configuration = {
    "clipboard": "copy"
}

Here we define the summary_table widget.

summary_table = pn.ui.Tabulator(
    summary_data,
    editors=editors,
    formatters=formatters,
    frozen_columns=frozen_columns,
    layout="fit_data_table",
    selectable=1,
    show_index=False,
    text_align=text_align,
    titles=titles,
    widths=widths,
    configuration=base_configuration,
)
summary_table

Now lets style the table using the Pandas styler api. The editable column gets a translucent highlight so it reads in both light and dark mode.

ACTION_COLORS = {'buy': GREEN, 'sell': RED}

def style_of_action_cell(value):
    """Returns the css to apply to an 'action' cell depending on the val"""
    return f'color: {ACTION_COLORS[value]}' if value in ACTION_COLORS else ''

summary_table.style.map(style_of_action_cell, subset=["action"]).set_properties(
    **{"background-color": "rgba(127, 127, 127, 0.15)"}, subset=["quantity"]
)
  ticker company info quantity price value action notes
0 AAPL Apple
75 145.929993 10944.749451 buy
1 MSFT Microsoft
40 248.160004 9926.400146 sell
2 AMZN Amazon
100 102.239998 10223.999786 hold
3 GOOGL Alphabet
50 99.370003 4968.500137 hold
4 TSLA Tesla
40 177.899994 7115.999756 hold
5 BRK-B Berkshire Hathaway
60 309.170013 18550.200806 hold
6 UNH United Health Group
20 486.049988 9720.999756 hold
7 JNJ Johnson & Johnson
40 168.229996 6729.199829 hold

For later we also need a function to handle when a user edits a cell in the table. Edits and patch update the table’s value in place without emitting an event, so a small reactive counter records each change for the plots to depend on.

edits = pn.rx(0)

def handle_cell_edit(event):
    """Updates the `value` cell when the `quantity` cell is updated"""
    if event.column == "quantity":
        price = summary_table.value.loc[event.row, "price"]
        summary_table.patch({"value": [(event.row, event.value * price)]})
        edits.rx.value += 1

summary_table.on_edit(handle_cell_edit)

Define the plots#

Both plot functions are pure: they take the table data and return a figure, leaving colours to the page theme.

def candlestick(data, selection):
    """Returns a candlestick plot"""
    index = selection[0] if selection else 0
    ticker = data.loc[index, "ticker"]
    company = data.loc[index, "company"]

    dff_ticker_hist = historical_data.loc[ticker].reset_index()

    fig = go.Figure(
        go.Candlestick(
            x=dff_ticker_hist["Date"],
            open=dff_ticker_hist["Open"],
            high=dff_ticker_hist["High"],
            low=dff_ticker_hist["Low"],
            close=dff_ticker_hist["Close"],
        )
    )
    fig.update_layout(title_text=f"{ticker} {company} Daily Price", autosize=True)
    return fig

candlestick(summary_data, [])
def portfolio_distribution(data, edits=0):
    """Returns the distribution of the portfolio"""
    fig = px.pie(
        data,
        values="value",
        names="ticker",
        hole=0.3,
        title=f"Portfolio Total $ {data['value'].sum():,.0f}",
    )
    fig.layout.autosize = True
    return fig

portfolio_distribution(summary_data)

Bind the widgets and functions#

The candlestick plot depends on the selection in summary_table, and the portfolio_distribution on the table data and the edit counter.

candlestick_pane = pn.ui.Plotly(
    pn.bind(candlestick, summary_table.param.value, summary_table.param.selection),
    sizing_mode="stretch_both",
)
distribution_pane = pn.ui.Plotly(
    pn.bind(portfolio_distribution, summary_table.param.value, edits),
    sizing_mode="stretch_both",
)

Layout the app#

A responsive Grid places the plots side by side on wide screens and stacks them on narrow ones, with the table spanning the full width below.

grid = pn.ui.Grid(
    pn.ui.Grid(candlestick_pane, size={"xs": 12, "md": 8}, height=450),
    pn.ui.Grid(distribution_pane, size={"xs": 12, "md": 4}, height=450),
    pn.ui.Grid(summary_table, size={"xs": 12}),
    container=True, spacing=2,
)

page = pn.ui.Page(
    title="Portfolio Analysis",
    main=[grid],
    theme_config={"palette": {"primary": {"main": ACCENT}}},
)

page

Served App#

if pn.state.served:
    page.servable()