-
Notifications
You must be signed in to change notification settings - Fork 1
/
app.py
212 lines (164 loc) · 6.73 KB
/
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
import starfishX as sx
import pandas as pd
import matplotlib.pyplot as plt
import streamlit as st
from PIL import Image
import base64
from bs4 import BeautifulSoup
import requests
import json
#---------------------------------#
# Page layout
## Page expands to full width
st.set_page_config(layout="wide")
my_page = st.sidebar.radio('Page Navigation', ['Thai Stock Exchange App', 'Cryptocurrency Price App'])
if my_page == 'Thai Stock Exchange App':
image = Image.open('logo.png')
st.image(image, width = 250)
st.write("""
# Thai Stock Exchange App
""")
# Create get_stock function to pull stock data
def get_stock(stock, startdate='2016-01-01'):
df = sx.loadHistData(stock, start=startdate,
OHLC=True, Volume=True)
return df
stock_symbol = st.text_input("Stock Symbol (ex. AOT, PTT, etc.)", 'AOT')
date = st.selectbox('select startdate', [2010, 2011, 2012, 2013, 2014,
2015, 2016, 2017, 2018, 2019, 2020])
start_date = f'{date}-01-01'
try:
df = get_stock(stock=stock_symbol, startdate=start_date)
st.dataframe(df)
st.dataframe(df.describe())
# Stock symbol
st.write(stock_symbol)
# Closing Price
st.write("""
## Closing Price
""")
st.line_chart(df.CLOSE)
# Volume Price
st.write("""
## Volume
""")
st.line_chart(df.VOLUME)
# display income statement
st.write("""
## Income Statement
""")
st.dataframe(sx.getIncomeStatement(stock_symbol))
# display financial ratio
st.write("""
## Financial ratio
""")
st.dataframe(sx.getFinanceRatio(stock_symbol))
except:
st.error('The data of this stock is currently not available')
st.error('ไม่พบข้อมูล')
elif my_page == 'Cryptocurrency Price App':
image = Image.open('logo2.jpeg')
st.image(image, width = 500)
st.title('Crypto Price App')
st.markdown("""
This app retrieves cryptocurrency prices for the top 100 cryptocurrency from the **CoinMarketCap**!
""")
#---------------------------------#
# About
expander_bar = st.beta_expander("About")
expander_bar.markdown("""
* **Python libraries:** base64, pandas, streamlit, numpy, matplotlib, seaborn, BeautifulSoup, requests, json, time
* **Data source:** [CoinMarketCap](http://coinmarketcap.com).
""")
#---------------------------------#
# Page layout (continued)
## Divide page to 3 columns (col1 = sidebar, col2 and col3 = page contents)
col1 = st.sidebar
col2, col3 = st.beta_columns((2,1))
#---------------------------------#
# Sidebar + Main panel
col1.header('Input Options')
## Sidebar - Currency price unit
currency_price_unit = col1.selectbox('Select currency for price', ('USD','BTC','ETH'))
# Web scraping of CoinMarketCap data
@st.cache
def load_data():
cmc = requests.get('https://coinmarketcap.com')
soup = BeautifulSoup(cmc.content, 'html.parser')
data = soup.find('script', id='__NEXT_DATA__', type='application/json')
coins = {}
coin_data = json.loads(data.contents[0])
listings = coin_data['props']['initialState']['cryptocurrency']['listingLatest']['data']
for i in listings:
coins[str(i['id'])] = i['slug']
coin_name = []
coin_symbol = []
marketCap = []
percentChange24h = []
percentChange7d = []
price = []
volume24h = []
for i in listings:
coin_name.append(i['slug'])
coin_symbol.append(i['symbol'])
price.append(i['quote'][currency_price_unit]['price'])
percentChange24h.append(i['quote'][currency_price_unit]['percentChange24h'])
percentChange7d.append(i['quote'][currency_price_unit]['percentChange7d'])
marketCap.append(i['quote'][currency_price_unit]['marketCap'])
volume24h.append(i['quote'][currency_price_unit]['volume24h'])
df = pd.DataFrame(columns=['coin_name', 'coin_symbol', 'marketCap', 'percentChange24h', 'percentChange7d', 'price', 'volume24h'])
df['coin_name'] = coin_name
df['coin_symbol'] = coin_symbol
df['price'] = price
df['percentChange24h'] = percentChange24h
df['percentChange7d'] = percentChange7d
df['marketCap'] = marketCap
df['volume24h'] = volume24h
return df
df = load_data()
## Sidebar - Cryptocurrency selections
sorted_coin = sorted(df['coin_symbol'])
selected_coin = col1.multiselect('Cryptocurrency', sorted_coin, sorted_coin)
df_selected_coin = df[(df['coin_symbol'].isin(selected_coin))] # Filtering data
## Sidebar - Number of coins to display
num_coin = col1.slider('Display Top N Coins', 1, 100, 100)
df_coins = df_selected_coin[:num_coin]
## Sidebar - Percent change timeframe
percent_timeframe = col1.selectbox('Percent change time frame',
['7d','24h', '1h'])
percent_dict = {"7d":'percentChange7d',"24h":'percentChange24h'}
selected_percent_timeframe = percent_dict[percent_timeframe]
sort_values = col1.selectbox('Sort values?', ['Yes', 'No'])
col2.subheader('Price Data of Selected Cryptocurrency')
col2.write('Data Dimension: ' + str(df_selected_coin.shape[0]) + ' rows and ' + str(df_selected_coin.shape[1]) + ' columns.')
col2.dataframe(df_coins)
def filedownload(df):
csv = df.to_csv(index=False)
b64 = base64.b64encode(csv.encode()).decode() # strings <-> bytes conversions
href = f'<a href="data:file/csv;base64,{b64}" download="crypto.csv">Download CSV File</a>'
return href
col2.markdown(filedownload(df_selected_coin), unsafe_allow_html=True)
col2.subheader('Table of % Price Change')
df_change = pd.concat([df_coins.coin_symbol, df_coins.percentChange24h, df_coins.percentChange7d], axis=1)
df_change = df_change.set_index('coin_symbol')
df_change['positive_percentChange24h'] = df_change['percentChange24h'] > 0
df_change['positive_percentChange7d'] = df_change['percentChange7d'] > 0
col2.dataframe(df_change)
# Conditional creation of Bar plot (time frame)
col3.subheader('Bar plot of % Price Change')
if percent_timeframe == '7d':
if sort_values == 'Yes':
df_change = df_change.sort_values(by=['percentChange7d'])
col3.write('*7 days period*')
plt.figure(figsize=(5,25))
plt.subplots_adjust(top = 1, bottom = 0)
df_change['percentChange7d'].plot(kind='barh', color=df_change.positive_percentChange7d.map({True: 'g', False: 'r'}))
col3.pyplot(plt)
elif percent_timeframe == '24h':
if sort_values == 'Yes':
df_change = df_change.sort_values(by=['percentChange24h'])
col3.write('*24 hour period*')
plt.figure(figsize=(5,25))
plt.subplots_adjust(top = 1, bottom = 0)
df_change['percentChange24h'].plot(kind='barh', color=df_change.positive_percentChange24h.map({True: 'g', False: 'r'}))
col3.pyplot(plt)