Skip to content

Instantly share code, notes, and snippets.

@xescuder
Last active March 15, 2024 20:32
Show Gist options
  • Save xescuder/59824f0a6bd8ca29f6eb42ef4cc6a718 to your computer and use it in GitHub Desktop.
Save xescuder/59824f0a6bd8ca29f6eb42ef4cc6a718 to your computer and use it in GitHub Desktop.
Example of streamlit using ib_insync and streamlit
import logging
import pandas as pd
from dateutil.relativedelta import relativedelta
from dateutil.utils import today
from app.charts import render_candlestick_chart
import streamlit as st
import asyncio
import plotly.graph_objects as go
st.set_page_config(
layout='wide',
page_title='My Dashboard'
)
def get_or_create_eventloop():
try:
return asyncio.get_event_loop()
except RuntimeError as ex:
if "There is no current event loop in thread" in str(ex):
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
return asyncio.get_event_loop()
loop = get_or_create_eventloop()
asyncio.set_event_loop(loop)
from ib_insync import *
from app import ib_utils
if 'ib' not in st.session_state:
st.session_state['ib'] = IB()
if not st.session_state['ib'].isConnected():
st.session_state['ib'].connect(
'127.0.0.1',
4001,
clientId=3,
timeout=0)
logging.basicConfig(level=logging.INFO)
def summary(portfolio_df, col):
fig = go.Figure()
fig.add_trace(
go.Pie(
labels=list(portfolio_df["symbol"]),
values=list(portfolio_df["market_value"]),
sort=False
)
)
fig.update_layout(
margin=dict(l=0, r=0, t=10, b=0)
)
col.plotly_chart(fig, use_container_width=True)
def positions_table(portfolio_df, col):
def highlight_up(val):
color = 'green' if val > 0 else 'red'
return f'background-color: {color}'
portfolio_df = portfolio_df.style. \
format(precision=2, thousands='.', decimal=','). \
map(highlight_up, subset=['perc_change'])
col.dataframe(portfolio_df, column_config={
'symbol': 'Symbol',
'name': 'Name',
'avg_cost': 'Price',
'position': 'Size',
'market_price': 'Current Price',
'market_value': None,
'perc_change': 'Change%',
'unrealized_pnl': 'Unrealized PNL',
'realized_pnl': None
}, hide_index=True)
with st.container():
balance = ib_utils.balance(st.session_state['ib'])
st.markdown(f'# My portfolio <p class="btc-text">{balance:,.2f}</p>', unsafe_allow_html=True)
col1, col2 = st.columns([5, 3])
portfolio_df = ib_utils.portfolio_items(st.session_state['ib'])
positions_table(portfolio_df, col1)
summary(portfolio_df, col2)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment