irshadtech10 commited on
Commit
49555e1
·
verified ·
1 Parent(s): 6d4426f

Upload 2 files

Browse files
Files changed (2) hide show
  1. main.py +227 -0
  2. requirements.txt +6 -0
main.py ADDED
@@ -0,0 +1,227 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ import os
3
+ import json
4
+ from openai import OpenAI
5
+ import openai
6
+ import pandas as pd
7
+ import matplotlib.pyplot as plt
8
+ import yfinance as yf
9
+ import streamlit as st
10
+ from dotenv import load_dotenv
11
+ load_dotenv()
12
+ OPENAI_API_KEY = os.getenv("OPENAI_API_KEY")
13
+ client = OpenAI()
14
+
15
+ def get_stock_price(ticker):
16
+ return str(yf.Ticker(ticker).history(period = '1y').iloc[-1].Close)
17
+
18
+
19
+ def calculate_SMA(ticker, window):
20
+ data = yf.Ticker(ticker).history(period = '1y').Close
21
+ return str(data.rolling(window = window).mean().iloc[-1])
22
+
23
+
24
+ def calculate_EMA(ticker, window):
25
+ data = yf.Ticker(ticker).history(period = '1y').Close
26
+ return str(data.ewm(span = window, adjust = False).mean().iloc[-1])
27
+
28
+
29
+ def calculate_RSI(ticker):
30
+ data = yf.Ticker(ticker).history(period = '1y').Close
31
+ delta = data.diff()
32
+ up = delta.clip(lower = 0)
33
+ down = -1 * delta.clip(upper = 0)
34
+ ema_up = up.ewm(com = 14-1, adjust = False).mean()
35
+ ema_down = down.ewm(com = 14 - 1, adjust = False).mean()
36
+ rs = ema_up / ema_down
37
+ return str(100 - (100 / (1 + rs)).iloc[-1])
38
+
39
+
40
+ def calculate_MACD(ticker):
41
+ data = yf.Ticker(ticker).history(period = '1y').Close
42
+ short_EMA = data.ewm(span = 12, adjust = False).mean()
43
+ long_EMA = data.ewm(span = 26, adjust = False).mean()
44
+
45
+ MACD = short_EMA - long_EMA
46
+ signal = MACD.ewm(span = 9, adjust = False).mean()
47
+ MACD_histogram = MACD - signal
48
+
49
+ return f'{MACD[-1]}, {signal[-1]}, {MACD_histogram[-1]}'
50
+
51
+
52
+ def plot_stock_price(ticker):
53
+ data = yf.Ticker(ticker).history(period = '1y')
54
+ plt.figure(figsize=(10, 5))
55
+ plt.plot(data.index, data.Close)
56
+ plt.title(f"{ticker} Stock Price over last year")
57
+ plt.xlabel('Date')
58
+ plt.ylabel('Stock Price ($)')
59
+ plt.grid(True)
60
+ plt.savefig('stock.png')
61
+ plt.close()
62
+
63
+
64
+ functions = [
65
+ {
66
+ 'name': 'get_stock_price',
67
+ 'description': 'Gets the latest stock price given the ticker symbol of company',
68
+ 'parameters':{
69
+ 'type': 'object',
70
+ 'properties': {
71
+ 'ticker':{
72
+ 'type': 'string',
73
+ 'description': 'The stock ticker symbol for a company (for example AAPL for Apple)'
74
+ }
75
+ },
76
+ 'required': ['ticker']
77
+ }
78
+ },
79
+
80
+ {
81
+ 'name': 'calculate_SMA',
82
+ 'description': 'Calculate the simple moving average for a given stock ticker and a window',
83
+ 'parameters':{
84
+ 'type': 'object',
85
+ 'properties':{
86
+ 'ticker':{
87
+ 'type': 'string',
88
+ 'description': 'The stock ticker symbol for a company (for example AAPL for Apple)'
89
+ },
90
+ 'window':{
91
+ 'type': 'integer',
92
+ 'description': 'The timeframe to consider when calculating the SMA'
93
+ },
94
+ },
95
+ 'required':['ticker', 'window']
96
+ },
97
+ },
98
+
99
+ {
100
+ 'name': 'calculate_EMA',
101
+ 'description': 'Calculate the exponential moving average for a given stock ticker and a window',
102
+ 'parameters':{
103
+ 'type': 'object',
104
+ 'properties':{
105
+ 'ticker':{
106
+ 'type': 'string',
107
+ 'description': 'The stock ticker symbol for a company (for example AAPL for Apple)'
108
+ },
109
+ 'window':{
110
+ 'type': 'integer',
111
+ 'description': 'The timeframe to consider when calculating the EMA'
112
+ },
113
+ },
114
+ 'required':['ticker', 'window']
115
+ },
116
+ },
117
+
118
+ {
119
+ 'name': 'calculate_RSI',
120
+ 'description': 'Calcuate the RSI for a given stock ticker',
121
+ 'parameters':{
122
+ 'type': 'object',
123
+ 'properties': {
124
+ 'ticker': {
125
+ 'type': 'string',
126
+ 'description': 'The stock ticker symbol for a company (for example AAPL for Apple)'
127
+ }
128
+ },
129
+ 'required': ['ticker']
130
+ },
131
+ },
132
+
133
+ {
134
+ 'name': 'calculate_MACD',
135
+ 'description': 'Cacluate the MACD for a given stock ticker.',
136
+ 'parameters':{
137
+ 'type': 'object',
138
+ 'properties':{
139
+ 'ticker':{
140
+ 'type': 'string',
141
+ 'description': 'The stock ticker symbol for a company (for example AAPL for Apple)'
142
+ },
143
+ },
144
+ 'required': ['ticker']
145
+ },
146
+ },
147
+
148
+ {
149
+ 'name': 'plot_stock_price',
150
+ 'description': 'Plot the stock price for the last year given the ticker symbol of a company',
151
+ 'parameters':{
152
+ 'type': 'object',
153
+ 'properties':{
154
+ 'ticker':{
155
+ 'type':'string',
156
+ 'description': 'The stock ticker symbol for a company (for example AAPL for Apple)'
157
+ },
158
+ },
159
+ 'required': ['ticker']
160
+ },
161
+ },
162
+ ]
163
+
164
+
165
+ available_functions = {
166
+ 'get_stock_price': get_stock_price,
167
+ 'calculate_SMA': calculate_SMA,
168
+ 'calculate_EMA': calculate_EMA,
169
+ 'calculate_RSI': calculate_RSI,
170
+ 'calculate_MACD': calculate_MACD,
171
+ 'plot_stock_price': plot_stock_price
172
+ }
173
+
174
+
175
+ if 'messages' not in st.session_state:
176
+ st.session_state['messages'] = []
177
+
178
+ st.title("Stock Analysis Chatbot Assistant")
179
+
180
+ user_input = st.text_input('Your Input: ')
181
+
182
+ if user_input:
183
+ try:
184
+ st.session_state['messages'].append({'role': 'user', 'content': f'{user_input}'})
185
+ response = openai.chat.completions.create(
186
+ model = 'gpt-3.5-turbo-0125',
187
+ messages = st.session_state['messages'],
188
+ functions = functions,
189
+ function_call = 'auto'
190
+ )
191
+
192
+ response_message = response.choices[0].message
193
+ if response_message.function_call:
194
+ function_name = response_message.function_call.name
195
+ function_args = json.loads(response_message.function_call.arguments)
196
+ if function_name in ['get_stock_price', 'calculate_RSI', 'calculate_MACD', 'plot_stock_price']:
197
+ args_dict = {'ticker': function_args['ticker']}
198
+ elif function_name in ['calculate_SMA', 'calculate_EMA']:
199
+ args_dict = {'ticker': function_args['ticker'], 'window': function_args['window']}
200
+
201
+ function_to_call = available_functions[function_name]
202
+ function_response = function_to_call(**args_dict)
203
+
204
+ if function_name == 'plot_stock_price':
205
+ st.image('stock.png')
206
+
207
+ else:
208
+ st.session_state['messages'].append(response_message)
209
+ st.session_state['messages'].append(
210
+ {
211
+ 'role': 'function',
212
+ 'name': function_name,
213
+ 'content': function_response
214
+ }
215
+ )
216
+
217
+ second_response = openai.chat.completions.create(
218
+ model = 'gpt-3.5-turbo-0613',
219
+ messages = st.session_state['messages']
220
+ )
221
+ st.write(second_response.choices[0].message.content)
222
+ st.session_state['messages'].append({'role': 'assistant', 'content': second_response.choices[0].message.content})
223
+ else:
224
+ st.write(response_message.content)
225
+ st.session_state['messages'].append({'role': 'assistant', 'content': response_message.content})
226
+ except :
227
+ st.write("Stock data not found!")
requirements.txt ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ matplotlib==3.8.3
2
+ openai==1.13.3
3
+ pandas==2.2.1
4
+ python-dotenv==1.0.1
5
+ streamlit==1.31.1
6
+ yfinance==0.2.37