PB-Dashboard / app.py
anaucoin
fix 3-11 internal dash error
92a313c
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.14.2
# kernelspec:
# display_name: Python [conda env:bbytes] *
# language: python
# name: conda-env-bbytes-py
# ---
# +
import csv
import pandas as pd
from datetime import datetime, timedelta
import numpy as np
import datetime as dt
import matplotlib.pyplot as plt
from pathlib import Path
import time
import plotly.graph_objects as go
import plotly.io as pio
from PIL import Image
import streamlit as st
import plotly.express as px
import altair as alt
import dateutil.parser
from matplotlib.colors import LinearSegmentedColormap
# +
class color:
PURPLE = '\033[95m'
CYAN = '\033[96m'
DARKCYAN = '\033[36m'
BLUE = '\033[94m'
GREEN = '\033[92m'
YELLOW = '\033[93m'
RED = '\033[91m'
BOLD = '\033[1m'
UNDERLINE = '\033[4m'
END = '\033[0m'
@st.cache_data
def print_PL(amnt, thresh, extras = "" ):
if amnt > 0:
return color.BOLD + color.GREEN + str(amnt) + extras + color.END
elif amnt < 0:
return color.BOLD + color.RED + str(amnt)+ extras + color.END
elif np.isnan(amnt):
return str(np.nan)
else:
return str(amnt + extras)
@st.cache_data
def get_headers(logtype):
otimeheader = ""
cheader = ""
plheader = ""
fmat = '%Y-%m-%d %H:%M:%S'
if logtype == "ByBit":
otimeheader = 'Create Time'
cheader = 'Contracts'
plheader = 'Closed P&L'
fmat = '%Y-%m-%d %H:%M:%S'
if logtype == "BitGet":
otimeheader = 'Date'
cheader = 'Futures'
plheader = 'Realized P/L'
fmat = '%Y-%m-%d %H:%M:%S'
if logtype == "MEXC":
otimeheader = 'Trade time'
cheader = 'Futures'
plheader = 'closing position'
fmat = '%Y/%m/%d %H:%M'
if logtype == "Binance":
otimeheader = 'Date'
cheader = 'Symbol'
plheader = 'Realized Profit'
fmat = '%Y-%m-%d %H:%M:%S'
#if logtype == "Kucoin":
# otimeheader = 'Time'
# cheader = 'Contract'
# plheader = ''
# fmat = '%Y/%m/%d %H:%M:%S'
if logtype == "Kraken":
otimeheader = 'time'
cheader = 'asset'
plheader = 'amount'
fmat = '%Y-%m-%d %H:%M:%S.%f'
if logtype == "OkX":
otimeheader = '\ufeffOrder Time'
cheader = '\ufeffInstrument'
plheader = '\ufeffPL'
fmat = '%Y-%m-%d %H:%M:%S'
return otimeheader.lower(), cheader.lower(), plheader.lower(), fmat
@st.cache_data
def get_coin_info(df_coin, principal_balance,plheader):
numtrades = int(len(df_coin))
numwin = int(sum(df_coin[plheader] > 0))
numloss = int(sum(df_coin[plheader] < 0))
winrate = np.round(100*numwin/numtrades,4)
grosswin = sum(df_coin[df_coin[plheader] > 0][plheader])
grossloss = sum(df_coin[df_coin[plheader] < 0][plheader])
if grossloss != 0:
pfactor = -1*np.round(grosswin/grossloss,2)
else:
pfactor = np.nan
cum_PL = np.round(sum(df_coin[plheader].values),2)
cum_PL_perc = np.round(100*cum_PL/principal_balance,2)
mean_PL = np.round(sum(df_coin[plheader].values/len(df_coin)),2)
mean_PL_perc = np.round(100*mean_PL/principal_balance,2)
return numtrades, numwin, numloss, winrate, pfactor, cum_PL, cum_PL_perc, mean_PL, mean_PL_perc
@st.cache_data
def get_hist_info(df_coin, principal_balance,plheader):
numtrades = int(len(df_coin))
numwin = int(sum(df_coin[plheader] > 0))
numloss = int(sum(df_coin[plheader] < 0))
if numtrades != 0:
winrate = np.round(100*numwin/numtrades,4)
else:
winrate = np.nan
grosswin = sum(df_coin[df_coin[plheader] > 0][plheader])
grossloss = sum(df_coin[df_coin[plheader] < 0][plheader])
if grossloss != 0:
pfactor = -1*np.round(grosswin/grossloss,2)
else:
pfactor = np.nan
return numtrades, numwin, numloss, winrate, pfactor
@st.cache_data
def get_rolling_stats(df, lev, otimeheader, days):
max_roll = (df[otimeheader].max() - df[otimeheader].min()).days
if max_roll >= days:
rollend = df[otimeheader].max()-timedelta(days=days)
rolling_df = df[df[otimeheader] >= rollend]
if len(rolling_df) > 0:
rolling_perc = rolling_df['Return Per Trade'].dropna().cumprod().values[-1]-1
else:
rolling_perc = np.nan
else:
rolling_perc = np.nan
return 100*rolling_perc
@st.cache_data
def cc_coding(row):
return ['background-color: lightgrey'] * len(row) if row['Exit Date'] <= datetime.strptime('2022-12-16 00:00:00','%Y-%m-%d %H:%M:%S').date() else [''] * len(row)
def ctt_coding(row):
return ['background-color: lightgrey'] * len(row) if row['Exit Date'] <= datetime.strptime('2023-01-02 00:00:00','%Y-%m-%d %H:%M:%S').date() else [''] * len(row)
@st.cache_data
def my_style(v, props=''):
props = 'color:red' if v < 0 else 'color:green'
return props
def filt_df(df, cheader, symbol_selections):
df = df.copy()
df = df[df[cheader].isin(symbol_selections)]
return df
def drop_frac_cents(d):
D = np.floor(100*d)/100
return D
def load_data(filename, account, exchange, otimeheader, fmat):
cols1 = ['id','datetime', 'exchange', 'subaccount', 'pair', 'side', 'action', 'amount', 'price', 'errors']
cols2 = ['id','datetime', 'exchange', 'subaccount', 'pair', 'side', 'action', 'amount', 'price', 'errors', 'P/L', 'P/L %','exit price', 'Lev']
old_df = pd.read_csv("history-old.csv", header = 0, names= cols1)
df = pd.read_csv(filename, header = 0, names= cols2)
df.loc[df['exit price'] > 0, 'price'] = df.loc[df['exit price'] > 0, 'exit price']
df = pd.concat([old_df, df[old_df.columns]], ignore_index=True)
filtdf = df[(df.exchange == exchange) & (df.subaccount == account)].dropna()
if not filtdf.empty:
filtdf = filtdf.sort_values('datetime')
filtdf = filtdf.iloc[np.where(filtdf.action == 'open')[0][0]:, :] #get first open signal in dataframe
tnum = 0
dca = 0
newdf = pd.DataFrame([], columns=['Trade','Signal','Entry Date','Buy Price', 'Sell Price','Exit Date', 'P/L per token', 'P/L %'])
for index, row in filtdf.iterrows():
if row.action == 'open':
dca += 1
tnum += 1
sig = 'Long' if row.side == 'long' else 'Short'
temp = pd.DataFrame({'Trade' :[tnum], 'Signal': [sig], 'Entry Date':[row.datetime],'Buy Price': [row.price], 'Sell Price': [np.nan],'Exit Date': [np.nan], 'P/L per token': [np.nan], 'P/L %': [np.nan], 'DCA': [dca]})
newdf = pd.concat([newdf,temp], ignore_index = True)
if row.action == 'close':
for j in np.arange(tnum-1, tnum-dca-1,-1):
newdf.loc[j,'Sell Price'] = row.price
newdf.loc[j,'Exit Date'] = row.datetime
dca = 0
newdf['Buy Price'] = pd.to_numeric(newdf['Buy Price'])
newdf['Sell Price'] = pd.to_numeric(newdf['Sell Price'])
newdf['P/L per token'] = newdf['Sell Price'] - newdf['Buy Price']
newdf['P/L %'] = 100*newdf['P/L per token']/newdf['Buy Price']
newdf = newdf.dropna()
else:
newdf = pd.DataFrame([], columns=['Trade','Signal','Entry Date','Buy Price', 'Sell Price','Exit Date', 'P/L per token', 'P/L %'])
if account == 'Pure Bread (ByBit)':
tvdata = pd.read_csv('pb-history-old.csv',header = 0).drop('Unnamed: 0', axis=1)
elif account == 'PUMPernickel (ByBit)':
tvdata = pd.read_csv('pn-history-old.csv',header = 0).drop('Unnamed: 0', axis=1)
else:
tvdata = pd.DataFrame([])
if tvdata.empty:
df = newdf
else:
df = pd.concat([tvdata, newdf], ignore_index =True)
df = df.sort_values('Entry Date', ascending = True)
df.index = range(len(df))
df.Trade = df.index + 1
dateheader = 'Date'
theader = 'Time'
df[dateheader] = [tradetimes.split(" ")[0] for tradetimes in df[otimeheader].values]
df[theader] = [tradetimes.split(" ")[1] for tradetimes in df[otimeheader].values]
df[otimeheader] = pd.to_datetime(df[otimeheader])
df['Exit Date'] = pd.to_datetime(df['Exit Date'])
df[dateheader] = [dateutil.parser.parse(date).date() for date in df[dateheader]]
df[theader] = [dateutil.parser.parse(time).time() for time in df[theader]]
return df
def get_sd_df(sd_df, sd, bot_selections, dca1, dca2, dca3, dca4, dca5, dca6, fees, lev, dollar_cap, principal_balance):
sd = 2*.00026
# ------ Standard Dev. Calculations.
if bot_selections == "Cinnamon Toast":
dca_map = {1: dca1/100, 2: dca2/100, 3: dca3/100, 4: dca4/100, 1.1: dca5/100, 2.1: dca6/100}
sd_df['DCA %'] = sd_df['DCA'].map(dca_map)
sd_df['Calculated Return % (+)'] = df['Signal'].map(signal_map)*(df['DCA %'])*(1-fees)*((df['Sell Price']*(1+df['Signal'].map(signal_map)*sd) - df['Buy Price']*(1-df['Signal'].map(signal_map)*sd))/df['Buy Price']*(1-df['Signal'].map(signal_map)*sd) - fees) #accounts for fees on open and close of trade
sd_df['Calculated Return % (-)'] = df['Signal'].map(signal_map)*(df['DCA %'])*(1-fees)*((df['Sell Price']*(1-df['Signal'].map(signal_map)*sd)-df['Buy Price']*(1+df['Signal'].map(signal_map)*sd))/df['Buy Price']*(1+df['Signal'].map(signal_map)*sd) - fees) #accounts for fees on open and close of trade
sd_df['DCA'] = np.floor(sd_df['DCA'].values)
sd_df['Return Per Trade (+)'] = np.nan
sd_df['Return Per Trade (-)'] = np.nan
sd_df['Balance used in Trade (+)'] = np.nan
sd_df['Balance used in Trade (-)'] = np.nan
sd_df['New Balance (+)'] = np.nan
sd_df['New Balance (-)'] = np.nan
g1 = sd_df.groupby('Exit Date').sum(numeric_only=True)['Calculated Return % (+)'].reset_index(name='Return Per Trade (+)')
g2 = sd_df.groupby('Exit Date').sum(numeric_only=True)['Calculated Return % (-)'].reset_index(name='Return Per Trade (-)')
sd_df.loc[sd_df['DCA']==1.0,'Return Per Trade (+)'] = 1+lev*g1['Return Per Trade (+)'].values
sd_df.loc[sd_df['DCA']==1.0,'Return Per Trade (-)'] = 1+lev*g2['Return Per Trade (-)'].values
sd_df['Compounded Return (+)'] = sd_df['Return Per Trade (+)'].cumprod()
sd_df['Compounded Return (-)'] = sd_df['Return Per Trade (-)'].cumprod()
sd_df.loc[sd_df['DCA']==1.0,'New Balance (+)'] = [min(dollar_cap/lev, bal*principal_balance) for bal in sd_df.loc[sd_df['DCA']==1.0,'Compounded Return (+)']]
sd_df.loc[sd_df['DCA']==1.0,'Balance used in Trade (+)'] = np.concatenate([[principal_balance], sd_df.loc[sd_df['DCA']==1.0,'New Balance (+)'].values[:-1]])
sd_df.loc[sd_df['DCA']==1.0,'New Balance (-)'] = [min(dollar_cap/lev, bal*principal_balance) for bal in sd_df.loc[sd_df['DCA']==1.0,'Compounded Return (-)']]
sd_df.loc[sd_df['DCA']==1.0,'Balance used in Trade (-)'] = np.concatenate([[principal_balance], sd_df.loc[sd_df['DCA']==1.0,'New Balance (-)'].values[:-1]])
else:
sd_df['Calculated Return % (+)'] = df['Signal'].map(signal_map)*(1-fees)*((df['Sell Price']*(1+df['Signal'].map(signal_map)*sd) - df['Buy Price']*(1-df['Signal'].map(signal_map)*sd))/df['Buy Price']*(1-df['Signal'].map(signal_map)*sd) - fees) #accounts for fees on open and close of trade
sd_df['Calculated Return % (-)'] = df['Signal'].map(signal_map)*(1-fees)*((df['Sell Price']*(1-df['Signal'].map(signal_map)*sd)-df['Buy Price']*(1+df['Signal'].map(signal_map)*sd))/df['Buy Price']*(1+df['Signal'].map(signal_map)*sd) - fees) #accounts for fees on open and close of trade
sd_df['Return Per Trade (+)'] = np.nan
sd_df['Return Per Trade (-)'] = np.nan
g1 = sd_df.groupby('Exit Date').sum(numeric_only=True)['Calculated Return % (+)'].reset_index(name='Return Per Trade (+)')
g2 = sd_df.groupby('Exit Date').sum(numeric_only=True)['Calculated Return % (-)'].reset_index(name='Return Per Trade (-)')
sd_df['Return Per Trade (+)'] = 1+lev*g1['Return Per Trade (+)'].values
sd_df['Return Per Trade (-)'] = 1+lev*g2['Return Per Trade (-)'].values
sd_df['Compounded Return (+)'] = sd_df['Return Per Trade (+)'].cumprod()
sd_df['Compounded Return (-)'] = sd_df['Return Per Trade (-)'].cumprod()
sd_df['New Balance (+)'] = [min(dollar_cap/lev, bal*principal_balance) for bal in sd_df['Compounded Return (+)']]
sd_df['Balance used in Trade (+)'] = np.concatenate([[principal_balance], sd_df['New Balance (+)'].values[:-1]])
sd_df['New Balance (-)'] = [min(dollar_cap/lev, bal*principal_balance) for bal in sd_df['Compounded Return (-)']]
sd_df['Balance used in Trade (-)'] = np.concatenate([[principal_balance], sd_df['New Balance (-)'].values[:-1]])
sd_df['Net P/L Per Trade (+)'] = (sd_df['Return Per Trade (+)']-1)*sd_df['Balance used in Trade (+)']
sd_df['Cumulative P/L (+)'] = sd_df['Net P/L Per Trade (+)'].cumsum()
sd_df['Net P/L Per Trade (-)'] = (sd_df['Return Per Trade (-)']-1)*sd_df['Balance used in Trade (-)']
sd_df['Cumulative P/L (-)'] = sd_df['Net P/L Per Trade (-)'].cumsum()
return sd_df
@st.cache_data
def get_account_drawdown(trades, principal_balance):
max_draw_perc = 0.00
beg = 0
trades = np.hstack([0.0, trades.dropna().values]) + principal_balance
if len(trades) > 2:
for ind in range(len(trades)-1):
delta = 100*(trades[ind+1:] - trades[ind])/trades[ind]
max_draw_perc = min(max_draw_perc, delta.min())
else:
max_draw = min(max_draw, trades)
max_draw_perc = 100*max_draw/(principal_balance)
return max_draw_perc
def runapp() -> None:
bot_selections = "Pure Bread"
otimeheader = 'Exit Date'
fmat = '%Y-%m-%d %H:%M:%S'
fees = .075/100
#st.header(f"{bot_selections} Performance Dashboard :bread: :moneybag:")
no_errors = True
#st.write("Welcome to the Trading Bot Dashboard by BreadBytes! You can use this dashboard to track " +
# "the performance of our trading bots.")
if bot_selections == "Pumpernickel":
lev_cap = 2
dollar_cap = 1000000000.00
data = load_data('history.csv', 'PUMPernickel (ByBit)', 'Bybit Futures', otimeheader, fmat)
if bot_selections == "Pure Bread":
lev_cap = 3
dollar_cap = 1000000000.00
data = load_data('history.csv', 'Pure Bread (ByBit)', 'Bybit Futures', otimeheader, fmat)
df = data.copy(deep=True)
dateheader = 'Date'
theader = 'Time'
#st.subheader("Choose your settings:")
with st.form("user input", ):
if no_errors:
with st.container():
col1, col2 = st.columns(2)
with col1:
try:
startdate = st.date_input("Start Date", value=pd.to_datetime(df[otimeheader]).min())
except:
st.error("Please select your exchange or upload a supported trade log file.")
no_errors = False
with col2:
try:
enddate = st.date_input("End Date", value=datetime.today())
except:
st.error("Please select your exchange or upload a supported trade log file.")
no_errors = False
#st.sidebar.subheader("Customize your Dashboard")
if no_errors and (enddate < startdate):
st.error("End Date must be later than Start date. Please try again.")
no_errors = False
with st.container():
col1,col2 = st.columns(2)
with col2:
lev = st.number_input('Leverage', min_value=1, value=1, max_value= lev_cap, step=1)
with col1:
principal_balance = st.number_input('Starting Balance', min_value=0.00, value=1000.00, max_value= dollar_cap, step=.01)
#hack way to get button centered
c = st.columns(9)
with c[4]:
submitted = st.form_submit_button("Get Cookin'!")
signal_map = {'Long': 1, 'Short':-1}
if submitted and principal_balance * lev > dollar_cap:
lev = np.floor(dollar_cap/principal_balance)
st.error(f"WARNING: (Starting Balance)*(Leverage) exceeds the ${dollar_cap} limit. Using maximum available leverage of {lev}")
df = df[(df[dateheader] >= startdate) & (df[dateheader] <= enddate)]
if submitted and len(df) == 0:
st.error("There are no available trades matching your selections. Please try again!")
no_errors = False
if no_errors:
if bot_selections == "Pumpernickel":
dca_map = {1: 1/5, 2: 1/5, 3: 1/5, 4: 1/5, 5: 1/5} #for unequal dca amounts
signal_map = {'Long': 1, 'Short':-1}
df['DCA %'] = df['DCA'].map(dca_map)
df['Calculated Return %'] = (df['DCA %'])*(df['Signal'].map(signal_map)*(df['Sell Price']-df['Buy Price'])/df['Buy Price']-2*fees) #accounts for fees on open and close of trade
df['DCA'] = np.floor(df['DCA'].values)
df['Return Per Trade'] = np.nan
df['Balance used in Trade'] = np.nan
df['New Balance'] = np.nan
g = df.groupby('Exit Date').sum(numeric_only=True)['Calculated Return %'].reset_index(name='Return Per Trade')
df.loc[df['DCA']==1.0,'Return Per Trade'] = 1+lev*g['Return Per Trade'].values
df['Compounded Return'] = df['Return Per Trade'].cumprod()
df.loc[df['DCA']==1.0,'New Balance'] = [min(dollar_cap/lev, bal*principal_balance) for bal in df.loc[df['DCA']==1.0,'Compounded Return']]
df.loc[df['DCA']==1.0,'Balance used in Trade'] = np.concatenate([[principal_balance], df.loc[df['DCA']==1.0,'New Balance'].values[:-1]])
else:
df['Calculated Return %'] = (df['Signal'].map(signal_map)*(df['Sell Price']-df['Buy Price'])/df['Buy Price'])-2*fees #accounts for fees on open and close of trade
df['Return Per Trade'] = np.nan
g = df.groupby('Exit Date').sum(numeric_only=True)['Calculated Return %'].reset_index(name='Return Per Trade')
df['Return Per Trade'] = 1+lev*g['Return Per Trade'].values
df['Compounded Return'] = df['Return Per Trade'].cumprod()
df['New Balance'] = [min(dollar_cap/lev, bal*principal_balance) for bal in df['Compounded Return']]
df['Balance used in Trade'] = np.concatenate([[principal_balance], df['New Balance'].values[:-1]])
df['Net P/L Per Trade'] = drop_frac_cents((df['Return Per Trade']-1)*df['Balance used in Trade'])
df['Cumulative P/L'] = df['Net P/L Per Trade'].cumsum()
max_draw = get_account_drawdown(df['Cumulative P/L'], principal_balance)
cum_pl = df.loc[df.dropna().index[-1],'Cumulative P/L'] + principal_balance
effective_return = 100*((cum_pl - principal_balance)/principal_balance)
#st.header(f"{bot_selections} Results")
with st.container():
if len(bot_selections) > 1:
col1, col2 = st.columns(2)
with col1:
st.metric(
"Total Account Balance",
f"${cum_pl:.2f}",
f"{100*(cum_pl-principal_balance)/(principal_balance):.2f} %",
)
dfdata = df.dropna()
# Create figure
fig = go.Figure()
pyLogo = Image.open("logo.png")
# fig.add_traces(go.Scatter(x=sd_df['Exit Date'], y = sd_df['Cumulative P/L (+)'],line_shape='spline',
# line = dict(smoothing = 1.3, color='rgba(31, 119, 200,0)'), showlegend = False)
# )
# fig.add_traces(go.Scatter(x=sd_df['Exit Date'], y = sd_df['Cumulative P/L (-)'],
# line = dict(smoothing = 1.3, color='rgba(31, 119, 200,0)'), line_shape='spline',
# fill='tonexty',
# fillcolor = 'rgba(31, 119, 200,.2)', name = '+/- Standard Deviation')
# )
# Add trace
fig.add_trace(
go.Scatter(x=dfdata['Exit Date'], y=np.round(dfdata['Cumulative P/L'].values,2), line_shape='spline',
line = {'smoothing': .7, 'color' : 'rgba(90, 223, 137, 1)'},
name='P/L')
)
buyhold = (principal_balance/dfdata['Buy Price'][dfdata.index[0]])*(dfdata['Buy Price']-dfdata['Buy Price'][dfdata.index[0]])
fig.add_trace(go.Scatter(x=dfdata['Exit Date'], y=np.round(buyhold.values,2), line_shape='spline',
line = {'smoothing': .7, 'color' :'rgba(33, 212, 225, 1)'}, name = 'Buy & Hold')
)
img_width = 2001
img_height = 622
fig.add_layout_image(
dict(
source=pyLogo,
xref="paper",
yref="paper",
x = 0.1,
y = 1,
xanchor ="left", yanchor = "top",
sizex= 1,
sizey= 1,
opacity=0.2,
layer = "below")
)
#style layout
fig.update_layout(
height = 550,
xaxis=dict(
title="Exit Date",
tickmode='array',
showgrid=False
),
yaxis=dict(
title="Cumulative P/L",
showgrid=False
),
legend=dict(
x=.05,
y=0.95,
traceorder="normal"
),
plot_bgcolor = 'rgba(10, 10, 10, 1)'
)
st.plotly_chart(fig, theme=None, use_container_width=True, height=550)
st.write()
df['Per Trade Return Rate'] = df['Return Per Trade']-1
totals = pd.DataFrame([], columns = ['# of Trades', 'Wins', 'Losses', 'Win Rate', 'Profit Factor'])
data = get_hist_info(df.dropna(), principal_balance,'Per Trade Return Rate')
totals.loc[len(totals)] = list(i for i in data)
totals['Cum. P/L'] = cum_pl-principal_balance
totals['Cum. P/L (%)'] = 100*(cum_pl-principal_balance)/principal_balance
if df.empty:
st.error("Oops! None of the data provided matches your selection(s). Please try again.")
else:
with st.container():
for row in totals.itertuples():
c1, c2, c3, c4 = st.columns(4)
col1, col2, col3, col4 = st.columns(4)
with col1:
st.metric(
"Total Trades",
f"{row._1:.0f}",
)
with c1:
st.metric(
"Cumulative P/L",
f"${row._6:.2f}",
f"{row._7:.2f} %",
)
with col2:
st.metric(
"Wins",
f"{row.Wins:.0f}",
)
with c2:
st.metric(
"Profit Factor",
f"{row._5:.2f}",
)
with col3:
st.metric(
"Losses",
f"{row.Losses:.0f}",
)
with c3:
st.metric(
"Rolling 7 Days",
"",#f"{(1+get_rolling_stats(df,lev, otimeheader, 7)/100)*principal_balance:.2f}",
f"{get_rolling_stats(df,lev, otimeheader, 7):.2f}%",
)
st.metric(
"Rolling 90 Days",
"",#f"{(1+get_rolling_stats(df,lev, otimeheader, 30)/100)*principal_balance:.2f}",
f"{get_rolling_stats(df,lev, otimeheader, 90):.2f}%",
)
with col4:
st.metric(
"Win Rate",
f"{row._4:.1f}%",
)
with c4:
st.metric(
"Rolling 30 Days",
"",#f"{(1+get_rolling_stats(df,lev, otimeheader, 90)/100)*principal_balance:.2f}",
f"{get_rolling_stats(df,lev, otimeheader, 30):.2f}%",
)
st.metric(
"Max Drawdown",
"",#f"{np.round(100*max_draw/principal_balance,2)/100*principal_balance:.2f}",
f"{np.round(max_draw,2)}%",
)
if bot_selections == "Pumpernickel":
grouped_df = df.groupby('Exit Date').agg({'Signal':'min','Entry Date': 'min','Exit Date': 'max','Buy Price': 'mean',
'Sell Price' : 'max',
'Net P/L Per Trade': 'mean',
'Calculated Return %' : lambda x: np.round(100*lev*x.sum(),2),
'DCA': lambda x: int(np.floor(x.max()))})
grouped_df.index = range(1, len(grouped_df)+1)
grouped_df.rename(columns={'DCA' : '# of DCAs', 'Buy Price':'Avg. Buy Price',
'Net P/L Per Trade':'Net P/L',
'Calculated Return %':'P/L %'}, inplace=True)
else:
grouped_df = df.groupby('Exit Date').agg({'Signal':'min','Entry Date': 'min','Exit Date': 'max','Buy Price': 'mean',
'Sell Price' : 'max',
'Net P/L Per Trade': 'mean',
'Calculated Return %' : lambda x: np.round(100*lev*x.sum(),2)})
grouped_df.index = range(1, len(grouped_df)+1)
grouped_df.rename(columns={'Buy Price':'Buy Price',
'Net P/L Per Trade':'Net P/L',
'Calculated Return %':'P/L %'}, inplace=True)
st.subheader("Trade Logs")
grouped_df['Entry Date'] = pd.to_datetime(grouped_df['Entry Date'])
grouped_df['Exit Date'] = pd.to_datetime(grouped_df['Exit Date'])
if bot_selections == "Pure Bread":
st.dataframe(grouped_df.style.format({'Entry Date':'{:%m-%d-%Y %H:%M:%S}','Exit Date':'{:%m-%d-%Y %H:%M:%S}','Buy Price': '${:.5f}', 'Sell Price': '${:.5f}', 'Net P/L':'${:.2f}', 'P/L %':'{:.2f}%'})\
.applymap(my_style,subset=['Net P/L'])\
.applymap(my_style,subset=['P/L %']), use_container_width=True)
else:
st.dataframe(grouped_df.style.format({'Entry Date':'{:%m-%d-%Y %H:%M:%S}','Exit Date':'{:%m-%d-%Y %H:%M:%S}','Avg. Buy Price': '${:.2f}', 'Sell Price': '${:.2f}', 'Net P/L':'${:.2f}', 'P/L %':'{:.2f}%'})\
.applymap(my_style,subset=['Net P/L'])\
.applymap(my_style,subset=['P/L %']), use_container_width=True)
# st.subheader("Checking Status")
# if submitted:
# st.dataframe(sd_df)
if __name__ == "__main__":
st.set_page_config(
"Trading Bot Dashboard", layout = 'wide'
)
runapp()
# -