Skip to content

Commit

Permalink
Update asset liability page
Browse files Browse the repository at this point in the history
  • Loading branch information
SinaKhalili committed Oct 2, 2024
1 parent fff97d5 commit 6d665d9
Show file tree
Hide file tree
Showing 5 changed files with 77 additions and 107 deletions.
61 changes: 18 additions & 43 deletions src/page/asset_liability.py
Original file line number Diff line number Diff line change
@@ -1,22 +1,9 @@
import asyncio
from asyncio import AbstractEventLoop
import os
import time

from anchorpy import Wallet
from driftpy.account_subscription_config import AccountSubscriptionConfig
from driftpy.constants.perp_markets import mainnet_perp_market_configs
from driftpy.constants.spot_markets import mainnet_spot_market_configs
from driftpy.drift_client import DriftClient
from lib.page import RPC_STATE_KEY
from lib.page import VAT_STATE_KEY
from sections.asset_liab_matrix import get_matrix
from solana.rpc.async_api import AsyncClient
from lib.api import api
import pandas as pd
import streamlit as st

from utils import load_newest_files
from utils import load_vat


options = [0, 1, 2, 3]
labels = [
Expand All @@ -27,44 +14,32 @@
]


def asset_liab_matrix_page(): # (loop: AbstractEventLoop, vat: Vat, drift_client: DriftClient, env='mainnet'):
st.write("Loading vat...")
rpc = st.session_state[RPC_STATE_KEY]
loop: AbstractEventLoop = asyncio.new_event_loop()
drift_client = DriftClient(
AsyncClient(rpc),
Wallet.dummy(),
account_subscription=AccountSubscriptionConfig("cached"),
)
loop: AbstractEventLoop = asyncio.new_event_loop()
newest_snapshot = load_newest_files(os.getcwd() + "/pickles")
start_load_vat = time.time()
vat = loop.run_until_complete(load_vat(drift_client, newest_snapshot))
st.session_state["vat"] = vat
st.write(f"loaded vat in {time.time() - start_load_vat}")
st.session_state[VAT_STATE_KEY] = vat

def asset_liab_matrix_page():
mode = st.selectbox("Options", options, format_func=lambda x: labels[x])

if mode is None:
mode = 0

perp_market_inspect = st.selectbox(
perp_market_index = st.selectbox(
"Market index", [x.market_index for x in mainnet_perp_market_configs]
)

if perp_market_inspect is None:
perp_market_inspect = 0

res, df = get_matrix(loop, vat, drift_client, "mainnet", mode, perp_market_inspect)
if perp_market_index is None:
perp_market_index = 0

result = api(
"asset-liability",
"matrix",
"0" if mode is None else str(mode),
"0" if perp_market_index is None else str(perp_market_index),
as_json=True,
)
res = pd.DataFrame(result["res"])
df = pd.DataFrame(result["df"])

st.write(f"{df.shape[0]} users for scenario")

st.write(res)

tabs = st.tabs(["FULL"] + [x.symbol for x in mainnet_spot_market_configs])

tabs[0].dataframe(df)
tabs[0].dataframe(df, hide_index=True)

for idx, tab in enumerate(tabs[1:]):
important_cols = [x for x in df.columns if "spot_" + str(idx) in x]
Expand All @@ -73,4 +48,4 @@ def asset_liab_matrix_page(): # (loop: AbstractEventLoop, vat: Vat, drift_clien
by="spot_" + str(idx) + "_all", ascending=False
)
tab.write(f"{ len(toshow)} users with this asset to cover liabilities")
tab.dataframe(toshow)
tab.dataframe(toshow, hide_index=True)
22 changes: 22 additions & 0 deletions src/page/backend.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import pandas as pd
import requests
import streamlit as st


def backend_page():

if st.button("Load Pickle"):
result = requests.get("http://localhost:8000/pickle")
st.write(result.json())

st.write(
"""
## Backend API
- [swagger](http://localhost:8000/docs)
- [redoc](http://localhost:8000/redoc)
"""
)

st.title("Health")
45 changes: 25 additions & 20 deletions src/page/health.py
Original file line number Diff line number Diff line change
@@ -1,36 +1,41 @@
from lib.api import api
import plotly.express as px
import streamlit as st

from lib.health_utils import (
get_account_health_distribution,
get_largest_perp_positions,
get_largest_spot_borrows,
get_most_levered_perp_positions_above_1m,
get_most_levered_spot_borrows_above_1m,
)
from lib.page import VAT_STATE_KEY


