vsumm/tesla-sentiment-analysis
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")17dfSentiment['timestamp'] = [datetime.strptime(dt, '%Y-%m-%d') for dt in dfSentiment['timestamp'].tolist()]18 19# Multi-select columns to build chart20col_list = dfSentiment.columns.tolist()21 22r_sentiment = re.compile(".*sentiment")23sentiment_cols = list(filter(r_sentiment.match, col_list))24 25r_post = re.compile(".*post")26post_list = list(filter(r_post.match, col_list))27 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_list39 40# Config for page41st.set_page_config(42 page_title= 'TSLA Bot',43 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 'Start Date',55 min(dfSentiment['timestamp']),56 min_value=min(dfSentiment['timestamp']),57 max_value=max(dfSentiment['timestamp'])58 )59 60 61 end_date_filter = st.date_input(62 'End Date',63 max(dfSentiment['timestamp']),64 min_value=min(dfSentiment['timestamp']),65 max_value=max(dfSentiment['timestamp'])66 )67 68 sentiment_select = st.selectbox('Select Sentiment/Reddit Data', sentiment_cols)69 stock_select = st.selectbox('Select Stock Data', stocks_cols)70 71# Banner with TSLA and Reddit images72tsla_logo = Image.open('./images/tsla_logo.png')73reddit_logo = Image.open('./images/reddit_logo.png')74st.image([tsla_logo, reddit_logo], width=200)75 76# dashboard title77st.title('Vir\'s Sentiment Analysis for Tesla Stock Price')78 79## dataframe filter80# start date81dfSentiment = dfSentiment[dfSentiment['timestamp'] >= datetime(start_date_filter.year, start_date_filter.month, start_date_filter.day)]82 83# end date84dfSentiment = dfSentiment[dfSentiment['timestamp'] <= datetime(end_date_filter.year, end_date_filter.month, end_date_filter.day)]85dfSentiment = dfSentiment.reset_index(drop=True)86 87 88# creating a single-element container89placeholder = st.empty()90 91# near real-time / live feed simulation92for i in range(1, len(dfSentiment)-1):93 94 # creating KPIs95 last_close = dfSentiment['close'][i]96 last_close_lag1 = dfSentiment['close'][i-1]97 last_sentiment = dfSentiment['sentiment_score'][i]98 last_sentiment_lag1 = dfSentiment['sentiment_score'][i-1]99 100 101 with placeholder.container():102 103 # create columns104 kpi1, kpi2, kpi3 = st.columns(3)105 106 # fill in those three columns with respective metrics or KPIs107 kpi1.metric(108 label='Sentiment Score',109 value=round(last_sentiment, 3),110 delta=round(last_sentiment_lag1, 3),111 )112 113 kpi2.metric(114 label='Last Closing Price',115 value=round(last_close),116 delta=round(last_close - last_close_lag1)117 ) 118 119 # create two columns for charts120 fig_col1, fig_col2 = st.columns(2)121 122 with fig_col1:123 # Add traces124 fig=make_subplots(specs=[[{"secondary_y":True}]])125 126 fig.add_trace( 127 go.Scatter( 128 x=dfSentiment['timestamp'][0:i],129 y=dfSentiment[sentiment_select][0:i],130 name=sentiment_select,131 mode='lines', 132 hoverinfo='none', 133 ) 134 )135 136 if sentiment_select.startswith('perc') == True:137 yaxis_label = '% Change Sentiment'138 139 elif sentiment_select in sentiment_cols:140 yaxis_label = 'Sentiment Score'141 142 elif sentiment_select in post_list:143 yaxis_label = 'Volume'144 145 fig.layout.yaxis.title=yaxis_label146 147 if stock_select.startswith('perc') == True:148 fig.add_trace( 149 go.Scatter( 150 x=dfSentiment['timestamp'][0:i],151 y=dfSentiment[stock_select][0:i],152 name=stock_select,153 mode='lines', 154 hoverinfo='none', 155 yaxis='y2', 156 ) 157 )158 fig.layout.yaxis2.title='% Change Stock Price ($US)'159 160 elif stock_select == 'volume':161 fig.add_trace( 162 go.Scatter( 163 x=dfSentiment['timestamp'][0:i],164 y=dfSentiment[stock_select][0:i],165 name=stock_select,166 mode='lines', 167 hoverinfo='none', 168 yaxis='y2', 169 ) 170 )171 172 fig.layout.yaxis2.title="Shares Traded"173 174 175 else:176 fig.add_trace( 177 go.Scatter( 178 x=dfSentiment['timestamp'][0:i],179 y=dfSentiment[stock_select][0:i],180 name=stock_select,181 mode='lines', 182 hoverinfo='none', 183 yaxis='y2', 184 ) 185 )186 187 fig.layout.yaxis2.title='Stock Price ($USD)'188 189 190 fig.layout.xaxis.title='Timestamp'191 192 # write the figure throught streamlit193 st.write(fig)194 195 196 st.markdown('### Detailed Data View')197 st.dataframe(dfSentiment.iloc[:, 1:][0:i])198 time.sleep(1)199 