sanjeevl10 commited on
Commit
93a1678
β€’
1 Parent(s): 2519a3a

Removed app_memory, StockPredictLLM

Browse files
Files changed (3) hide show
  1. StockPredictionLLM.xml +34 -0
  2. app_test3_memory.py +0 -306
  3. chainlit.md +20 -1
StockPredictionLLM.xml ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <mxfile host="app.diagrams.net">
2
+ <diagram name="Page-1">
3
+ <mxGraphModel dx="819" dy="641" grid="1" gridSize="10" guides="1" tooltips="1" connect="1" arrows="1" fold="1" page="1" pageScale="1" pageWidth="827" pageHeight="1169" math="0" shadow="0">
4
+ <root>
5
+ <mxCell id="0" />
6
+ <mxCell id="1" parent="0" />
7
+ <mxCell id="2" value="Data Collection" style="rounded=1;whiteSpace=wrap;html=1;" vertex="1" parent="1">
8
+ <mxGeometry x="280" y="20" width="200" height="100" as="geometry" />
9
+ </mxCell>
10
+ <mxCell id="3" value="Historical Data&#xa;News Data&#xa;Stock Ticker Information" style="rounded=1;whiteSpace=wrap;html=1;" vertex="1" parent="1">
11
+ <mxGeometry x="320" y="60" width="120" height="80" as="geometry" />
12
+ </mxCell>
13
+ <mxCell id="4" value="Data Analyst" style="rounded=1;whiteSpace=wrap;html=1;" vertex="1" parent="1">
14
+ <mxGeometry x="280" y="140" width="200" height="60" as="geometry" />
15
+ </mxCell>
16
+ <mxCell id="5" value="Analyzes and preprocesses the data" style="rounded=1;whiteSpace=wrap;html=1;" vertex="1" parent="1">
17
+ <mxGeometry x="320" y="160" width="120" height="40" as="geometry" />
18
+ </mxCell>
19
+ <mxCell id="6" value="ARIMA Model (using Historical Data)" style="rounded=1;whiteSpace=wrap;html=1;" vertex="1" parent="1">
20
+ <mxGeometry x="80" y="240" width="200" height="60" as="geometry" />
21
+ </mxCell>
22
+ <mxCell id="7" value="Random Forest Model (using News Data)" style="rounded=1;whiteSpace=wrap;html=1;" vertex="1" parent="1">
23
+ <mxGeometry x="480" y="240" width="200" height="60" as="geometry" />
24
+ </mxCell>
25
+ <mxCell id="8" value="Prediction Output" style="rounded=1;whiteSpace=wrap;html=1;" vertex="1" parent="1">
26
+ <mxGeometry x="280" y="340" width="200" height="60" as="geometry" />
27
+ </mxCell>
28
+ <mxCell id="9" value="Results from ARIMA and Random Forest models" style="rounded=1;whiteSpace=wrap;html=1;" vertex="1" parent="1">
29
+ <mxGeometry x="320" y="360" width="120" height="40" as="geometry" />
30
+ </mxCell>
31
+ <mxCell id="10" value="Evaluator" style="rounded=1;whiteSpace=wrap;html=1;" vertex="1" parent="1">
32
+ <mxGeometry x="280" y="440" width="200" height="60" as="geometry" />
33
+ </mxCell>
34
+ <mxCell id="11" value="Evaluates the prediction outputs" style="rounded=1;white
app_test3_memory.py DELETED
@@ -1,306 +0,0 @@
1
- from langchain_experimental.agents import create_pandas_dataframe_agent
2
- from langchain.llms import OpenAI
3
- import chainlit as cl
4
- from plotly.subplots import make_subplots
5
- import utils as u
6
- from langchain.agents import AgentExecutor, create_openai_tools_agent
7
- from langchain_core.messages import BaseMessage, HumanMessage
8
- from langchain_openai import ChatOpenAI
9
- from langchain_core.output_parsers.openai_functions import JsonOutputFunctionsParser
10
- from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder
11
- from tools import data_analyst
12
- from tools import stock_sentiment_evalutor
13
- import functools
14
- from typing import Annotated
15
- import operator
16
- from typing import Sequence, TypedDict
17
- from langchain.agents import initialize_agent, Tool
18
- from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder
19
- from langgraph.graph import END, StateGraph
20
- import numpy as np
21
- import pandas as pd
22
- from dotenv import load_dotenv
23
- import os
24
- import yfinance as yf
25
- import functools
26
- from typing import Annotated
27
- import operator
28
- from typing import Sequence, TypedDict
29
- from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder
30
- from langgraph.graph import END, StateGraph
31
- from tools import data_analyst, forecasting_expert_arima, forecasting_expert_rf, evaluator, stock_sentiment_evalutor, investment_advisor
32
- from chainlit.input_widget import Select
33
- import matplotlib.pyplot as plt
34
- from langgraph.checkpoint.memory import MemorySaver
35
-
36
- load_dotenv()
37
- HF_ACCESS_TOKEN = os.environ["HF_ACCESS_TOKEN"]
38
- DAYS_TO_FETCH_NEWS = os.environ["DAYS_TO_FETCH_NEWS"]
39
- NO_OF_NEWS_ARTICLES_TO_FETCH = os.environ["NO_OF_NEWS_ARTICLES_TO_FETCH"]
40
- OPENAI_API_KEY = os.environ["OPENAI_API_KEY"]
41
-
42
- from GoogleNews import GoogleNews
43
-
44
- def search_news(stockticker):
45
- """Useful to search the internet for news about a given topic and return relevant results."""
46
- # Set the number of top news results to return
47
- googlenews = GoogleNews()
48
- googlenews.set_period('7d')
49
- googlenews.get_news(stockticker)
50
- result_string=googlenews.get_texts()
51
-
52
- return result_string
53
-
54
-
55
- def create_agent(llm: ChatOpenAI, tools: list, system_prompt: str):
56
- # Each worker node will be given a name and some tools.
57
- prompt = ChatPromptTemplate.from_messages(
58
- [
59
- (
60
- "system",
61
- system_prompt,
62
- ),
63
- MessagesPlaceholder(variable_name="messages"),
64
- MessagesPlaceholder(variable_name="agent_scratchpad"),
65
- ]
66
- )
67
- agent = create_openai_tools_agent(llm, tools, prompt)
68
- executor = AgentExecutor(agent=agent, tools=tools)
69
- return executor
70
-
71
-
72
- def agent_node(state, agent, name):
73
- result = agent.invoke(state)
74
- return {"messages": [HumanMessage(content=result["output"], name=name)]}
75
-
76
- llm = ChatOpenAI(model="gpt-3.5-turbo")
77
-
78
- #======================== AGENTS ==================================
79
- # The agent state is the input to each node in the graph
80
- class AgentState(TypedDict):
81
- # The annotation tells the graph that new messages will always
82
- # be added to the current states
83
- messages: Annotated[Sequence[BaseMessage], operator.add]
84
- # The 'next' field indicates where to route to next
85
- next: str
86
-
87
- # DATA ANALYST
88
- prompt_data_analyst="You are a stock data analyst.\
89
- Provide correct stock ticker from Yahoo Finance.\
90
- Expected output: stocticker.\
91
- Provide it in the following format: >>stockticker>> \
92
- for example: >>AAPL>>"
93
-
94
- tools_data_analyst=data_analyst.data_analyst_tools()
95
- data_agent = create_agent(
96
- llm,
97
- tools_data_analyst,
98
- prompt_data_analyst)
99
- get_historical_prices = functools.partial(agent_node, agent=data_agent, name="Data_analyst")
100
-
101
- #ARIMA Forecasting expert
102
- prompt_forecasting_expert_arima="""<|begin_of_text|><|start_header_id|>system<|end_header_id|>
103
- You are stock prediction expert, \
104
- take historical stock data from message and train the ARIMA model from statsmodels Python library on the last week,then provide prediction for the 'Close' price for the next day.\
105
- Give the value for mae_arima to Evaluator.\
106
- Expected output:list of predicted prices with predicted dates for a selected stock ticker and mae_arima value.\n
107
- <|eot_id|><|start_header_id|>assistant<|end_header_id|>"""
108
-
109
- tools_forecasting_expert_arima=forecasting_expert_arima.forecasting_expert_arima_tools()
110
- code_forecasting_arima = create_agent(
111
- llm,
112
- tools_forecasting_expert_arima,
113
- prompt_forecasting_expert_arima,
114
- )
115
- predict_future_prices_arima = functools.partial(agent_node, agent=code_forecasting_arima, name="Forecasting_expert_ARIMA")
116
-
117
- # RF Forecasting expert
118
- prompt_forecasting_expert_random_forest="""<|begin_of_text|><|start_header_id|>system<|end_header_id|>
119
- You are stock prediction expert, \
120
- take historical stock data from message and train the Random forest model from statsmodels Python library on the last week,then provide prediction for the 'Close' price for the next day.\
121
- Give the value for mae_rf to Evaluator.\
122
- Expected output:list of predicted prices with predicted dates for a selected stock ticker and mae_rf value.\n
123
- <|eot_id|><|start_header_id|>assistant<|end_header_id|>"""
124
-
125
- tools_forecasting_expert_random_forest=forecasting_expert_rf.forecasting_expert_rf_tools()
126
- code_forecasting_random_forest = create_agent(
127
- llm,
128
- tools_forecasting_expert_random_forest,
129
- prompt_forecasting_expert_random_forest,
130
- )
131
- predict_future_prices_random_forest = functools.partial(agent_node, agent=code_forecasting_random_forest, name="Forecasting_expert_random_forest")
132
-
133
- # EVALUATOR
134
- prompt_evaluator="""<|begin_of_text|><|start_header_id|>system<|end_header_id|>
135
- You are an evaluator retrieve arima_prediction and arima mean average error from forecasting expert arima and rf_prediction and mean average error for random forest from forecasting expert random forest\
136
- print final prediction number.
137
- Next, compare prediction price and current price to provide reccommendation if he should buy/sell/hold the stock. \
138
- Expected output: one value for the prediction, explain why you have selected this value, reccommendation buy or sell stock and why.\
139
- <|eot_id|><|start_header_id|>assistant<|end_header_id|>"""
140
-
141
- tools_evaluate=evaluator.evaluator_tools()
142
- code_evaluate = create_agent(
143
- llm,
144
- tools_evaluate,
145
- prompt_evaluator,
146
- )
147
- evaluate = functools.partial(agent_node, agent=code_evaluate, name="Evaluator")
148
-
149
- #Stock Sentiment Evaluator
150
- prompt_sentiment_evaluator="""<|begin_of_text|><|start_header_id|>system<|end_header_id|>
151
- You are a stock sentiment evaluator, that takes in a stock ticker and
152
- then using your StockSentimentAnalysis tool retrieve news for the stock based on the configured data range starting today and their corresponding sentiment,
153
- alongwith the most dominant sentiment for the stock\
154
- Expected output: List ALL stock news and their sentiment from the StockSentimentAnalysis tool response, and the dominant sentiment for the stock also in StockSentimentAnalysis tool response as is without change\
155
- Also ensure you use the tool only once and do not make changes to messages
156
- Also you are not to change the response from the tool\
157
- <|eot_id|><|start_header_id|>assistant<|end_header_id|>"""
158
-
159
- tools_sentiment_evaluator=stock_sentiment_evalutor.sentimental_analysis_tools()
160
- sentiment_evaluator = create_agent(
161
- llm,
162
- tools_sentiment_evaluator,
163
- prompt_sentiment_evaluator,
164
- )
165
- evaluate_sentiment = functools.partial(agent_node, agent=sentiment_evaluator, name="Sentiment_Evaluator")
166
-
167
- # Investment advisor
168
- prompt_inv_advisor="""<|begin_of_text|><|start_header_id|>system<|end_header_id|>
169
- Provide personalized investment advice and recommendations.\
170
- Consider user input message for the latest news on the stock.\
171
- Provide overall sentiment of the news Positive/Negative/Neutral, and recommend if the user should invest in such stock.\
172
- MUST finish the analysis with a summary on the latest news from the user input on the stock!\
173
- <|eot_id|><|start_header_id|>assistant<|end_header_id|>"""
174
-
175
- tools_reccommend=investment_advisor.investment_advisor_tools()
176
-
177
- code_inv_advisor = create_agent(
178
- llm,
179
- tools_reccommend,
180
- prompt_inv_advisor,
181
- )
182
-
183
- reccommend = functools.partial(agent_node, agent=code_inv_advisor, name="Investment_advisor")
184
-
185
- workflow_data = StateGraph(AgentState)
186
- workflow_data.add_node("Data_analyst", get_historical_prices)
187
- workflow_data.set_entry_point("Data_analyst")
188
- graph_data=workflow_data.compile()
189
-
190
- workflow = StateGraph(AgentState)
191
- #workflow.add_node("Data_analyst", get_historical_prices)
192
- workflow.add_node("Forecasting_expert_random_forest", predict_future_prices_random_forest)
193
- workflow.add_node("Forecasting_expert_ARIMA", predict_future_prices_arima)
194
- workflow.add_node("Evaluator", evaluate)
195
-
196
-
197
- # Finally, add entrypoint
198
- workflow.set_entry_point("Forecasting_expert_random_forest")
199
- workflow.add_edge("Forecasting_expert_random_forest","Forecasting_expert_ARIMA")
200
- workflow.add_edge("Forecasting_expert_ARIMA","Evaluator")
201
- workflow.add_edge("Evaluator",END)
202
- graph = workflow.compile()
203
-
204
- #Print graph
205
- #graph.get_graph().print_ascii()
206
-
207
- memory = MemorySaver()
208
- workflow_news = StateGraph(AgentState)
209
- workflow_news.add_node("Investment_advisor", reccommend)
210
- workflow_news.set_entry_point("Investment_advisor")
211
- workflow_news.add_edge("Investment_advisor",END)
212
- graph_news = workflow_news.compile(checkpointer=memory)
213
-
214
- from langchain_core.runnables import RunnableConfig
215
- @cl.on_chat_start
216
- async def on_chat_start():
217
- cl.user_session.set("counter", 0)
218
- # Sending an image with the local file path
219
- elements = [
220
- cl.Image(name="image1", display="inline", path="./good_day.jpg",size="large")
221
- ]
222
- await cl.Message(content="Hello there, Welcome to ##StockSavyy!", elements=elements).send()
223
- await cl.Message(content="Tell me the stockticker you want me to analyze.").send()
224
-
225
- @cl.on_message
226
- async def main(message: cl.Message):
227
- #"what is the weather in sf"
228
- counter = cl.user_session.get("counter")
229
- counter += 1
230
- cl.user_session.set("counter", counter)
231
- await cl.Message(content=f"You sent {counter} message(s)!").send()
232
- if counter==1:
233
- inputs = {"messages": [HumanMessage(content=message.content)]}
234
-
235
- res_data = graph_data.invoke(inputs, config=RunnableConfig(callbacks=[
236
- cl.LangchainCallbackHandler(
237
- to_ignore=["ChannelRead", "RunnableLambda", "ChannelWrite", "__start__", "_execute"]
238
- # can add more into the to_ignore: "agent:edges", "call_model"
239
- # to_keep=
240
-
241
- )]))
242
- #print(res_data)
243
- await cl.Message(content=res_data["messages"][-1].content).send()
244
- #print('ticker',str(res_data).split(">>"))
245
- if len(str(res_data).split(">>")[1])<10:
246
- stockticker=(str(res_data).split(">>")[1])
247
- else:
248
- stockticker=(str(res_data).split(">>")[0])
249
- #print('ticker1',stockticker)
250
- print('here')
251
- df=u.get_stock_price(stockticker)
252
- df_history=u.historical_stock_prices(stockticker,90)
253
- df_history_to_msg1=eval(str(list((pd.DataFrame(df_history['Close'].values.reshape(1, -1)[0]).T).iloc[0,:])))
254
- inputs_all = {"messages": [HumanMessage(content=(f"Predict {stockticker}, historical prices are: {df_history_to_msg1}."))]}
255
- #print(inputs_all)
256
- df_history=pd.DataFrame(df_history)
257
- df_history['stockticker']=np.repeat(stockticker,len(df_history))
258
- df_history.to_csv('df_history.csv')
259
-
260
- res = graph.invoke(inputs_all, config=RunnableConfig(callbacks=[
261
- cl.LangchainCallbackHandler(
262
- to_ignore=["ChannelRead", "RunnableLambda", "ChannelWrite", "__start__", "_execute"]
263
- # can add more into the to_ignore: "agent:edges", "call_model"
264
- # to_keep=
265
-
266
- )]))
267
- await cl.Message(content= res["messages"][-2].content + '\n\n' + res["messages"][-1].content).send()
268
-
269
- df_history=pd.read_csv('df_history.csv')
270
- stockticker=str(df_history['stockticker'][0])
271
- df_search=search_news(stockticker)
272
- with open('search_news.txt', 'w') as a:
273
- a.write(str(df_search[0:10]))
274
- file = open("search_news.txt", "r")
275
- df_search = file.read()
276
- print(stockticker)
277
-
278
- config = {"configurable": {"thread_id": "1"}}
279
- inputs_news = {"messages": [HumanMessage(content=(f"Summarize articles for {stockticker} to write 2 sentences about following articles: {df_search}."))]}
280
- k=0
281
- for event in graph_news.stream(inputs_news, config, stream_mode="values"):
282
- k+=1
283
- if k>1:
284
- await cl.Message(content=event["messages"][-1].content).send()
285
-
286
-
287
- if counter==1:
288
- df=u.historical_stock_prices(stockticker,90)
289
- df=u.calculate_MACD(df, fast_period=12, slow_period=26, signal_period=9)
290
- fig = u.plot_macd2(df)
291
-
292
- if fig:
293
- elements = [cl.Pyplot(name="plot", figure=fig, display="inline",size="large"),
294
- ]
295
- await cl.Message(
296
- content="Here is the MACD plot",
297
- elements=elements,
298
- ).send()
299
- else:
300
- await cl.Message(
301
- content="Failed to generate the MACD plot."
302
- ).send()
303
-
304
-
305
-
306
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
chainlit.md CHANGED
@@ -1 +1,20 @@
1
- # Welcome to AskAnyQuery Bot!!
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ title: StockSavvy
3
+ emoji: πŸ“‰
4
+ colorFrom: pink
5
+ colorTo: yellow
6
+ sdk: docker
7
+ pinned: false
8
+ app_port: 7860
9
+ ---
10
+
11
+ ## πŸ€– StockSavvy
12
+
13
+ > Forecast and analyze stocks and make $$$!!!. Ask me anything about stocks.
14
+
15
+ ## Data from open-source data: Yahoo finance + Sentiment analysis.
16
+ LangGraph/Langchain/RAG/Chainlit/OpenAI
17
+ ---
18
+
19
+
20
+ > :wave: Code originates mainly from the amazing AI Makerspace Bootcamp!!! For more see [https://github.com/sanjeevl10/StockSavvyFinal]