James McCool commited on
Commit
2d7ef5b
·
1 Parent(s): df39e5b

Initial commit and modernize

Browse files
.streamlit/secrets.toml ADDED
@@ -0,0 +1 @@
 
 
1
+ mongo_uri = "mongodb+srv://multichem:Xr1q5wZdXPbxdUmJ@testcluster.lgwtp5i.mongodb.net/?retryWrites=true&w=majority&appName=TestCluster"
Dockerfile CHANGED
@@ -5,11 +5,23 @@ WORKDIR /app
5
  RUN apt-get update && apt-get install -y \
6
  build-essential \
7
  curl \
 
8
  git \
9
  && rm -rf /var/lib/apt/lists/*
10
 
11
  COPY requirements.txt ./
12
  COPY src/ ./src/
 
 
 
 
 
 
 
 
 
 
 
13
 
14
  RUN pip3 install -r requirements.txt
15
 
@@ -17,4 +29,4 @@ EXPOSE 8501
17
 
18
  HEALTHCHECK CMD curl --fail http://localhost:8501/_stcore/health
19
 
20
- ENTRYPOINT ["streamlit", "run", "src/streamlit_app.py", "--server.port=8501", "--server.address=0.0.0.0"]
 
5
  RUN apt-get update && apt-get install -y \
6
  build-essential \
7
  curl \
8
+ software-properties-common \
9
  git \
10
  && rm -rf /var/lib/apt/lists/*
11
 
12
  COPY requirements.txt ./
13
  COPY src/ ./src/
14
+ COPY .streamlit/ ./.streamlit/
15
+
16
+
17
+ ENV MONGO_URI="mongodb+srv://multichem:Xr1q5wZdXPbxdUmJ@testcluster.lgwtp5i.mongodb.net/?retryWrites=true&w=majority&appName=TestCluster"
18
+ RUN useradd -m -u 1000 user
19
+ USER user
20
+ ENV HOME=/home/user\
21
+ PATH=/home/user/.local/bin:$PATH
22
+ WORKDIR $HOME/app
23
+ RUN pip install --no-cache-dir --upgrade pip
24
+ COPY --chown=user . $HOME/app
25
 
26
  RUN pip3 install -r requirements.txt
27
 
 
29
 
30
  HEALTHCHECK CMD curl --fail http://localhost:8501/_stcore/health
31
 
32
+ ENTRYPOINT ["streamlit", "run", "src/application.py", "--server.port=8501", "--server.address=0.0.0.0"]
requirements.txt CHANGED
@@ -1,3 +1,7 @@
1
- altair
2
- pandas
3
- streamlit
 
 
 
 
 
1
+ streamlit
2
+ matplotlib
3
+ pymongo
4
+ pulp
5
+ docker
6
+ plotly
7
+ scipy
src/database.py ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ from pymongo import MongoClient
3
+
4
+ @st.cache_resource
5
+ def init_conn():
6
+
7
+ uri = st.secrets['mongo_uri']
8
+ client = MongoClient(uri, retryWrites=True, serverSelectionTimeoutMS=100000)
9
+ dfs_db = client["NCAAF_Database"]
10
+ props_db = client["Props_DB"]
11
+
12
+ return props_db, dfs_db
13
+
14
+ props_db, dfs_db = init_conn()
src/streamlit_app.py CHANGED
@@ -1,40 +1,123 @@
1
- import altair as alt
2
  import numpy as np
3
  import pandas as pd
4
- import streamlit as st
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5
 
6
- """
7
- # Welcome to Streamlit!
8
-
9
- Edit `/streamlit_app.py` to customize this app to your heart's desire :heart:.
10
- If you have any questions, checkout our [documentation](https://docs.streamlit.io) and [community
11
- forums](https://discuss.streamlit.io).
12
-
13
- In the meantime, below is an example of what you can do with just a few lines of code:
14
- """
15
-
16
- num_points = st.slider("Number of points in spiral", 1, 10000, 1100)
17
- num_turns = st.slider("Number of turns in spiral", 1, 300, 31)
18
-
19
- indices = np.linspace(0, 1, num_points)
20
- theta = 2 * np.pi * num_turns * indices
21
- radius = indices
22
-
23
- x = radius * np.cos(theta)
24
- y = radius * np.sin(theta)
25
-
26
- df = pd.DataFrame({
27
- "x": x,
28
- "y": y,
29
- "idx": indices,
30
- "rand": np.random.randn(num_points),
31
- })
32
-
33
- st.altair_chart(alt.Chart(df, height=700, width=700)
34
- .mark_point(filled=True)
35
- .encode(
36
- x=alt.X("x", axis=None),
37
- y=alt.Y("y", axis=None),
38
- color=alt.Color("idx", legend=None, scale=alt.Scale()),
39
- size=alt.Size("rand", legend=None, scale=alt.Scale(range=[1, 150])),
40
- ))
 
1
+ import streamlit as st
2
  import numpy as np
3
  import pandas as pd
4
+ from database import props_db, dfs_db
5
+ st.set_page_config(layout="wide")
6
+
7
+ game_format = {'Win%': '{:.2%}', 'Vegas': '{:.2%}', 'Win% Diff': '{:.2%}'}
8
+ american_format = {'First Inning Lead Percentage': '{:.2%}', 'Fifth Inning Lead Percentage': '{:.2%}'}
9
+
10
+ @st.cache_resource(ttl=600)
11
+ def init_baselines():
12
+ collection = dfs_db["NCAAF_GameModel"]
13
+ cursor = collection.find()
14
+ raw_display = pd.DataFrame(list(cursor))
15
+ game_model = raw_display[['Team', 'Opp', 'Win%', 'Vegas', 'Win% Diff', 'Win Line', 'Vegas Line', 'Line Diff', 'PD Spread', 'Vegas Spread', 'Spread Diff', 'O/U']]
16
+ game_model = game_model.replace('', np.nan)
17
+ game_model = game_model.sort_values(by='O/U', ascending=False)
18
+ game_model.loc[:, ~game_model.columns.isin(['Team', 'Opp'])] = game_model.loc[:, ~game_model.columns.isin(['Team', 'Opp'])].apply(pd.to_numeric)
19
+
20
+ collection = props_db["NCAAF_Props"]
21
+ cursor = collection.find()
22
+
23
+ raw_display = pd.DataFrame(list(cursor))
24
+ market_props = raw_display[['Name', 'Position', 'Projection', 'PropType', 'OddsType', 'over_pay', 'under_pay']]
25
+ market_props['over_prop'] = market_props['Projection']
26
+ market_props['over_line'] = market_props['over_pay'].apply(lambda x: (x - 1) * 100 if x >= 2.0 else -100 / (x - 1))
27
+ market_props['under_prop'] = market_props['Projection']
28
+ market_props['under_line'] = market_props['under_pay'].apply(lambda x: (x - 1) * 100 if x >= 2.0 else -100 / (x - 1))
29
+
30
+ return game_model, market_props
31
+
32
+ def convert_df_to_csv(df):
33
+ return df.to_csv().encode('utf-8')
34
+
35
+ def calculate_no_vig(row):
36
+ def implied_probability(american_odds):
37
+ if american_odds < 0:
38
+ return (-american_odds) / ((-american_odds) + 100)
39
+ else:
40
+ return 100 / (american_odds + 100)
41
+
42
+ over_line = row['over_line']
43
+ under_line = row['under_line']
44
+ over_prop = row['over_prop']
45
+
46
+ over_prob = implied_probability(over_line)
47
+ under_prob = implied_probability(under_line)
48
+
49
+ total_prob = over_prob + under_prob
50
+ no_vig_prob = (over_prob / total_prob + 0.5) * over_prop
51
+
52
+ return no_vig_prob
53
+
54
+ prop_table_options = ['NCAAF_GAME_PLAYER_PASSING_ATTEMPTS', 'NCAAF_GAME_PLAYER_PASSING_COMPLETIONS', 'NCAAF_GAME_PLAYER_PASSING_INTERCEPTIONS',
55
+ 'NCAAF_GAME_PLAYER_PASSING_RUSHING_YARDS', 'NCAAF_GAME_PLAYER_PASSING_TOUCHDOWNS', 'NCAAF_GAME_PLAYER_PASSING_YARDS',
56
+ 'NCAAF_GAME_PLAYER_RECEIVING_RECEPTIONS', 'NCAAF_GAME_PLAYER_RECEIVING_TOUCHDOWNS', 'NCAAF_GAME_PLAYER_RECEIVING_YARDS',
57
+ 'NCAAF_GAME_PLAYER_RUSHING_ATTEMPTS', 'NCAAF_GAME_PLAYER_RUSHING_RECEIVING_YARDS', 'NCAAF_GAME_PLAYER_RUSHING_TOUCHDOWNS',
58
+ 'NCAAF_GAME_PLAYER_RUSHING_YARDS', 'NCAAF_GAME_PLAYER_SCORE_TOUCHDOWN']
59
+ prop_format = {'L3 Success': '{:.2%}', 'L6_Success': '{:.2%}', 'L10_success': '{:.2%}', 'Trending Over': '{:.2%}', 'Trending Under': '{:.2%}',
60
+ 'Implied Over': '{:.2%}', 'Implied Under': '{:.2%}', 'Over Edge': '{:.2%}', 'Under Edge': '{:.2%}'}
61
+
62
+ game_model, market_props = init_baselines()
63
+
64
+ tab1, tab2 = st.tabs(["Game Model", "Prop Market"])
65
+
66
+ with tab1:
67
+ if st.button("Reset Data", key='reset1'):
68
+ st.cache_data.clear()
69
+ game_model, market_props = init_baselines()
70
+ line_var1 = st.radio('How would you like to display odds?', options = ['Percentage', 'American'], key='line_var1')
71
+ team_frame = game_model
72
+ if line_var1 == 'Percentage':
73
+ team_frame = team_frame[['Team', 'Opp', 'Win%', 'Vegas', 'Win% Diff', 'PD Spread', 'Vegas Spread', 'Spread Diff']]
74
+ team_frame = team_frame.set_index('Team')
75
+ try:
76
+ st.dataframe(team_frame.style.background_gradient(axis=0).background_gradient(cmap='RdYlGn').background_gradient(cmap='RdYlGn_r', subset=['PD Spread', 'Vegas Spread', 'Spread Diff']).format(game_format, precision=2), use_container_width = True)
77
+ except:
78
+ st.dataframe(team_frame.style.background_gradient(axis=0).background_gradient(cmap='RdYlGn').background_gradient(cmap='RdYlGn_r', subset=['PD Spread', 'Vegas Spread']).format(precision=2), use_container_width = True)
79
+ if line_var1 == 'American':
80
+ team_frame = team_frame[['Team', 'Opp', 'Win Line', 'Vegas Line', 'Line Diff', 'PD Spread', 'Vegas Spread', 'Spread Diff']]
81
+ team_frame = team_frame.set_index('Team')
82
+ st.dataframe(team_frame.style.background_gradient(axis=0).background_gradient(cmap='RdYlGn_r').format(precision=2), height = 1000, use_container_width = True)
83
+
84
+ st.download_button(
85
+ label="Export Team Model",
86
+ data=convert_df_to_csv(team_frame),
87
+ file_name='NCAAF_team_betting_export.csv',
88
+ mime='text/csv',
89
+ key='team_export',
90
+ )
91
+
92
+ with tab2:
93
+ if st.button("Reset Data", key='reset4'):
94
+ st.cache_data.clear()
95
+ game_model, market_props = init_baselines()
96
+ market_type = st.selectbox('Select type of prop are you wanting to view', options = prop_table_options, key = 'market_type_key')
97
+ disp_market = market_props.copy()
98
+ disp_market = disp_market[disp_market['PropType'] == market_type]
99
+ disp_market['No_Vig_Prop'] = disp_market.apply(calculate_no_vig, axis=1)
100
+ fanduel_frame = disp_market[disp_market['OddsType'] == 'FANDUEL']
101
+ fanduel_dict = dict(zip(fanduel_frame['Name'], fanduel_frame['No_Vig_Prop']))
102
+ draftkings_frame = disp_market[disp_market['OddsType'] == 'DRAFTKINGS']
103
+ draftkings_dict = dict(zip(draftkings_frame['Name'], draftkings_frame['No_Vig_Prop']))
104
+ mgm_frame = disp_market[disp_market['OddsType'] == 'MGM']
105
+ mgm_dict = dict(zip(mgm_frame['Name'], mgm_frame['No_Vig_Prop']))
106
+ bet365_frame = disp_market[disp_market['OddsType'] == 'BET_365']
107
+ bet365_dict = dict(zip(bet365_frame['Name'], bet365_frame['No_Vig_Prop']))
108
+
109
+ disp_market['FANDUEL'] = disp_market['Name'].map(fanduel_dict)
110
+ disp_market['DRAFTKINGS'] = disp_market['Name'].map(draftkings_dict)
111
+ disp_market['MGM'] = disp_market['Name'].map(mgm_dict)
112
+ disp_market['BET365'] = disp_market['Name'].map(bet365_dict)
113
+
114
+ disp_market = disp_market[['Name', 'Position','FANDUEL', 'DRAFTKINGS', 'MGM', 'BET365']]
115
+ disp_market = disp_market.drop_duplicates(subset=['Name'], keep='first', ignore_index=True)
116
 
117
+ st.dataframe(disp_market.style.background_gradient(axis=1, subset=['FANDUEL', 'DRAFTKINGS', 'MGM', 'BET365'], cmap='RdYlGn').format(prop_format, precision=2), height = 1000, use_container_width = True)
118
+ st.download_button(
119
+ label="Export Market Props",
120
+ data=convert_df_to_csv(disp_market),
121
+ file_name='NCAAF_market_props_export.csv',
122
+ mime='text/csv',
123
+ )