-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathapp.py
More file actions
435 lines (375 loc) · 14.1 KB
/
app.py
File metadata and controls
435 lines (375 loc) · 14.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
from dash import dash, html, dcc, Input, Output, State, dash_table
import dash_bootstrap_components as dbc
import numpy as np
import pandas as pd
from scipy.stats import norm
import plotly.express as px
import plotly.graph_objects as go
app = dash.Dash(__name__,
external_stylesheets=[dbc.themes.MINTY])
server = app.server
money = dash_table.FormatTemplate.money(0)
percentage = dash_table.FormatTemplate.percentage(2)
df = pd.read_csv('data/freq.csv')
edge = pd.read_csv('data/edge.csv')
advantage = [0.005*i - 0.0054 for i in range(-1, 7)]
rule = dbc.Card([
dbc.CardHeader('Rules'),
dbc.Row([
dbc.Col(
dcc.Checklist(
id='rule-check-1',
options={
'dd': ' Double Deck',
'd10': ' Double on 10+',
'd9': ' Double on 9+'
},
value=[],
labelStyle = {'display': 'block'}
),
width=3
),
dbc.Col(
dcc.Checklist(
id='rule-check-2',
options={
'h17': ' Dealer hits S17',
'european': ' No hole card',
'das': ' Double after split',
},
value=['h17'],
labelStyle = {'display': 'block'}
),
width=3
),
dbc.Col(
dcc.Checklist(
id='rule-check-3',
options={
'd3': ' Double > 2 cards',
'rsa': ' Resplit aces',
'dsa': ' Draw to splitted aces',
},
value=[],
labelStyle = {'display': 'block'}
),
width=3
),
dbc.Col(
dcc.Checklist(
id='rule-check-4',
options={
'late': ' Late Surrender',
'early': ' Early Surrender'
},
value=[],
labelStyle = {'display': 'block'}
),
width=3
)
])
])
base = dcc.Store(id='base', data=0.00054)
personalization = dbc.Card([
dbc.CardHeader('Personal settings'),
dbc.CardBody(
dash_table.DataTable(
id='personalization_table',
columns=[
{'id': 'stat', 'name': ''},
{'id': 'value', 'name': 'Input Your Value Here', 'type': 'numeric', 'editable': True}
],
data=[
{'stat': 'Bankroll', 'value': 10000},
{'stat': 'Hour', 'value': 1},
{'stat': 'Round per Hour', 'value': 100}
],
style_data_conditional=[
{
'if': {
'column_id': 'value',
},
'backgroundColor': 'cornsilk',
# 'color': 'white'
}]
#style_header = {'display': 'none'}
)
)
])
freq_table = dash_table.DataTable(
id='freq-table',
columns=[
{'id': 'count', 'name': 'Count'},
{'id': 'freq', 'name': 'Frequency', 'type': 'numeric', 'format': percentage},
{'id': 'ev', 'name': 'EV', 'type': 'numeric', 'format': percentage},
{'id': 'customized', 'name': 'Customized', 'type': 'numeric', 'format': money, 'editable': True}
],
data=df.to_dict('records'),
style_data_conditional=[
{
'if': {
'column_id': 'customized',
},
'backgroundColor': 'cornsilk',
# 'color': 'white'
}]
)
stat_table = dash_table.DataTable(
id='stat_table',
columns=[
{'id': 'stat', 'name': ''},
{'id': 'value', 'name': ''}
],
data=[
{'stat': 'EV', 'value': 0},
{'stat': 'RoR', 'value': 0},
{'stat': 'EV (%)', 'value':0},
{'stat': 'EV/hour', 'value':0},
{'stat': 'Standard deviation', 'value':0},
{'stat': 'Risk of Ruin (per hour)', 'value':0},
{'stat': 'Risk of Ruin', 'value':0}
],
# style_header = {'display': 'none'}
)
worst_table = dbc.Card([
dbc.CardHeader('Worse Case Scenario'),
dbc.CardBody(
dash_table.DataTable(
id='worst_table',
columns=[
{'id': 'probability', 'name': 'Probability'},
{'id': 'return', 'name': 'Return'}
],
data=[
{'probability': '1%', 'return': 0},
{'probability': '5%', 'return': 0},
{'probability': '10%', 'return': 0},
{'probability': '50%', 'return': 0}
]
# style_header = {'display': 'none'}
)
)
])
dist_graph = dcc.Graph(id='dist_graph')
main_page = [
dbc.Row([
dbc.Col(
[
rule,
html.Br(),
freq_table
],
width=7
),
dbc.Col(
dbc.Spinner(
children=dist_graph),
width=5)
]),
# html.Br(style={"line-height": 1}),
dbc.Row([
dbc.Col(personalization, width=4),
dbc.Col(stat_table, width=4),
dbc.Col(worst_table, width=4)
])
]
app.layout = dbc.Container([
# Stored data
base,
# Header
html.H1('Simple and Easy Blackjack Calculator'),
dbc.Tabs([
dbc.Tab(label='Main Page', children=main_page),
dbc.Tab(label='Guide', children=dcc.Markdown(
'''
### Overview
Welcome, advantage players! This is the first free online Blackjack bankroll managment application. If you are hesitating whether to purchase CVCX or the BJA Pro Betting Software in the early stage of your counting journey, you may want to try out this web app.
If you are already a pro in Blackjack, I will advise you to use either CVCX or the BJA Pro Betting Software. They are designed with a simulation approach and with more advanced statistics. This web app is using a theoretical approach, which results should be treated as approximations (at least in the current stage) if you are going serious in card counting.
### How to use
1. Specify the rules of your blackjack game using the checkboxes. This will determine the the base advantage of the house.
2. Specify your own bet spread (i.e., betting strategy). Please note the players' advantage with each count is estimated roughly using the heuristic of +0.5% advantage for each unit increase in the count.
3. Specify your bankroll (i.e., the amount of money you prepare for card counting), hour (i.e., usually the amount of time for 1 trip), and the number of rounds per hour. These will be used for risk estimation.
4. Adjust your bet spread so that your expected return and risk become reasonable. Please also be reminded to use a bet spread that will not draw much attention from the casino!
### Good luck counting!
'''
)),
dbc.Tab(label='Learn More', children=dcc.Markdown(
'''
For more information, please contact me on Reddit at [r/lohessabb](https://www.reddit.com/user/lohessabb).
Source code is available upon request.
''')
)
]),
])
# Update base edge
@app.callback(
Output(component_id='base', component_property='data'),
[Input(component_id='rule-check-1', component_property='value'),
Input(component_id='rule-check-2', component_property='value'),
Input(component_id='rule-check-3', component_property='value'),
Input(component_id='rule-check-4', component_property='value')]
)
def update_output_div(rule_1, rule_2, rule_3, rule_4):
input_value = rule_1 + rule_2 + rule_3 + rule_4
ddf = edge[edge['Rule'].isin(input_value)]
if 'dd' in input_value:
return(ddf['DD'].sum())
else:
return(ddf['Shoe'].sum())
# Update EV
@app.callback(
Output(component_id='freq-table', component_property='data'),
Input(component_id='base', component_property='data'),
State(component_id='freq-table', component_property='data')
)
def update_output_div(input_value, rows):
for i, row in enumerate(rows):
row['ev'] = advantage[i] + input_value
return rows
# Update statistics
@app.callback(
Output(component_id='stat_table', component_property='data'),
[Input(component_id='freq-table', component_property='data'),
Input(component_id='personalization_table', component_property='data')],
State(component_id='stat_table', component_property='data')
)
def update_output_div(freq, personalization, rows):
dff = pd.DataFrame(freq)
bankroll = pd.DataFrame(personalization).iloc[0, 1]
round_per_hour = pd.DataFrame(personalization).iloc[2, 1]
# Average bet
rows[0]['stat'] = 'Average Bet'
avg_bet = sum(dff['freq']*dff['customized'])
rows[0]['value'] = f'${avg_bet:.2f}'
# EV
rows[1]['stat'] = 'Expected Value (per round)'
ev = sum(dff['freq']*dff['ev']*dff['customized'])
rows[1]['value'] = f'${ev:.2f}'
# EV / hour
rows[2]['stat'] = 'Expected Value (per hour)'
ev_hour = sum(dff['freq']*dff['ev']*dff['customized']*round_per_hour)
rows[2]['value'] = f'${ev_hour:.2f}'
# EV %
rows[3]['stat'] = 'EV (%)'
ev_percentage = ev / avg_bet
rows[3]['value'] = f'{ev_percentage*100:.2f}%'
# Standard deviation / round
rows[4]['stat'] = 'Standard deviation (per round)'
std = sum(dff['freq'] * 1.16 ** 2 * dff['customized'] ** 2) ** 0.5
rows[4]['value'] = f'${std:.2f}'
# Standard deviation / hour
rows[5]['stat'] = 'Standard deviation (per hour)'
std_hour = std * (round_per_hour ** 0.5)
rows[5]['value'] = f'${std_hour:.2f}'
# RoR
rows[6]['stat'] = 'Risk of Ruin'
ror = min(
((1 - ev / std) / (1 + ev / std)) ** (bankroll / std), 1
) # if the risk f
rows[6]['value'] = f'{ror*100:.2f}%'
return rows
# Update Distribution
@app.callback(
Output(component_id='dist_graph', component_property='figure'),
[Input(component_id='stat_table', component_property='data'),
Input(component_id='personalization_table', component_property='data'),
Input(component_id='worst_table', component_property='data')],
)
def update_output_div(stat, personalization, worst):
ev = float(pd.DataFrame(stat).iloc[1, 1].strip('$'))
sd = float(pd.DataFrame(stat).iloc[4, 1].strip('$'))
hours = pd.DataFrame(personalization).iloc[1, 1]
round_per_hour = pd.DataFrame(personalization).iloc[2, 1]
worst = pd.DataFrame(worst)
sd = sd * (hours * round_per_hour) ** 0.5 # Taking square root because each run is independent
z = np.linspace(norm.ppf(0.01), norm.ppf(0.99), 10000)
x = z * sd + ev * hours * round_per_hour
y = norm.pdf(z)
z50 = np.linspace(norm.ppf(0.25), norm.ppf(0.75), 1000)
x50 = z50 * sd + ev * hours * round_per_hour
y50 = norm.pdf(z50)
dff_whole = pd.DataFrame({'x': x, 'y': y})
dff_50 = pd.DataFrame({'x50': x50, 'y50': y50})
figure = px.line(dff_whole, x='x', y='y',
title = 'Distribution of Actual Return',
labels={'x': 'Actual Return', 'y': 'Probability Density'})
# figure.add_trace(go.Scatter(x=x50, y=y50, fill='tozeroy', mode='none'))
figure.add_trace(go.Scatter(
x=[norm.ppf(0.01) * sd + ev * hours * round_per_hour, norm.ppf(0.01) * sd + ev * hours * round_per_hour],
y=[0, 0.5],
line={
'color': 'rgb(31, 119, 180)',
'width': 1,
'dash': 'dashdot',
}, name=f'Worst 1%: {worst.iloc[0, 1]}'
))
figure.add_trace(go.Scatter(
x=[norm.ppf(0.05) * sd + ev * hours * round_per_hour, norm.ppf(0.05) * sd + ev * hours * round_per_hour],
y=[0, 0.5],
line={
'color': 'rgb(255, 127, 14)',
'width': 1,
'dash': 'dashdot',
}, name=f'Worst 5%: {worst.iloc[1, 1]}'
))
figure.add_trace(go.Scatter(
x=[norm.ppf(0.1) * sd + ev * hours * round_per_hour, norm.ppf(0.1) * sd + ev * hours * round_per_hour],
y=[0, 0.5],
line={
'color': 'rgb(44, 160, 44)',
'width': 1,
'dash': 'dashdot',
}, name=f'Worst 10%: {worst.iloc[2, 1]}'
))
figure.add_trace(go.Scatter(
x=[norm.ppf(0.5) * sd + ev * hours * round_per_hour, norm.ppf(0.5) * sd + ev * hours * round_per_hour],
y=[0, 0.5],
line={
'color': 'rgb(148, 103, 189)',
'width': 1,
'dash': 'dashdot',
}, name=f'Worst 50%: {worst.iloc[3, 1]}'
))
return figure
# Update worst table
@app.callback(
Output(component_id='worst_table', component_property='data'),
[Input(component_id='personalization_table', component_property='data'),
Input(component_id='stat_table', component_property='data')],
State(component_id='worst_table', component_property='data')
)
def update_output_div(personalization, stat, rows):
dff = pd.DataFrame(stat)
ev = float(dff.iloc[1, 1].strip('$'))
sd = float(dff.iloc[4, 1].strip('$'))
dff_personalization = pd.DataFrame(personalization)
hours = dff_personalization.iloc[1, 1]
round_per_hour = dff_personalization.iloc[2, 1]
# Worst 1%
z = norm.ppf(0.01)
r = z * sd * (hours * round_per_hour) ** 0.5 + ev * (hours * round_per_hour)
rows[0]['return'] = f'${r:.2f}'
# Worst 5%
z = norm.ppf(0.05)
r = z * sd * (hours * round_per_hour) ** 0.5 + ev * (hours * round_per_hour)
rows[1]['return'] = f'${r:.2f}'
# Worst 10%
z = norm.ppf(0.1)
r = z * sd * (hours * round_per_hour) ** 0.5 + ev * (hours * round_per_hour)
rows[2]['return'] = f'${r:.2f}'
# Worst 50%
z = norm.ppf(0.5)
r = z * sd * (hours * round_per_hour) ** 0.5 + ev * (hours * round_per_hour)
rows[3]['return'] = f'${r:.2f}'
return rows
'''
# Testing - Check whether Store is okay
@app.callback(
Output(component_id='testing', component_property='children'),
Input(component_id='base', component_property='data')
)
def update_output_div(input_value):
return(input_value)
'''
if __name__ == '__main__':
app.run_server(debug=True)