muzammil-eds commited on
Commit
465628b
1 Parent(s): 8a7ffdd

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +186 -60
app.py CHANGED
@@ -1,25 +1,84 @@
 
 
1
  import streamlit as st
2
  import yfinance as yf
3
  import pandas as pd
4
  from langchain.agents import create_csv_agent, AgentType
 
 
 
5
  from htmlTemplates import css, user_template, bot_template
6
 
7
- from langchain.llms import GPT4All
8
- from langchain.callbacks.streaming_stdout import StreamingStdOutCallbackHandler
 
9
 
10
- local_path = (
11
- "tinyllama-1.1b-chat-v0.3.Q2_K.gguf" # replace with your desired local file path
 
 
12
  )
13
 
14
- # Callbacks support token-wise streaming
15
- callbacks = [StreamingStdOutCallbackHandler()]
16
 
17
- # Verbose is required to pass to the callback manager
18
- llm = GPT4All(model=local_path, callbacks=callbacks, verbose=True)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
19
 
20
 
21
  def init_ses_states():
22
  st.session_state.setdefault('chat_history', [])
 
23
 
24
 
25
  def relative_returns(df):
@@ -32,71 +91,138 @@ def display_convo():
32
  with st.container():
33
  for i, message in enumerate(reversed(st.session_state.chat_history)):
34
  if i % 2 == 0:
35
- st.markdown(bot_template.replace("{{MSG}}", message), unsafe_allow_html=True)
36
  else:
37
  st.markdown(user_template.replace("{{MSG}}", message), unsafe_allow_html=True)
38
 
39
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
40
  def main():
41
  st.set_page_config(page_title="Stock Price AI Bot", page_icon=":chart:")
42
  st.write(css, unsafe_allow_html=True)
 
43
  init_ses_states()
44
  st.title("Stock Price AI Bot")
45
  st.caption("Visualizations and OpenAI Chatbot for Multiple Stocks Over A Specified Period")
46
 
 
47
  with st.sidebar:
48
- asset_tickers = sorted(
49
- ['DOW', 'NVDA', 'TSL', 'GOOGL', 'AMZN', 'AI', 'NIO', 'LCID', 'F', 'LYFY', 'AAPL', 'MSFT', 'BTC-USD',
50
- 'ETH-USD'])
51
- asset_dropdown = st.multiselect('Pick Assets:', asset_tickers)
52
- metric_tickers = ['Adj. Close', 'Relative Returns']
53
- metric_dropdown = st.selectbox("Metric", metric_tickers)
54
- viz_tickers = ['Line Chart', 'Area Chart']
55
- viz_dropdown = st.multiselect("Pick Charts:", viz_tickers)
56
- start = st.date_input('Start', value=pd.to_datetime('2023-01-01'))
57
- end = st.date_input('End', value=pd.to_datetime('today'))
58
-
59
- if len(asset_dropdown) > 0:
60
- df = yf.download(asset_dropdown, start, end)['Adj Close']
61
- if metric_dropdown == 'Relative Returns':
62
- df = relative_returns(df)
63
- if len(viz_dropdown) > 0:
64
- with st.expander("Data Visualizations", expanded=True):
65
- if "Line Chart" in viz_dropdown:
66
- st.line_chart(df)
67
- if "Area Chart" in viz_dropdown:
68
- st.area_chart(df)
69
-
70
- st.header("Chat with your Data")
71
- query = st.text_input("Enter a query:")
72
- chat_prompt = f'''
73
- You are an AI ChatBot intended to help with user stock data.
74
- \nDATA MODE: {metric_dropdown}
75
- \nSTOCKS: {asset_dropdown}
76
- \nTIME PERIOD: {start} to {end}
77
- \nCHAT HISTORY: {st.session_state.chat_history}
78
- \nUSER MESSAGE: {query}
79
- \nAI RESPONSE HERE:
80
- '''
81
-
82
- if st.button("Execute") and query:
83
- with st.spinner('Generating response...'):
84
- try:
85
- DF = pd.DataFrame(df)
86
- DF.to_csv('data.csv')
87
- agent = create_csv_agent(
88
- llm,
89
- 'data.csv',
90
- verbose=True,
91
- agent_type=AgentType.OPENAI_FUNCTIONS,
92
- )
93
- answer = agent.run(chat_prompt)
94
- st.session_state.chat_history.append(f"USER: {query}\n")
95
- st.session_state.chat_history.append(f"AI: {answer}\n")
96
- display_convo()
97
- except Exception as e:
98
- st.error(f"An error occurred: {str(e)}")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
99
 
100
 
