dnautiyal/IntroToMLOps-Week1-StreamlitApp
0
1from datetime import date2from datetime import datetime3import re4 5import numpy as np 6import pandas as pd 7from PIL import Image8import plotly.express as px 9import plotly.graph_objects as go10import streamlit as st 11import time12 13from plotly.subplots import make_subplots14 15# Read CSV file into pandas and extract timestamp data16dfSentiment = pd.read_csv('sentiment_data.csv')### YOUR LINE OF CODE HERE17dfSentiment['timestamp'] = [datetime.strptime(dt, '%Y-%m-%d') for dt in dfSentiment['timestamp'].tolist()]18 19# Multi-select columns to build chart20col_list = dfSentiment.columns.values.tolist()### YOUR LINE OF CODE HERE #### Extract columns into a list21 22r_sentiment = re.compile(".*sentiment")23sentiment_cols = list(filter(r_sentiment.match, col_list))### YOUR LINE OF CODE HERE24 25r_post = re.compile(".*post")26post_list = list(filter(r_post.match, col_list))### YOUR LINE OF CODE HERE27 28r_perc= re.compile(".*perc")29perc_list = list(filter(r_perc.match, col_list))30 31r_close = re.compile(".*close")32close_list = list(filter(r_close.match, col_list))33 34r_volume = re.compile(".*volume")35volume_list = list(filter(r_volume.match, col_list))36 37sentiment_cols = sentiment_cols + post_list38stocks_cols = close_list + volume_list ### YOUR LINE OF CODE HERE39 40# Config for page41st.set_page_config(42 page_title= 'TSLA Sentiment Analyzer Using Huggingface and StreamLit App',### YOUR LINE OF CODE HERE43 page_icon='✅',44 layout='wide',45)46 47with st.sidebar:48 # FourthBrain logo to sidebar49 fourthbrain_logo = Image.open('./images/fourthbrain_logo.png')50 st.image([fourthbrain_logo], width=300)51 52 # Date selection filters53 start_date_filter = st.date_input(54 ### YOUR LINE OF CODE HERE55 'Start Date',56 min(dfSentiment['timestamp']),57 min_value=min(dfSentiment['timestamp']),58 max_value=max(dfSentiment['timestamp'])59 )60 61 62 end_date_filter = st.date_input(63 'End Date',64 max(dfSentiment['timestamp']),65 min_value=min(dfSentiment['timestamp']),66 max_value=max(dfSentiment['timestamp'])67 )68 69 sentiment_select = st.selectbox('Select Sentiment Data', sentiment_cols) ### YOUR LINE OF CODE HERE70 stock_select = st.selectbox('Select Stock Data', stocks_cols) ### YOUR LINE OF CODE HERE71 72# Banner with TSLA and Reddit images73tsla_logo = Image.open('./images/tsla_logo.png')### YOUR LINE OF CODE HERE74reddit_logo = Image.open('./images/reddit_logo.png')75st.image([tsla_logo, reddit_logo], width=200)76 77# dashboard title78### YOUR LINE OF CODE HERE79st.title('TSLA Dashboard')80 81## dataframe filter82# start date83dfSentiment = dfSentiment[dfSentiment['timestamp'] >= datetime(start_date_filter.year, start_date_filter.month, start_date_filter.day)]84 85# end date86dfSentiment = dfSentiment[dfSentiment['timestamp'] <= datetime(end_date_filter.year, end_date_filter.month, end_date_filter.day)]87dfSentiment = dfSentiment.reset_index(drop=True)88 89 90# creating a single-element container91placeholder = st.empty()### YOUR LINE OF CODE HERE92 93# near real-time / live feed simulation94for i in range(1, len(dfSentiment)-1):95 96 # creating KPIs97 last_close = dfSentiment['close'][i]98 last_close_lag1 = dfSentiment['close'][i-1]99 last_sentiment = dfSentiment['sentiment_score'][i] ### YOUR LINE OF CODE HERE100 last_sentiment_lag1 = dfSentiment['sentiment_score'][i-1]### YOUR LINE OF CODE HERE101 102 103 with placeholder.container():104 105 # create columns106 kpi1, kpi2 = st.columns(2)107 108 # fill in those three columns with respective metrics or KPIs109 kpi1.metric(110 label='Sentiment Score',111 value=round(last_sentiment, 3),112 delta=round(last_sentiment_lag1, 3),113 )114 115 kpi2.metric(116 label='Last Closing Price',117 ### YOUR LINE 1 OF CODE HERE118 ### YOUR LINE 2 OF CODE HERE119 value=round(last_close),120 delta=round(last_close - last_close_lag1)121 )122 123 124 # create two columns for charts125 fig_col1, fig_col2 = st.columns(2)126 127 with fig_col1:128 # Add traces129 fig=make_subplots(specs=[[{"secondary_y":True}]])130 131 132 fig.add_trace( 133 go.Scatter( 134 x=dfSentiment['timestamp'][0:i],135 y=dfSentiment[sentiment_select][0:i],136 name=sentiment_select,137 mode='lines', 138 hoverinfo='none', 139 ) 140 )141 142 if sentiment_select.startswith('perc') == True:143 yaxis_label = '% Change Sentiment'144 145 elif sentiment_select in sentiment_cols:146 yaxis_label = 'Sentiment Score'147 148 elif sentiment_select in post_list:149 yaxis_label = 'Volume'150 151 fig.layout.yaxis.title=yaxis_label152 153 if stock_select.startswith('perc') == True:154 fig.add_trace( 155 go.Scatter( 156 x=dfSentiment['timestamp'][0:i],157 y=dfSentiment[stock_select][0:i],158 name=stock_select,159 mode='lines', 160 hoverinfo='none', 161 yaxis='y2', 162 ) 163 )164 fig.layout.yaxis2.title='% Change Stock Price ($US)'165 166 elif stock_select == 'volume':167 fig.add_trace( 168 go.Scatter( 169 x=dfSentiment['timestamp'][0:i],170 y=dfSentiment[stock_select][0:i],171 name=stock_select,172 mode='lines', 173 hoverinfo='none', 174 yaxis='y2', 175 ) 176 )177 178 fig.layout.yaxis2.title="Shares Traded"179 180 181 else:182 fig.add_trace( 183 go.Scatter( 184 x=dfSentiment['timestamp'][0:i],185 y=dfSentiment[stock_select][0:i],186 name=stock_select,187 mode='lines', 188 hoverinfo='none', 189 yaxis='y2', 190 ) 191 )192 193 fig.layout.yaxis2.title='Stock Price ($USD)'194 195 196 fig.layout.xaxis.title='Timestamp'197 198 # write the figure throught streamlit199 ### YOUR LINE OF CODE HERE200 st.write(fig)201 202 203 st.markdown('### Detailed Data View')204 st.dataframe(dfSentiment.iloc[:, 1:][0:i])205 time.sleep(1)206 