anaucoin commited on
Commit
939a229
·
1 Parent(s): b528f30

initial commit

Browse files
Files changed (3) hide show
  1. README.md +5 -5
  2. app.py +327 -0
  3. requirements.txt +8 -0
README.md CHANGED
@@ -1,13 +1,13 @@
1
  ---
2
- title: PB Dashboard
3
- emoji: 🏃
4
  colorFrom: yellow
5
- colorTo: indigo
6
  sdk: streamlit
7
- sdk_version: 1.21.0
8
  app_file: app.py
9
  pinned: false
10
- license: gpl-3.0
11
  ---
12
 
13
  Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
1
  ---
2
+ title: SB Dashboard
3
+ emoji: 🐢
4
  colorFrom: yellow
5
+ colorTo: purple
6
  sdk: streamlit
7
+ sdk_version: 1.17.0
8
  app_file: app.py
9
  pinned: false
10
+ license: gpl
11
  ---
12
 
13
  Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
app.py ADDED
@@ -0,0 +1,327 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # ---
2
+ # jupyter:
3
+ # jupytext:
4
+ # text_representation:
5
+ # extension: .py
6
+ # format_name: light
7
+ # format_version: '1.5'
8
+ # jupytext_version: 1.14.2
9
+ # kernelspec:
10
+ # display_name: Python [conda env:bbytes] *
11
+ # language: python
12
+ # name: conda-env-bbytes-py
13
+ # ---
14
+
15
+ # +
16
+ import csv
17
+ import pandas as pd
18
+ from datetime import datetime, timedelta
19
+ import numpy as np
20
+ import datetime as dt
21
+ import matplotlib.pyplot as plt
22
+ from pathlib import Path
23
+
24
+ import streamlit as st
25
+ import plotly.express as px
26
+ import altair as alt
27
+ import dateutil.parser
28
+ import copy
29
+
30
+
31
+ # +
32
+ @st.experimental_memo
33
+ def get_hist_info(df_coin, principal_balance,plheader):
34
+ numtrades = int(len(df_coin))
35
+ numwin = int(sum(df_coin[plheader] > 0))
36
+ numloss = int(sum(df_coin[plheader] < 0))
37
+ winrate = int(np.round(100*numwin/numtrades,2))
38
+
39
+ grosswin = sum(df_coin[df_coin[plheader] > 0][plheader])
40
+ grossloss = sum(df_coin[df_coin[plheader] < 0][plheader])
41
+ if grossloss !=0:
42
+ pfactor = -1*np.round(grosswin/grossloss,2)
43
+ else:
44
+ pfactor = np.nan
45
+ return numtrades, numwin, numloss, winrate, pfactor
46
+ @st.experimental_memo
47
+ def get_rolling_stats(df, lev, otimeheader, days):
48
+ max_roll = (df[otimeheader].max() - df[otimeheader].min()).days
49
+
50
+ if max_roll >= days:
51
+ rollend = df[otimeheader].max()-timedelta(days=days)
52
+ rolling_df = df[df[otimeheader] >= rollend]
53
+
54
+ if len(rolling_df) > 0:
55
+ rolling_perc = rolling_df['Return Per Trade'].dropna().cumprod().values[-1]-1
56
+ else:
57
+ rolling_perc = np.nan
58
+ else:
59
+ rolling_perc = np.nan
60
+ return 100*rolling_perc
61
+
62
+ @st.experimental_memo
63
+ def filt_df(df, cheader, symbol_selections):
64
+ """
65
+ Inputs: df (pd.DataFrame), cheader (str) and symbol_selections (list[str]).
66
+
67
+ Returns a filtered pd.DataFrame containing only data that matches symbol_selections (list[str])
68
+ from df[cheader].
69
+ """
70
+
71
+ df = df.copy()
72
+ df = df[df[cheader].isin(symbol_selections)]
73
+
74
+ return df
75
+
76
+ @st.experimental_memo
77
+ def my_style(v, props=''):
78
+ props = 'color:red' if v < 0 else 'color:green'
79
+ return props
80
+
81
+ @st.cache(ttl=24*3600, allow_output_mutation=True)
82
+ def load_data(filename, otimeheader,fmat):
83
+ df = pd.read_csv(open(filename,'r'), sep='\t') # so as not to mutate cached value
84
+ df.columns = ['Trade','Signal','Entry Date','Buy Price', 'Sell Price','Exit Date', 'P/L per token', 'P/L %']
85
+
86
+ df['Buy Price'] = df['Buy Price'].str.replace('$', '', regex=True)
87
+ df['Sell Price'] = df['Sell Price'].str.replace('$', '', regex=True)
88
+ df['Buy Price'] = df['Buy Price'].str.replace(',', '', regex=True)
89
+ df['Sell Price'] = df['Sell Price'].str.replace(',', '', regex=True)
90
+ df['P/L per token'] = df['P/L per token'].str.replace('$', '', regex=True)
91
+ df['P/L per token'] = df['P/L per token'].str.replace(',', '', regex=True)
92
+ df['P/L %'] = df['P/L %'].str.replace('%', '', regex=True)
93
+
94
+ df['Buy Price'] = pd.to_numeric(df['Buy Price'])
95
+ df['Sell Price'] = pd.to_numeric(df['Sell Price'])
96
+ df['P/L per token'] = pd.to_numeric(df['P/L per token'])
97
+ df['P/L %'] = pd.to_numeric(df['P/L %'])
98
+
99
+ dateheader = 'Date'
100
+ theader = 'Time'
101
+
102
+ df[dateheader] = [tradetimes.split(" ")[0] for tradetimes in df[otimeheader].values]
103
+ df[theader] = [tradetimes.split(" ")[1] for tradetimes in df[otimeheader].values]
104
+
105
+ df[otimeheader]= [dateutil.parser.parse(date+' '+time)
106
+ for date,time in zip(df[dateheader],df[theader])]
107
+
108
+ df[otimeheader] = pd.to_datetime(df[otimeheader])
109
+ df['Exit Date'] = pd.to_datetime(df['Exit Date'])
110
+ df.sort_values(by=otimeheader, inplace=True)
111
+
112
+ df[dateheader] = [dateutil.parser.parse(date).date() for date in df[dateheader]]
113
+ df[theader] = [dateutil.parser.parse(time).time() for time in df[theader]]
114
+ df['Trade'] = [i+1 for i in range(len(df))] #reindex
115
+
116
+ return df
117
+
118
+ def runapp():
119
+ bot_selections = "Short Bread"
120
+ otimeheader = 'Entry Date'
121
+ plheader = 'Calculated Return %'
122
+ fmat = '%Y-%m-%d %H:%M:%S'
123
+ dollar_cap = 30000.00
124
+ fees = .075/100
125
+ st.header(f"{bot_selections} Performance Dashboard :bread: :moneybag:")
126
+ st.write("Welcome to the Trading Bot Dashboard by BreadBytes! You can use this dashboard to track " +
127
+ "the performance of our trading bots.")
128
+ # st.sidebar.header("FAQ")
129
+
130
+ # with st.sidebar.subheader("FAQ"):
131
+ # st.write(Path("FAQ_README.md").read_text())
132
+ st.subheader("Choose your settings:")
133
+ no_errors = True
134
+
135
+ data = load_data("SB-Trade-Log.csv",otimeheader,fmat)
136
+ df = data.copy(deep=True)
137
+
138
+ grouped_df = df.groupby('Exit Date').agg({'Signal':'min','Entry Date': 'min','Exit Date': 'max','Buy Price': 'mean',
139
+ 'Sell Price' : 'max',
140
+ 'P/L per token': 'mean',
141
+ 'P/L %':lambda x: np.round(x.sum()/4,2)})
142
+ grouped_df.index = range(1, len(grouped_df)+1)
143
+ grouped_df.rename(columns={'Buy Price':'Avg. Buy Price',
144
+ 'P/L per token':'Avg. P/L per token'}, inplace=True)
145
+
146
+ dateheader = 'Date'
147
+ theader = 'Time'
148
+
149
+ with st.form("user input"):
150
+ if no_errors:
151
+ with st.container():
152
+ col1, col2 = st.columns(2)
153
+ with col1:
154
+ try:
155
+ startdate = st.date_input("Start Date", value=pd.to_datetime(df[otimeheader]).min())
156
+ except:
157
+ st.error("Please select your exchange or upload a supported trade log file.")
158
+ no_errors = False
159
+ with col2:
160
+ try:
161
+ enddate = st.date_input("End Date", value=datetime.today())
162
+ except:
163
+ st.error("Please select your exchange or upload a supported trade log file.")
164
+ no_errors = False
165
+ #st.sidebar.subheader("Customize your Dashboard")
166
+
167
+ if no_errors and (enddate < startdate):
168
+ st.error("End Date must be later than Start date. Please try again.")
169
+ no_errors = False
170
+ with st.container():
171
+ col1,col2 = st.columns(2)
172
+ with col2:
173
+ lev = st.number_input('Leverage', min_value=1, value=1, max_value= 5, step=1)
174
+ with col1:
175
+ principal_balance = st.number_input('Starting Balance', min_value=0.00, value=1000.00, max_value= dollar_cap, step=.01)
176
+
177
+ #hack way to get button centered
178
+ c = st.columns(9)
179
+ with c[4]:
180
+ submitted = st.form_submit_button("Get Cookin'!")
181
+
182
+ signal_map = {'Long': 1, 'Short':-1} # 1 for long #-1 for short
183
+
184
+ df['Calculated Return %'] = (1-fees)*(df['Signal'].map(signal_map)*(df['Sell Price']-df['Buy Price'])/df['Buy Price'] - fees) #accounts for fees on open and close of trade
185
+
186
+
187
+ if submitted and principal_balance * lev > dollar_cap:
188
+ lev = np.floor(dollar_cap/principal_balance)
189
+ st.error(f"WARNING: (Starting Balance)*(Leverage) exceeds the ${dollar_cap} limit. Using maximum available leverage of {lev}")
190
+
191
+ if submitted and no_errors:
192
+ df = df[(df[dateheader] >= startdate) & (df[dateheader] <= enddate)]
193
+
194
+ if len(df) == 0:
195
+ st.error("There are no available trades matching your selections. Please try again!")
196
+ no_errors = False
197
+ if no_errors:
198
+ df['Return Per Trade'] = 1+lev*df['Calculated Return %'].values
199
+
200
+ df['Compounded Return'] = df['Return Per Trade'].cumprod()
201
+ df['New Balance'] = [min(dollar_cap/lev, bal*principal_balance) for bal in df['Compounded Return']]
202
+ df['Balance used in Trade'] = np.concatenate([[principal_balance], df['New Balance'].values[:-1]])
203
+ df['Net P/L Per Trade'] = (df['Return Per Trade']-1)*df['Balance used in Trade']
204
+ df['Cumulative P/L'] = df['Net P/L Per Trade'].cumsum()
205
+
206
+ cum_pl = df.loc[df.dropna().index[-1],'Cumulative P/L'] + principal_balance
207
+
208
+ effective_return = 100*((cum_pl - principal_balance)/principal_balance)
209
+
210
+ st.header(f"{bot_selections} Results")
211
+ if len(bot_selections) > 1:
212
+ st.metric(
213
+ "Total Account Balance",
214
+ f"${cum_pl:.2f}",
215
+ f"{100*(cum_pl-principal_balance)/(principal_balance):.2f} %",
216
+ )
217
+
218
+ st.line_chart(data=df.dropna(), x='Exit Date', y='Cumulative P/L', use_container_width=True)
219
+
220
+ df['Per Trade Return Rate'] = df['Return Per Trade']-1
221
+
222
+ totals = pd.DataFrame([], columns = ['# of Trades', 'Wins', 'Losses', 'Win Rate', 'Profit Factor'])
223
+ data = get_hist_info(df.dropna(), principal_balance,'Calculated Return %')
224
+ totals.loc[len(totals)] = list(i for i in data)
225
+
226
+ totals['Cum. P/L'] = cum_pl-principal_balance
227
+ totals['Cum. P/L (%)'] = 100*(cum_pl-principal_balance)/principal_balance
228
+ #results_df['Avg. P/L'] = (cum_pl-principal_balance)/results_df['# of Trades'].values[0]
229
+ #results_df['Avg. P/L (%)'] = 100*results_df['Avg. P/L'].values[0]/principal_balance
230
+
231
+ if df.empty:
232
+ st.error("Oops! None of the data provided matches your selection(s). Please try again.")
233
+ else:
234
+ #st.dataframe(totals.style.format({'# of Trades': '{:.0f}','Wins': '{:.0f}','Losses': '{:.0f}','Win Rate': '{:.2f}%','Profit Factor' : '{:.2f}', 'Avg. P/L (%)': '{:.2f}%', 'Cum. P/L (%)': '{:.2f}%', 'Cum. P/L': '{:.2f}', 'Avg. P/L': '{:.2f}'})
235
+ #.text_gradient(subset=['Win Rate'],cmap="RdYlGn", vmin = 0, vmax = 100)\
236
+ #.text_gradient(subset=['Profit Factor'],cmap="RdYlGn", vmin = 0, vmax = 2), use_container_width=True)
237
+ for row in totals.itertuples():
238
+ col1, col2, col3, col4 = st.columns(4)
239
+ c1, c2, c3, c4 = st.columns(4)
240
+ with col1:
241
+ st.metric(
242
+ "Total Trades",
243
+ f"{row._1:.0f}",
244
+ )
245
+ with c1:
246
+ st.metric(
247
+ "Profit Factor",
248
+ f"{row._5:.2f}",
249
+ )
250
+ with col2:
251
+ st.metric(
252
+ "Wins",
253
+ f"{row.Wins:.0f}",
254
+ )
255
+ with c2:
256
+ st.metric(
257
+ "Cumulative P/L",
258
+ f"${row._6:.2f}",
259
+ f"{row._7:.2f} %",
260
+ )
261
+ with col3:
262
+ st.metric(
263
+ "Losses",
264
+ f"{row.Losses:.0f}",
265
+ )
266
+ with c3:
267
+ st.metric(
268
+ "Rolling 7 Days",
269
+ "",#f"{(1+get_rolling_stats(df,otimeheader, 30))*principal_balance:.2f}",
270
+ f"{get_rolling_stats(df,lev, otimeheader, 7):.2f}%",
271
+ )
272
+ st.metric(
273
+ "Rolling 30 Days",
274
+ "",#f"{(1+get_rolling_stats(df,otimeheader, 30))*principal_balance:.2f}",
275
+ f"{get_rolling_stats(df,lev, otimeheader, 30):.2f}%",
276
+ )
277
+
278
+ with col4:
279
+ st.metric(
280
+ "Win Rate",
281
+ f"{row._4:.1f}%",
282
+ )
283
+ with c4:
284
+ st.metric(
285
+ "Rolling 90 Days",
286
+ "",#f"{(1+get_rolling_stats(df,otimeheader, 30))*principal_balance:.2f}",
287
+ f"{get_rolling_stats(df,lev, otimeheader, 90):.2f}%",
288
+ )
289
+ st.metric(
290
+ "Rolling 180 Days",
291
+ "",#f"{(1+get_rolling_stats(df,otimeheader, 30))*principal_balance:.2f}",
292
+ f"{get_rolling_stats(df,lev, otimeheader, 180):.2f}%",
293
+ )
294
+ if submitted:
295
+ grouped_df = df.groupby('Exit Date').agg({'Signal':'min','Entry Date': 'min','Exit Date': 'max','Buy Price': 'mean',
296
+ 'Sell Price' : 'max',
297
+ 'Net P/L Per Trade': 'mean',
298
+ 'Calculated Return %' : lambda x: np.round(100*lev*x.sum(),3)})
299
+ grouped_df.index = range(1, len(grouped_df)+1)
300
+ grouped_df.rename(columns={'Buy Price':'Avg. Buy Price',
301
+ 'Net P/L Per Trade':'Net P/L',
302
+ 'Calculated Return %':'P/L %'}, inplace=True)
303
+ else:
304
+ grouped_df = df.groupby('Exit Date').agg({'Signal':'min','Entry Date': 'min','Exit Date': 'max','Buy Price': 'mean',
305
+ 'Sell Price' : 'max',
306
+ 'P/L per token': 'mean',
307
+ 'Calculated Return %' : lambda x: np.round(100*x.sum(),3)})
308
+ grouped_df.index = range(1, len(grouped_df)+1)
309
+ grouped_df.rename(columns={'Buy Price':'Avg. Buy Price',
310
+ 'P/L per token':'Net P/L',
311
+ 'Calculated Return %':'P/L %'}, inplace=True)
312
+ st.subheader("Trade Logs")
313
+ grouped_df['Entry Date'] = pd.to_datetime(grouped_df['Entry Date'])
314
+ grouped_df['Exit Date'] = pd.to_datetime(grouped_df['Exit Date'])
315
+ 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':'${:.3f}', 'P/L %':'{:.2f}%'})\
316
+ .applymap(my_style,subset=['Net P/L'])\
317
+ .applymap(my_style,subset=['P/L %']), use_container_width=True)
318
+
319
+ if __name__ == "__main__":
320
+ st.set_page_config(
321
+ "Trading Bot Dashboard",
322
+ layout="wide",
323
+ )
324
+ runapp()
325
+ # -
326
+
327
+
requirements.txt ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ pandas
2
+ datetime
3
+ numpy
4
+ matplotlib
5
+ pathlib
6
+ plotly
7
+ altair
8
+ streamlit