101
  if __name__ == '__main__':
102
  main()
 
 
1
+ import os
2
+
3
  import streamlit as st
4
  import yfinance as yf
5
  import pandas as pd
6
  from langchain.agents import create_csv_agent, AgentType
7
+ import re
8
+ import sqlite3
9
+ from langchain.chat_models import ChatOpenAI
10
  from htmlTemplates import css, user_template, bot_template
11
 
12
+ # openai.api_key = os.environ("OPENAI_API_KEY") # vLLM server is not authenticated
13
+ os.environ['OPENAI_API_KEY'] = os.getenv('OPENAI_API_KEY')
14
+
15
 
16
+ llm = ChatOpenAI(
17
+ model='gpt-3.5-turbo',
18
+ max_tokens=500,
19
+ temperature=0.7,
20
  )
21
 
 
 
22
 
23
+ #
24
+ # class FinLLM(LLM):
25
+ #
26
+ # @property
27
+ # def _llm_type(self) -> str:
28
+ # return "custom"
29
+ #
30
+ # def _call(self, prompt: str, stop: Optional[List[str]] = None) -> str:
31
+ # out = g4f.ChatCompletion.create(
32
+ # model="gpt-3.5-turbo",
33
+ # messages=[{"role": "user", "content": prompt}],
34
+ # temperature=0.5, # You can adjust parameters as needed
35
+ # max_tokens=350 # Adjust the token limit as needed
36
+ # ) #
37
+ # if stop:
38
+ # stop_indexes = (out.find(s) for s in stop if s in out)
39
+ # min_stop = min(stop_indexes, default=-1)
40
+ # if min_stop > -1:
41
+ # out = out[:min_stop]
42
+ # return out
43
+ #
44
+ #
45
+ # llm = FinLLM()
46
+
47
+ def create_users_db():
48
+ with sqlite3.connect('MASTER.db') as conn:
49
+ cursor = conn.cursor()
50
+ cursor.execute("""
51
+ CREATE TABLE IF NOT EXISTS Users (
52
+ user_id INTEGER PRIMARY KEY AUTOINCREMENT,
53
+ email TEXT UNIQUE,
54
+ password TEXT
55
+ )
56
+ """)
57
+
58
+ def add_user_to_db(email, password):
59
+ with sqlite3.connect('MASTER.db') as conn:
60
+ cursor = conn.cursor()
61
+ try:
62
+ insert_query = "INSERT INTO Users (email, password) VALUES (?, ?)"
63
+ cursor.execute(insert_query, (email, password))
64
+ except sqlite3.IntegrityError as e:
65
+ # Handle specific error if the email already exists
66
+ print(f"Error: {e}")
67
+ return False
68
+ return True
69
+
70
+ def authenticate_user(email, password):
71
+ with sqlite3.connect('MASTER.db') as conn:
72
+ cursor = conn.cursor()
73
+ select_query = "SELECT * FROM Users WHERE email = ? AND password = ?"
74
+ cursor.execute(select_query, (email, password))
75
+ user = cursor.fetchone()
76
+ return user is not None
77
 
78
 
79
  def init_ses_states():
80
  st.session_state.setdefault('chat_history', [])
81
+ st.session_state.setdefault('user_authenticated', False)
82
 
83
 
84
  def relative_returns(df):
 
91
  with st.container():
92
  for i, message in enumerate(reversed(st.session_state.chat_history)):
93
  if i % 2 == 0:
94
+ st.markdown(bot_template.replace("{{MSG}}", message), unsafe_allow_html=True)
95
  else:
96
  st.markdown(user_template.replace("{{MSG}}", message), unsafe_allow_html=True)
97
 
98
 
99
+ def approve_password(password):
100
+ if len(password) >= 8 and re.search(r"(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[_@$#!?&*%])", password):
101
+ return True
102
+ return False
103
+
104
+
105
+ def approve_email(email):
106
+ email_regex = '^[a-zA-Z0-9]+[\._]?[a-zA-Z0-9]+[@]\w+[.]\w{2,3}$'
107
+ if re.search(email_regex, email):
108
+ return True
109
+ else:
110
+ return False
111
+
112
+
113
+ def user_authentication_tab():
114
+ with st.expander("User Authentication", expanded=True):
115
+ login_tab, create_account_tab = st.tabs(["Login", "Create Account"])
116
+
117
+ with login_tab:
118
+ email = st.text_input("Email:")
119
+ password = st.text_input("Password:", type='password')
120
+ if st.button("Login"):
121
+ if authenticate_user(email=email,password=password):
122
+ st.session_state.user_authenticated = True
123
+ else:
124
+ st.caption('Incorrect Username or Password.')
125
+
126
+ if st.session_state.user_authenticated:
127
+ st.caption("User Authenticated")
128
+
129
+ with create_account_tab:
130
+ new_email = st.text_input("New Email:")
131
+ new_password = st.text_input("New Password:", type='password')
132
+ confirm_password = st.text_input("Confirm Password:", type='password')
133
+ if st.button("Create Account"):
134
+ if not approve_email(new_email):
135
+ st.caption("Invalid Email")
136
+ return
137
+ if not approve_password(new_password):
138
+ st.caption("Invalid Password")
139
+ return
140
+ if new_password != confirm_password:
141
+ st.caption("Passwords do not match")
142
+ return
143
+ add_user_to_db(email=new_email, password=new_password)
144
+ st.caption(f"{new_email} Successfully Added")
145
+
146
+
147
  def main():
