-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstreamlit_app.py
290 lines (252 loc) · 5.41 KB
/
streamlit_app.py
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
import streamlit as st
import yfinance as yf
import pandas as pd
import altair as alt
st.set_page_config(
page_title="Stock peer group analysis",
page_icon=":chart_with_upwards_trend:"
)
"""
# :chart_with_upwards_trend: Stock peer group analysis
Easily compare stocks against others in their peer group.
"""
STOCKS = [
"AAPL",
"ABBV",
"ACN",
"ADBE",
"ADP",
"AMD",
"AMGN",
"AMT",
"AMZN",
"APD",
"AVGO",
"AXP",
"BA",
"BK",
"BKNG",
"BMY",
"BRK.B",
"BSX",
"C",
"CAT",
"CI",
"CL",
"CMCSA",
"COST",
"CRM",
"CSCO",
"CVX",
"DE",
"DHR",
"DIS",
"DUK",
"ELV",
"EOG",
"EQR",
"FDX",
"GD",
"GE",
"GILD",
"GOOG",
"GOOGL",
"HD",
"HON",
"HUM",
"IBM",
"ICE",
"INTC",
"ISRG",
"JNJ",
"JPM",
"KO",
"LIN",
"LLY",
"LMT",
"LOW",
"MA",
"MCD",
"MDLZ",
"META",
"MMC",
"MO",
"MRK",
"MSFT",
"NEE",
"NFLX",
"NKE",
"NOW",
"NVDA",
"ORCL",
"PEP",
"PFE",
"PG",
"PLD",
"PM",
"PSA",
"REGN",
"RTX",
"SBUX",
"SCHW",
"SLB",
"SO",
"SPGI",
"T",
"TJX",
"TMO",
"TSLA",
"TXN",
"UNH",
"UNP",
"UPS",
"V",
"VZ",
"WFC",
"WM",
"WMT",
"XOM",
]
DEFAULT_STOCKS = ["AAPL", "MSFT", "GOOGL", "NVDA", "AMZN", "TSLA", "META"]
def stocks_to_str(stocks):
return ",".join(stocks)
if "tickers_input" not in st.session_state:
st.session_state.tickers_input = st.query_params.get(
"stocks", stocks_to_str(DEFAULT_STOCKS)
).split(",")
# Callback to update query param when input changes
def update_query_param():
if st.session_state.tickers_input:
st.query_params["stocks"] = stocks_to_str(
st.session_state.tickers_input)
else:
st.query_params.pop("stocks", None)
# Input for stock tickers
tickers = st.multiselect(
"Stock tickers",
options=sorted(set(STOCKS) | set(st.session_state.tickers_input)),
default=st.session_state.tickers_input,
accept_new_options=True,
)
tickers = [t.upper() for t in tickers]
# Update query param when text input changes
if tickers:
st.query_params["stocks"] = stocks_to_str(tickers)
else:
# Clear the param if input is empty
st.query_params.pop("stocks", None)
if not tickers:
st.stop()
# Time horizon selector
horizon_map = {
"1 Week": "1wk",
"1 Month": "1mo",
"3 Months": "3mo",
"6 Months": "6mo",
"1 Year": "1y",
"5 Years": "5y",
"10 Years": "10y",
"20 Years": "20y",
}
horizon = st.segmented_control(
"Time horizon",
options=list(horizon_map.keys()),
default="3 Months",
)
@st.cache_resource(show_spinner=False)
def load_data(tickers, period):
data = pd.DataFrame()
for ticker in tickers:
stock = yf.Ticker(ticker)
hist = stock.history(period=period)["Close"]
data[ticker] = hist
return data
# Load the data
data = load_data(tickers, horizon_map[horizon])
if not len(data):
st.error("No data")
st.stop()
# Normalize prices (start at 1)
normalized = data.div(data.iloc[0])
""
""
# Plot 1: Normalized prices
"""
### Normalized stock prices
"""
chart1 = (
alt.Chart(
normalized.reset_index().melt(
id_vars=["Date"], var_name="Stock", value_name="Normalized price"
)
)
.mark_line()
.encode(
x="Date:T",
y="Normalized price:Q",
color=alt.Color("Stock:N", legend=alt.Legend(orient="bottom")),
)
.properties(height=400)
)
st.altair_chart(chart1, use_container_width=True)
""
""
# Plot individual stock vs peer average
"""
### Individual stocks vs peer average
For the analysis below, the "peer average" when analyzing stock X always
excludes X itself.
"""
if len(tickers) <= 1:
st.warning("Pick 2 or more tickers to compare them")
st.stop()
tabs = st.tabs(["Delta", "Price"])
for ticker in tickers:
# Calculate peer average (excluding current stock)
peers = normalized.drop(columns=[ticker])
peer_avg = peers.mean(axis=1)
# Create Delta chart
plot_data = pd.DataFrame(
{
"Date": normalized.index,
"Delta": normalized[ticker] - peer_avg,
}
)
chart = (
alt.Chart(plot_data)
.mark_area()
.encode(
x="Date:T",
y="Delta:Q",
)
.properties(title=f"{ticker} minus peer average", height=300)
)
tabs[0].write("")
tabs[0].altair_chart(chart, use_container_width=True)
# Create DataFrame with peer average.
plot_data = pd.DataFrame(
{
"Date": normalized.index,
"Stock price": normalized[ticker],
"Peer average": peer_avg,
}
).melt(id_vars=["Date"], var_name="Series", value_name="Price")
chart = (
alt.Chart(plot_data)
.mark_line()
.encode(
x="Date:T",
y="Price:Q",
color=alt.Color(
"Series:N",
scale=alt.Scale(
domain=["Stock price", "Peer average"], range=["red", "gray"]
),
legend=alt.Legend(orient="bottom"),
),
tooltip=["Date", "Series", "Price"],
)
.properties(title=f"{ticker} vs Peer average", height=300)
)
tabs[1].write("")
tabs[1].altair_chart(chart, use_container_width=True)