def health_page():
vat = st.session_state[VAT_STATE_KEY]
health_distribution = get_account_health_distribution(vat)
health_distribution = api("health", "health_distribution")
largest_perp_positions = api("health", "largest_perp_positions")
most_levered_positions = api("health", "most_levered_perp_positions_above_1m")
largest_spot_borrows = api("health", "largest_spot_borrows")
most_levered_borrows = api("health", "most_levered_spot_borrows_above_1m")

fig = px.bar(
health_distribution,
x="Health Range",
y="Counts",
title="Health Distribution",
hover_data={"Notional Values": ":,"}, # Custom format for notional values
labels={"Counts": "Num Users", "Notional Values": "Notional Value ($)"},
)

fig.update_traces(
hovertemplate="<b>Health Range: %{x}</b><br>Count: %{y}<br>Notional Value: $%{customdata[0]:,.0f}<extra></extra>"
)

with st.container():
st.plotly_chart(health_distribution, use_container_width=True)
st.plotly_chart(fig, use_container_width=True)

perp_col, spot_col = st.columns([1, 1])

with perp_col:
largest_perp_positions = get_largest_perp_positions(vat)
st.markdown("### **Largest perp positions:**")
st.table(largest_perp_positions)
most_levered_positions = get_most_levered_perp_positions_above_1m(vat)
st.write(largest_perp_positions)
st.markdown("### **Most levered perp positions > $1m:**")
st.table(most_levered_positions)
st.write(most_levered_positions)

with spot_col:
largest_spot_borrows = get_largest_spot_borrows(vat)
st.markdown("### **Largest spot borrows:**")
st.table(largest_spot_borrows)
most_levered_borrows = get_most_levered_spot_borrows_above_1m(vat)
st.write(largest_spot_borrows)
st.markdown("### **Most levered spot borrows > $750k:**")
st.table(most_levered_borrows)
st.write(most_levered_borrows)
47 changes: 12 additions & 35 deletions src/page/price_shock.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,16 +8,14 @@
from driftpy.account_subscription_config import AccountSubscriptionConfig
from driftpy.drift_client import DriftClient
from driftpy.pickle.vat import Vat
from lib.api import api
from lib.page import RPC_STATE_KEY
from lib.page import VAT_STATE_KEY
from lib.user_metrics import get_usermap_df
import pandas as pd
from solana.rpc.async_api import AsyncClient
import streamlit as st

from utils import load_newest_files
from utils import load_vat


def price_shock_plot(price_scenario_users: list[Any], oracle_distort: float):
levs = price_scenario_users
Expand Down Expand Up @@ -62,22 +60,6 @@ def price_shock_plot(price_scenario_users: list[Any], oracle_distort: float):


def price_shock_page():

rpc = st.session_state[RPC_STATE_KEY]
loop: AbstractEventLoop = asyncio.new_event_loop()
drift_client = DriftClient(
AsyncClient(rpc),
Wallet.dummy(),
account_subscription=AccountSubscriptionConfig("cached"),
)
loop: AbstractEventLoop = asyncio.new_event_loop()
newest_snapshot = load_newest_files(os.getcwd() + "/pickles")
start_load_vat = time.time()
vat = loop.run_until_complete(load_vat(drift_client, newest_snapshot))
st.session_state["vat"] = vat
print(f"loaded vat in {time.time() - start_load_vat}")
st.session_state[VAT_STATE_KEY] = vat

cov_col, distort_col = st.columns(2)
cov = cov_col.selectbox(
"covariance:",
Expand All @@ -96,24 +78,19 @@ def price_shock_page():
help="step size of oracle distortions",
)

user_keys = list(vat.users.user_map.keys())
st.write(len(user_keys), "drift users")
start_time = time.time()

price_scenario_users, user_keys, distorted_oracles = loop.run_until_complete(
get_usermap_df(drift_client, vat.users, "oracles", oracle_distort, None, cov)
)

end_time = time.time()
time_to_run = end_time - start_time
st.write(
time_to_run,
"seconds to run",
1 + len(price_scenario_users[1]) + len(price_scenario_users[2]),
"price-shock scenarios",
result = api(
"price-shock",
"usermap",
params={
"asset_group": cov,
"oracle_distortion": oracle_distort,
"n_scenarios": 5,
},
as_json=True,
)
st.write(result)

price_shock_plot(price_scenario_users, oracle_distort)
# price_shock_plot(price_scenario_users, oracle_distort)

# oracle_down_max = pd.DataFrame(price_scenario_users[-1][-1], index=user_keys)
# with st.expander(
Expand Down
9 changes: 0 additions & 9 deletions src/page/test_backend.py

This file was deleted.

0 comments on commit 6d665d9

Please sign in to comment.