148
  st.set_page_config(page_title="Stock Price AI Bot", page_icon=":chart:")
149
  st.write(css, unsafe_allow_html=True)
150
+ create_users_db()
151
  init_ses_states()
152
  st.title("Stock Price AI Bot")
153
  st.caption("Visualizations and OpenAI Chatbot for Multiple Stocks Over A Specified Period")
154
 
155
+
156
  with st.sidebar:
157
+ user_authentication_tab()
158
+
159
+
160
+ if st.session_state.user_authenticated:
161
+ with st.sidebar:
162
+ with st.expander("Settings",expanded=True):
163
+ asset_tickers = sorted(['DOW','NVDA','TSL','GOOGL','AMZN','AI','NIO','LCID','F','LYFY','AAPL', 'MSFT', 'BTC-USD', 'ETH-USD'])
164
+ asset_dropdown = st.multiselect('Pick Assets:', asset_tickers)
165
+
166
+ metric_tickers = ['Adj. Close', 'Relative Returns']
167
+ metric_dropdown = st.selectbox("Metric", metric_tickers)
168
+
169
+ viz_tickers = ['Line Chart', 'Area Chart']
170
+ viz_dropdown = st.multiselect("Pick Charts:", viz_tickers)
171
+
172
+ start = st.date_input('Start', value=pd.to_datetime('2023-01-01'))
173
+ end = st.date_input('End', value=pd.to_datetime('today'))
174
+
175
+ chatbot_temp = st.slider("Chat Bot Temperature",0.0,1.0,0.5)
176
+
177
+ # Only when a stock is selected
178
+ if len(asset_dropdown) > 0:
179
+ df = yf.download(asset_dropdown,start,end)['Adj Close']
180
+ if metric_dropdown == 'Relative Returns':
181
+ df = relative_returns(df)
182
+ if len(viz_dropdown) > 0:
183
+ with st.expander("Data Visualizations for {} of {}".format(metric_dropdown,asset_dropdown), expanded=True):
184
+ if "Line Chart" in viz_dropdown:
185
+ st.subheader("Line Chart")
186
+ st.line_chart(df)
187
+ if "Area Chart" in viz_dropdown:
188
+ st.subheader("Area Chart")
189
+ st.area_chart(df)
190
+ st.header("Chat with your Data")
191
+
192
+ query = st.text_input("Enter a query:")
193
+
194
+ chat_prompt = f'''
195
+ You are an AI ChatBot intended to help with user stock data.
196
+ \nYou have access to a pandas dataframe with the following specifications
197
+ \nDATA MODE: {metric_dropdown}
198
+ \nSTOCKS: {asset_dropdown}
199
+ \nTIME PERIOD: {start} to {end}
200
+ \nCHAT HISTORY: {st.session_state.chat_history}
201
+ \nUSER MESSAGE: {query}
202
+ \nAI RESPONSE HERE:
203
+ '''
204
+
205
+ if st.button("Execute") and query:
206
+ with st.spinner('Generating response...'):
207
+ try:
208
+ DF = pd.DataFrame(df)
209
+ DF.to_csv('data.csv')
210
+ agent = create_csv_agent(
211
+ llm,
212
+ 'data.csv',
213
+ verbose=True,
214
+ agent_type=AgentType.OPENAI_FUNCTIONS,
215
+ )
216
+
217
+ answer = agent.run(chat_prompt)
218
+ st.session_state.chat_history.append(f"USER: {query}\n")
219
+ st.session_state.chat_history.append(f"AI: {answer}\n")
220
+ display_convo()
221
+
222
+ except Exception as e:
223
+ st.error(f"An error occurred: {str(e)}")
224
 
225
 
226
  if __name__ == '__main__':
227
  main()
228
+