anaucoin commited on
Commit
1e1d50c
·
1 Parent(s): 9311b36

initial commit

Browse files
Files changed (4) hide show
  1. .streamlit/config.toml +6 -0
  2. .streamlit/secrets.toml +2 -0
  3. app.py +319 -0
  4. requirements.txt +9 -0
.streamlit/config.toml ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ [server]
2
+ port=8501
3
+ enableCORS = false
4
+ enableXsrfProtection = false
5
+ [theme]
6
+ base = "light"
.streamlit/secrets.toml ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ db_username = "Bakery"
2
+ db_password = "TheMuffinMan"
app.py ADDED
@@ -0,0 +1,319 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ rollend = datetime.today()-timedelta(days=days)
49
+ rolling_df = df[df[otimeheader] >= rollend]
50
+
51
+ if len(rolling_df) > 0:
52
+ rolling_perc = rolling_df['Return Per Trade'].dropna().cumprod().values[-1]-1
53
+ else:
54
+ rolling_perc = 0
55
+ return 100*lev*rolling_perc
56
+
57
+ @st.experimental_memo
58
+ def filt_df(df, cheader, symbol_selections):
59
+ """
60
+ Inputs: df (pd.DataFrame), cheader (str) and symbol_selections (list[str]).
61
+
62
+ Returns a filtered pd.DataFrame containing only data that matches symbol_selections (list[str])
63
+ from df[cheader].
64
+ """
65
+
66
+ df = df.copy()
67
+ df = df[df[cheader].isin(symbol_selections)]
68
+
69
+ return df
70
+
71
+ @st.experimental_memo
72
+ def my_style(v, props=''):
73
+ props = 'color:red' if v < 0 else 'color:green'
74
+ return props
75
+
76
+ @st.experimental_memo
77
+ def cc_coding(row):
78
+ return ['background-color: orange'] * len(row) if row['Exit Date'] <= datetime.strptime('2022-12-16 00:00:00','%Y-%m-%d %H:%M:%S').date() else [''] * len(row)
79
+
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','Entry Date','Buy Price', 'Sell Price','Exit Date', 'P/L per token', 'P/L %', 'Drawdown %']
85
+ df.insert(1, 'Signal', ['Long']*len(df))
86
+
87
+ df['Buy Price'] = df['Buy Price'].str.replace('$', '', regex=True)
88
+ df['Sell Price'] = df['Sell Price'].str.replace('$', '', regex=True)
89
+ df['Buy Price'] = df['Buy Price'].str.replace(',', '', regex=True)
90
+ df['Sell Price'] = df['Sell Price'].str.replace(',', '', regex=True)
91
+ df['P/L per token'] = df['P/L per token'].str.replace('$', '', regex=True)
92
+ df['P/L per token'] = df['P/L per token'].str.replace(',', '', regex=True)
93
+ df['P/L %'] = df['P/L %'].str.replace('%', '', regex=True)
94
+
95
+ df['Buy Price'] = pd.to_numeric(df['Buy Price'])
96
+ df['Sell Price'] = pd.to_numeric(df['Sell Price'])
97
+ df['P/L per token'] = pd.to_numeric(df['P/L per token'])
98
+ df['P/L %'] = pd.to_numeric(df['P/L %'])
99
+
100
+ dateheader = 'Date'
101
+ theader = 'Time'
102
+
103
+ df[dateheader] = [tradetimes.split(" ")[0] for tradetimes in df[otimeheader].values]
104
+ df[theader] = [tradetimes.split(" ")[1] for tradetimes in df[otimeheader].values]
105
+
106
+ df[otimeheader]= [dateutil.parser.parse(date+' '+time)
107
+ for date,time in zip(df[dateheader],df[theader])]
108
+
109
+ df[otimeheader] = pd.to_datetime(df[otimeheader])
110
+ df['Exit Date'] = pd.to_datetime(df['Exit Date'])
111
+ df.sort_values(by=otimeheader, inplace=True)
112
+
113
+ df[dateheader] = [dateutil.parser.parse(date).date() for date in df[dateheader]]
114
+ df[theader] = [dateutil.parser.parse(time).time() for time in df[theader]]
115
+ df['Trade'] = [i+1 for i in range(len(df))] #reindex
116
+
117
+ return df
118
+
119
+ def runapp():
120
+ bot_selections = "Cosmic Cupcake"
121
+ otimeheader = 'Entry Date'
122
+ plheader = 'P/L %'
123
+ fmat = '%Y-%m-%d %H:%M:%S'
124
+ dollar_cap = 30000.00
125
+ fees = .075/100
126
+ st.header(f"{bot_selections} Performance Dashboard :bread: :moneybag:")
127
+ st.write("Welcome to the Trading Bot Dashboard by BreadBytes! You can use this dashboard to track " +
128
+ "the performance of our trading bots.")
129
+ # st.sidebar.header("FAQ")
130
+
131
+ # with st.sidebar.subheader("FAQ"):
132
+ # st.write(Path("FAQ_README.md").read_text())
133
+ st.subheader("Choose your settings:")
134
+ no_errors = True
135
+
136
+ data = load_data("CC-Trade-Log.csv",otimeheader,fmat)
137
+ df = data.copy(deep=True)
138
+
139
+ dateheader = 'Date'
140
+ theader = 'Time'
141
+
142
+ with st.form("user input", ):
143
+ if no_errors:
144
+ with st.container():
145
+ col1, col2 = st.columns(2)
146
+ with col1:
147
+ try:
148
+ startdate = st.date_input("Start Date", value=pd.to_datetime(df[otimeheader]).min())
149
+ except:
150
+ st.error("Please select your exchange or upload a supported trade log file.")
151
+ no_errors = False
152
+ with col2:
153
+ try:
154
+ enddate = st.date_input("End Date", value=datetime.today())
155
+ except:
156
+ st.error("Please select your exchange or upload a supported trade log file.")
157
+ no_errors = False
158
+ #st.sidebar.subheader("Customize your Dashboard")
159
+
160
+ if no_errors and (enddate < startdate):
161
+ st.error("End Date must be later than Start date. Please try again.")
162
+ no_errors = False
163
+ with st.container():
164
+ col1,col2 = st.columns(2)
165
+ with col2:
166
+ lev = st.number_input('Leverage', min_value=1, value=1, max_value= 3, step=1)
167
+ with col1:
168
+ principal_balance = st.number_input('Starting Balance', min_value=0.00, value=1000.00, max_value= dollar_cap, step=.01)
169
+
170
+ #hack way to get button centered
171
+ c = st.columns(9)
172
+ with c[4]:
173
+ submitted = st.form_submit_button("Get Cookin'!")
174
+
175
+ if submitted and principal_balance * lev > dollar_cap:
176
+ lev = np.floor(dollar_cap/principal_balance)
177
+ st.error(f"WARNING: (Starting Balance)*(Leverage) exceeds the ${dollar_cap} limit. Using maximum available leverage of {lev}")
178
+
179
+ if submitted and no_errors:
180
+ df = df[(df[dateheader] >= startdate) & (df[dateheader] <= enddate)]
181
+
182
+ if len(df) == 0:
183
+ st.error("There are no available trades matching your selections. Please try again!")
184
+ no_errors = False
185
+ if no_errors:
186
+
187
+ signal_map = {'Long': 1, 'Short':-1} # 1 for long #-1 for short
188
+
189
+ df['Calculated Return %'] = df['Signal'].map(signal_map)*(1-fees)*((df['Sell Price']-df['Buy Price'])/df['Buy Price'] - fees) #accounts for fees on open and close of trade
190
+
191
+ df['Return Per Trade'] = 1+df['Calculated Return %'].values
192
+
193
+ df['Compounded Return'] = df['Return Per Trade'].cumprod()
194
+ df['Balance used in Trade'] = [min(dollar_cap/lev, bal*principal_balance) for bal in df['Compounded Return']]
195
+ df['Net P/L Per Trade'] = (df['Return Per Trade']-1)*lev*df['Balance used in Trade']
196
+ df['Cumulative P/L'] = df['Net P/L Per Trade'].cumsum()
197
+ cum_pl = df.loc[df.dropna().index[-1],'Cumulative P/L'] + principal_balance
198
+
199
+ effective_return = 100*((cum_pl - principal_balance)/principal_balance)
200
+
201
+ st.header(f"{bot_selections} Results")
202
+ if len(bot_selections) > 1:
203
+ st.metric(
204
+ "Total Account Balance",
205
+ f"${cum_pl:.2f}",
206
+ f"{100*(cum_pl-principal_balance)/(principal_balance):.2f} %",
207
+ )
208
+
209
+ st.line_chart(data=df.dropna(), x='Exit Date', y='Cumulative P/L', use_container_width=True)
210
+
211
+ df['Per Trade Return Rate'] = df['Return Per Trade']-1
212
+
213
+ totals = pd.DataFrame([], columns = ['# of Trades', 'Wins', 'Losses', 'Win Rate', 'Profit Factor'])
214
+ data = get_hist_info(df.dropna(), principal_balance,'Per Trade Return Rate')
215
+ totals.loc[len(totals)] = list(i for i in data)
216
+
217
+ totals['Cum. P/L'] = cum_pl-principal_balance
218
+ totals['Cum. P/L (%)'] = 100*(cum_pl-principal_balance)/principal_balance
219
+ #results_df['Avg. P/L'] = (cum_pl-principal_balance)/results_df['# of Trades'].values[0]
220
+ #results_df['Avg. P/L (%)'] = 100*results_df['Avg. P/L'].values[0]/principal_balance
221
+
222
+ if df.empty:
223
+ st.error("Oops! None of the data provided matches your selection(s). Please try again.")
224
+ else:
225
+ #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}'})
226
+ #.text_gradient(subset=['Win Rate'],cmap="RdYlGn", vmin = 0, vmax = 100)\
227
+ #.text_gradient(subset=['Profit Factor'],cmap="RdYlGn", vmin = 0, vmax = 2), use_container_width=True)
228
+ for row in totals.itertuples():
229
+ col1, col2, col3, col4 = st.columns(4)
230
+ c1, c2, c3, c4 = st.columns(4)
231
+ with col1:
232
+ st.metric(
233
+ "Total Trades",
234
+ f"{row._1:.0f}",
235
+ )
236
+ with c1:
237
+ st.metric(
238
+ "Profit Factor",
239
+ f"{row._5:.2f}",
240
+ )
241
+ with col2:
242
+ st.metric(
243
+ "Wins",
244
+ f"{row.Wins:.0f}",
245
+ )
246
+ with c2:
247
+ st.metric(
248
+ "Cumulative P/L",
249
+ f"${row._6:.2f}",
250
+ f"{row._7:.2f} %",
251
+ )
252
+ with col3:
253
+ st.metric(
254
+ "Losses",
255
+ f"{row.Losses:.0f}",
256
+ )
257
+ with c3:
258
+ st.metric(
259
+ "Rolling 7 Days",
260
+ "",#f"{(1+get_rolling_stats(df,otimeheader, 30))*principal_balance:.2f}",
261
+ f"{get_rolling_stats(df,lev, otimeheader, 7):.2f}%",
262
+ )
263
+ st.metric(
264
+ "Rolling 30 Days",
265
+ "",#f"{(1+get_rolling_stats(df,otimeheader, 30))*principal_balance:.2f}",
266
+ f"{get_rolling_stats(df,lev, otimeheader, 30):.2f}%",
267
+ )
268
+
269
+ with col4:
270
+ st.metric(
271
+ "Win Rate",
272
+ f"{row._4:.1f}%",
273
+ )
274
+ with c4:
275
+ st.metric(
276
+ "Rolling 90 Days",
277
+ "",#f"{(1+get_rolling_stats(df,otimeheader, 30))*principal_balance:.2f}",
278
+ f"{get_rolling_stats(df,lev, otimeheader, 90):.2f}%",
279
+ )
280
+ st.metric(
281
+ "Rolling 180 Days",
282
+ "",#f"{(1+get_rolling_stats(df,otimeheader, 30))*principal_balance:.2f}",
283
+ f"{get_rolling_stats(df,lev, otimeheader, 180):.2f}%",
284
+ )
285
+
286
+ if submitted:
287
+ grouped_df = df.groupby('Exit Date').agg({'Signal':'min','Entry Date': 'min','Exit Date': 'max','Buy Price': 'mean',
288
+ 'Sell Price' : 'max',
289
+ 'P/L per token': 'mean',
290
+ 'Calculated Return %' : lambda x: np.round(100*lev*x.sum(),2)})
291
+ grouped_df.index = range(1, len(grouped_df)+1)
292
+ grouped_df.rename(columns={'Buy Price':'Avg. Buy Price',
293
+ 'P/L per token':'Avg. P/L per token',
294
+ 'Calculated Return %':'P/L %'}, inplace=True)
295
+ else:
296
+ grouped_df = df.groupby('Exit Date').agg({'Signal':'min','Entry Date': 'min','Exit Date': 'max','Buy Price': 'mean',
297
+ 'Sell Price' : 'max',
298
+ 'P/L per token': 'mean',
299
+ 'P/L %':lambda x: np.round(x.sum()/4,2)})
300
+ grouped_df.index = range(1, len(grouped_df)+1)
301
+ grouped_df.rename(columns={'Buy Price':'Avg. Buy Price',
302
+ 'P/L per token':'Avg. P/L per token'}, inplace=True)
303
+ st.subheader("Trade Logs")
304
+ st.dataframe(grouped_df.style.format({'Avg. Buy Price': '${:.2f}', 'Sell Price': '${:.2f}', 'Avg. P/L per token':'${:.2f}', 'P/L %':'{:.2f}%'})\
305
+ .apply(cc_coding, axis=1)\
306
+ .applymap(my_style,subset=['Avg. P/L per token'])\
307
+ .applymap(my_style,subset=['P/L %']), use_container_width=True)
308
+ new_title = '<div style="text-align: right;"><span style="background-color:orange;">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span> Not Live Traded</div>'
309
+ st.markdown(new_title, unsafe_allow_html=True)
310
+
311
+ if __name__ == "__main__":
312
+ st.set_page_config(
313
+ "Trading Bot Dashboard",
314
+ layout="wide",
315
+ )
316
+ runapp()
317
+ # -
318
+
319
+
requirements.txt ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ pandas
2
+ datetime
3
+ numpy
4
+ matplotlib
5
+ pathlib
6
+ plotly
7
+ altair
8
+ openpyxl
9
+ streamlit