muzammil-eds commited on
Commit
83bfcfd
1 Parent(s): 465628b

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +51 -185
app.py CHANGED
@@ -1,92 +1,29 @@
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):
85
  rel = df.pct_change()
86
  cumret = ((1 + rel).cumprod() - 1).fillna(0)
87
  return cumret
88
 
89
-
90
  def display_convo():
91
  with st.container():
92
  for i, message in enumerate(reversed(st.session_state.chat_history)):
@@ -95,134 +32,63 @@ def display_convo():
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
-
 
1
  import os
 
2
  import streamlit as st
3
  import yfinance as yf
4
  import pandas as pd
5
  from langchain.agents import create_csv_agent, AgentType
 
 
6
  from langchain.chat_models import ChatOpenAI
7
  from htmlTemplates import css, user_template, bot_template
8
 
9
+ # Set OpenAI API Key
10
  os.environ['OPENAI_API_KEY'] = os.getenv('OPENAI_API_KEY')
11
 
12
+ # Initialize LangChain ChatOpenAI agent
13
  llm = ChatOpenAI(
14
  model='gpt-3.5-turbo',
15
  max_tokens=500,
16
  temperature=0.7,
17
  )
18
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
19
  def init_ses_states():
20
  st.session_state.setdefault('chat_history', [])
 
 
21
 
22
  def relative_returns(df):
23
  rel = df.pct_change()
24
  cumret = ((1 + rel).cumprod() - 1).fillna(0)
25
  return cumret
26
 
 
27
  def display_convo():
28
  with st.container():
29
  for i, message in enumerate(reversed(st.session_state.chat_history)):
 
32
  else:
33
  st.markdown(user_template.replace("{{MSG}}", message), unsafe_allow_html=True)
34
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
35
  def main():
36
  st.set_page_config(page_title="Stock Price AI Bot", page_icon=":chart:")
37
  st.write(css, unsafe_allow_html=True)
 
38
  init_ses_states()
39
  st.title("Stock Price AI Bot")
40
  st.caption("Visualizations and OpenAI Chatbot for Multiple Stocks Over A Specified Period")
41
 
 
42
  with st.sidebar:
43
+ asset_tickers = sorted(['DOW', 'NVDA', 'TSL', 'GOOGL', 'AMZN', 'AI', 'NIO', 'LCID', 'F', 'LYFY', 'AAPL', 'MSFT', 'BTC-USD', 'ETH-USD'])
44
+ asset_dropdown = st.multiselect('Pick Assets:', asset_tickers)
45
+ metric_tickers = ['Adj. Close', 'Relative Returns']
46
+ metric_dropdown = st.selectbox("Metric", metric_tickers)
47
+ viz_tickers = ['Line Chart', 'Area Chart']
48
+ viz_dropdown = st.multiselect("Pick Charts:", viz_tickers)
49
+ start = st.date_input('Start', value=pd.to_datetime('2023-01-01'))
50
+ end = st.date_input('End', value=pd.to_datetime('today'))
51
+
52
+ if len(asset_dropdown) > 0:
53
+ df = yf.download(asset_dropdown, start, end)['Adj Close']
54
+ if metric_dropdown == 'Relative Returns':
55
+ df = relative_returns(df)
56
+ if len(viz_dropdown) > 0:
57
+ with st.expander("Data Visualizations", expanded=True):
58
+ if "Line Chart" in viz_dropdown:
59
+ st.line_chart(df)
60
+ if "Area Chart" in viz_dropdown:
61
+ st.area_chart(df)
62
+
63
+ st.header("Chat with your Data")
64
+ query = st.text_input("Enter a query:")
65
+ chat_prompt = f'''
66
+ You are an AI ChatBot intended to help with user stock data.
67
+ \nDATA MODE: {metric_dropdown}
68
+ \nSTOCKS: {asset_dropdown}
69
+ \nTIME PERIOD: {start} to {end}
70
+ \nCHAT HISTORY: {st.session_state.chat_history}
71
+ \nUSER MESSAGE: {query}
72
+ \nAI RESPONSE HERE:
73
+ '''
74
+
75
+ if st.button("Execute") and query:
76
+ with st.spinner('Generating response...'):
77
+ try:
78
+ DF = pd.DataFrame(df)
79
+ DF.to_csv('data.csv')
80
+ agent = create_csv_agent(
81
+ llm,
82
+ 'data.csv',
83
+ verbose=True,
84
+ agent_type=AgentType.OPENAI_FUNCTIONS,
85
+ )
86
+ answer = agent.run(chat_prompt)
87
+ st.session_state.chat_history.append(f"USER: {query}\n")
88
+ st.session_state.chat_history.append(f"AI: {answer}\n")
89
+ display_convo()
90
+ except Exception as e:
91
+ st.error(f"An error occurred: {str(e)}")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
92
 
93
  if __name__ == '__main__':
94
  main()