Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 74cdd6d

Browse files
Add files via upload
1 parent a901c27 commit 74cdd6d

File tree

1 file changed

+82
-0
lines changed

1 file changed

+82
-0
lines changed

streamlit/sp500-app.py

Lines changed: 82 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,82 @@
1+
import streamlit as st
2+
import pandas as pd
3+
import base64
4+
import matplotlib.pyplot as plt
5+
import seaborn as sns
6+
import numpy as np
7+
import yfinance as yf
8+
9+
st.title('S&P 500 App')
10+
11+
st.markdown("""
12+
This app retrieves the list of the **S&P 500** (from Wikipedia) and its corresponding **stock closing price** (year-to-date)!
13+
* **Python libraries:** base64, pandas, streamlit, numpy, matplotlib, seaborn
14+
* **Data source:** [Wikipedia](https://www.wikipedia.org/).
15+
""")
16+
17+
st.sidebar.header('User Input Features')
18+
19+
# Web scraping of S&P 500 data
20+
#
21+
@st.cache
22+
def load_data():
23+
url = 'https://en.wikipedia.org/wiki/List_of_S%26P_500_companies'
24+
html = pd.read_html(url, header = 0)
25+
df = html[0]
26+
return df
27+
28+
df = load_data()
29+
sector = df.groupby('GICS Sector')
30+
31+
# Sidebar - Sector selection
32+
sorted_sector_unique = sorted( df['GICS Sector'].unique() )
33+
selected_sector = st.sidebar.multiselect('Sector', sorted_sector_unique, sorted_sector_unique)
34+
35+
# Filtering data
36+
df_selected_sector = df[ (df['GICS Sector'].isin(selected_sector)) ]
37+
38+
st.header('Display Companies in Selected Sector')
39+
st.write('Data Dimension: ' + str(df_selected_sector.shape[0]) + ' rows and ' + str(df_selected_sector.shape[1]) + ' columns.')
40+
st.dataframe(df_selected_sector)
41+
42+
# Download S&P500 data
43+
# https://discuss.streamlit.io/t/how-to-download-file-in-streamlit/1806
44+
def filedownload(df):
45+
csv = df.to_csv(index=False)
46+
b64 = base64.b64encode(csv.encode()).decode() # strings <-> bytes conversions
47+
href = f'<a href="data:file/csv;base64,{b64}" download="SP500.csv">Download CSV File</a>'
48+
return href
49+
50+
st.markdown(filedownload(df_selected_sector), unsafe_allow_html=True)
51+
52+
# https://pypi.org/project/yfinance/
53+
54+
data = yf.download(
55+
tickers = list(df_selected_sector[:10].Symbol),
56+
period = "ytd",
57+
interval = "1d",
58+
group_by = 'ticker',
59+
auto_adjust = True,
60+
prepost = True,
61+
threads = True,
62+
proxy = None
63+
)
64+
65+
# Plot Closing Price of Query Symbol
66+
def price_plot(symbol):
67+
df = pd.DataFrame(data[symbol].Close)
68+
df['Date'] = df.index
69+
plt.fill_between(df.Date, df.Close, color='skyblue', alpha=0.3)
70+
plt.plot(df.Date, df.Close, color='skyblue', alpha=0.8)
71+
plt.xticks(rotation=90)
72+
plt.title(symbol, fontweight='bold')
73+
plt.xlabel('Date', fontweight='bold')
74+
plt.ylabel('Closing Price', fontweight='bold')
75+
return st.pyplot()
76+
77+
num_company = st.sidebar.slider('Number of Companies', 1, 5)
78+
79+
if st.button('Show Plots'):
80+
st.header('Stock Closing Price')
81+
for i in list(df_selected_sector.Symbol)[:num_company]:
82+
price_plot(i)

0 commit comments

Comments
 (0)