KatGaw commited on
Commit
0bf43ca
1 Parent(s): 67d3861
.DS_Store ADDED
Binary file (6.15 kB). View file
 
Dockerfile ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ FROM python:3.9
2
+ RUN useradd -m -u 1000 user
3
+ USER user
4
+ ENV HOME=/home/user \
5
+ PATH=/home/user/.local/bin:$PATH
6
+ WORKDIR $HOME/app
7
+ COPY --chown=user . $HOME/app
8
+ COPY ./requirements.txt ~/app/requirements.txt
9
+ RUN pip install -r requirements.txt
10
+ COPY . .
11
+ CMD ["chainlit", "run", "app.py", "--port", "7860"]
LICENSE ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ MIT License
2
+
3
+ Copyright (c) 2024 Katerina Gawthorpe
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
README.md CHANGED
@@ -1,10 +1,22 @@
1
  ---
2
- title: ExpressMode
3
- emoji: 🌖
4
- colorFrom: blue
5
- colorTo: purple
6
  sdk: docker
7
  pinned: false
 
8
  ---
9
 
10
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
 
 
 
 
 
 
 
 
 
 
 
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
+ ![alt text](el_pic.png)
14
+
15
+ > Forecast and analyze stocks and make $$$!!!. Ask me anything about stocks.
16
+
17
+ ## Data from open-source data: Yahoo finance + Sentiment analysis.
18
+ LangGraph/Langchain/RAG/Chainlit/OpenAI
19
+ ---
20
+
21
+
22
+ > :wave: Code originates mainly from the amazing AI Makerspace Bootcamp!!! For more see [https://github.com/sanjeevl10/StockSavvyFinal]
app.py ADDED
@@ -0,0 +1,126 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from openai import OpenAI
2
+ import streamlit as st
3
+ import utils as u
4
+ from langchain_openai import ChatOpenAI
5
+ from tools import sentiment_analysis_util
6
+ import functools
7
+ from typing import Annotated
8
+ import operator
9
+ from typing import Sequence, TypedDict
10
+ import numpy as np
11
+ import pandas as pd
12
+ from dotenv import load_dotenv
13
+ import os
14
+ import functools
15
+ from typing import Annotated
16
+ import operator
17
+
18
+ st.set_page_config(page_title="LangChain Agent", layout="wide")
19
+ load_dotenv()
20
+ OPENAI_API_KEY = os.environ["OPENAI_API_KEY"]
21
+
22
+ llm = ChatOpenAI(model="gpt-3.5-turbo")
23
+
24
+ from langchain_core.runnables import RunnableConfig
25
+
26
+ st.title("💬 ExpressMood")
27
+
28
+ @st.cache_resource
29
+ def initialize_session_state():
30
+ if "chat_history" not in st.session_state:
31
+ st.session_state["messages"] = [{"role":"system", "content":"""
32
+ You are a sentiment analysis expert. Answer all questions related to cryptocurrency investment reccommendations. Say I don't know if you don't know.
33
+ """}]
34
+
35
+ initialize_session_state()
36
+
37
+ sideb=st.sidebar
38
+ with st.sidebar:
39
+ prompt=st.text_input("Enter topic for sentiment analysis: ")
40
+
41
+ check1=sideb.button(f"analyze {prompt}")
42
+
43
+ if check1:
44
+ # Add user message to chat history
45
+ st.session_state.messages.append({"role": "user", "content": prompt})
46
+ # Display user message in chat message container
47
+ with st.chat_message("user"):
48
+ st.markdown(prompt)
49
+
50
+ # ========================== Sentiment analysis
51
+ #Perform sentiment analysis on the cryptocurrency news & predict dominant sentiment along with plotting the sentiment breakdown chart
52
+ # Downloading from reddit
53
+
54
+ # Downloading from alpaca
55
+ if len(prompt.split(' '))<2:
56
+ print('here')
57
+ st.write('I am analyzing Google News ...')
58
+ news_articles = sentiment_analysis_util.fetch_news(str(prompt))
59
+ st.write('Now, I am analyzing Reddit ...')
60
+ reddit_news_articles=sentiment_analysis_util.fetch_reddit_news(prompt)
61
+ analysis_results = []
62
+
63
+ #Perform sentiment analysis for each product review
64
+ if len(prompt.split(' '))<2:
65
+ print('here')
66
+ for article in news_articles:
67
+ if prompt.lower()[0:6] in article['News_Article'].lower():
68
+ sentiment_analysis_result = sentiment_analysis_util.analyze_sentiment(article['News_Article'])
69
+
70
+ # Display sentiment analysis results
71
+ #print(f'News Article: {sentiment_analysis_result["News_Article"]} : Sentiment: {sentiment_analysis_result["Sentiment"]}', '\n')
72
+
73
+ result = {
74
+ 'News_Article': sentiment_analysis_result["News_Article"],
75
+ 'Sentiment': sentiment_analysis_result["Sentiment"][0]['label'],
76
+ 'Index': sentiment_analysis_result["Sentiment"][0]['score'],
77
+ 'URL': article['URL']
78
+ }
79
+
80
+ analysis_results.append(result)
81
+
82
+ articles_url=[]
83
+ for article in reddit_news_articles:
84
+ if prompt.lower()[0:6] in article.lower():
85
+ sentiment_analysis_result_reddit = sentiment_analysis_util.analyze_sentiment(article)
86
+
87
+ # Display sentiment analysis results
88
+ #print(f'News Article: {sentiment_analysis_result_reddit["News_Article"]} : Sentiment: {sentiment_analysis_result_reddit["Sentiment"]}', '\n')
89
+
90
+ result = {
91
+ 'News_Article': sentiment_analysis_result_reddit["News_Article"],
92
+ 'Index':np.round(sentiment_analysis_result_reddit["Sentiment"][0]['score'],2)
93
+ }
94
+ analysis_results.append(np.append(result,np.append(article.split('URL:')[-1:], ((article.split('Date: ')[-1:])[0][0:10]))))
95
+ #pd.DataFrame(analysis_results).to_csv('analysis_results.csv')
96
+
97
+ #Generate summarized message rationalize dominant sentiment
98
+ summary = sentiment_analysis_util.generate_summary_of_sentiment(analysis_results) #, dominant_sentiment)
99
+ st.chat_message("assistant").write((summary))
100
+ st.session_state.messages.append({"role": "assistant", "content": summary})
101
+ #answers=np.append(res["messages"][-1].content,summary)
102
+
103
+ client = OpenAI(api_key=OPENAI_API_KEY)
104
+
105
+ if "openai_model" not in st.session_state:
106
+ st.session_state["openai_model"] = "gpt-3.5-turbo"
107
+
108
+ if prompt := st.chat_input("Any other questions? "):
109
+ # Add user message to chat history
110
+ st.session_state.messages.append({"role": "user", "content": prompt})
111
+ # Display user message in chat message container
112
+ with st.chat_message("user"):
113
+ st.markdown(prompt)
114
+ # Display assistant response in chat message container
115
+ with st.chat_message("assistant"):
116
+ stream = client.chat.completions.create(
117
+ model=st.session_state["openai_model"],
118
+ messages=[
119
+ {"role": m["role"], "content": m["content"]}
120
+ for m in st.session_state.messages
121
+ ],
122
+ stream=True,
123
+ )
124
+ response = st.write_stream(stream)
125
+ st.session_state.messages.append({"role": "assistant", "content": response})
126
+
chainlit.md ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ # 🤖 ExpressMode
3
+ ----
4
+ ExpressMode is a powerful tool designed to perform sentiment analysis on any topic related to North American roads. This app helps you gain insights into public opinion, trends, and emotions surrounding road conditions, infrastructure, traffic, and more.
5
+
6
+ ### 🚀 Features
7
+
8
+ - Topic Sentiment Analysis: Quickly determine the sentiment (positive, neutral, negative) of discussions about North American roads.
9
+ - Comprehensive Data Sources: Leverage various sources including social media and news articles.
10
+ - Real-time Updates: Get the latest sentiment analysis as soon as new data is available.
11
+ - Customizable Filters: Focus on specific regions, road types, or timeframes for more targeted insights.
12
+
13
+ ### 🧑‍💻 Usage
14
+
15
+ -> Enter a one-word topic related to North American roads into the left sidebar.
16
+ -> Hit "Analyze" to view sentiment trends and detailed reports.
17
+ -> You can ask any other related question in the main search bar.
18
+
19
+ ### 💬 Feedback
20
+
21
+ For any questions or feedback, please contact [email protected].
22
+
23
+ 🚗 Try it out!
tools/.DS_Store ADDED
Binary file (6.15 kB). View file
 
tools/__pycache__/sentiment_analysis_util.cpython-311.pyc ADDED
Binary file (9.04 kB). View file
 
tools/sentiment_analysis_util.py ADDED
@@ -0,0 +1,221 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ import os
3
+ from dotenv import load_dotenv
4
+ from transformers import pipeline
5
+ import pandas as pd
6
+ from collections import defaultdict
7
+ from datetime import date
8
+ import matplotlib.pyplot as plt
9
+ import http.client, urllib.parse
10
+ from GoogleNews import GoogleNews
11
+ from langchain_openai import ChatOpenAI
12
+ import pandas as pd
13
+ import praw
14
+ from datetime import datetime
15
+ import numpy as np
16
+
17
+ load_dotenv()
18
+
19
+ def fetch_news(topic):
20
+
21
+ """ Fetches news articles within a specified date range.
22
+
23
+ Args:
24
+ - topic (str): Topic of interest
25
+
26
+ Returns:
27
+ - list: A list of dictionaries containing news. """
28
+
29
+ load_dotenv()
30
+ days_to_fetch_news = os.environ["DAYS_TO_FETCH_NEWS"]
31
+
32
+ googlenews = GoogleNews()
33
+ googlenews.set_period(days_to_fetch_news)
34
+ googlenews.get_news(topic)
35
+ news_json=googlenews.get_texts()
36
+ urls=googlenews.get_links()
37
+
38
+ no_of_news_articles_to_fetch = os.environ["NO_OF_NEWS_ARTICLES_TO_FETCH"]
39
+ news_article_list = []
40
+ counter = 0
41
+ for article in news_json:
42
+
43
+ if(counter >= int(no_of_news_articles_to_fetch)):
44
+ break
45
+
46
+ relevant_info = {
47
+ 'News_Article': article,
48
+ 'URL': urls[counter]
49
+ }
50
+ news_article_list.append(relevant_info)
51
+ counter+=1
52
+ return news_article_list
53
+
54
+ def fetch_reddit_news(topic):
55
+ load_dotenv()
56
+ REDDIT_USER_AGENT= os.environ["REDDIT_USER_AGENT"]
57
+ REDDIT_CLIENT_ID= os.environ["REDDIT_CLIENT_ID"]
58
+ REDDIT_CLIENT_SECRET= os.environ["REDDIT_CLIENT_SECRET"]
59
+ #https://medium.com/geekculture/a-complete-guide-to-web-scraping-reddit-with-python-16e292317a52
60
+ user_agent = REDDIT_USER_AGENT
61
+ reddit = praw.Reddit (
62
+ client_id= REDDIT_CLIENT_ID,
63
+ client_secret= REDDIT_CLIENT_SECRET,
64
+ user_agent=user_agent
65
+ )
66
+
67
+ headlines = set ( )
68
+ for submission in reddit.subreddit('nova').search(topic,time_filter='week'):
69
+ headlines.add(submission.title + ', Date: ' +datetime.utcfromtimestamp(int(submission.created_utc)).strftime('%Y-%m-%d %H:%M:%S') + ', URL:' +submission.url)
70
+
71
+ if len(headlines)<10:
72
+ for submission in reddit.subreddit('nova').search(topic,time_filter='year'):
73
+ headlines.add(submission.title + ', Date: ' +datetime.utcfromtimestamp(int(submission.created_utc)).strftime('%Y-%m-%d %H:%M:%S') + ', URL:' +submission.url)
74
+ if len(headlines)<10:
75
+ for submission in reddit.subreddit('nova').search(topic): #,time_filter='week'):
76
+ headlines.add(submission.title + ', Date: ' +datetime.utcfromtimestamp(int(submission.created_utc)).strftime('%Y-%m-%d %H:%M:%S') + ', URL:' +submission.url)
77
+ return headlines
78
+
79
+ def analyze_sentiment(article):
80
+ """
81
+ Analyzes the sentiment of a given news article.
82
+
83
+ Args:
84
+ - news_article (dict): Dictionary containing 'summary', 'headline', and 'created_at' keys.
85
+
86
+ Returns:
87
+ - dict: A dictionary containing sentiment analysis results.
88
+ """
89
+
90
+ #Analyze sentiment using default model
91
+ #classifier = pipeline('sentiment-analysis')
92
+
93
+ #Analyze sentiment using specific model
94
+ classifier = pipeline(model='tabularisai/robust-sentiment-analysis') #mrm8488/distilroberta-finetuned-financial-news-sentiment-analysis')
95
+ sentiment_result = classifier(str(article))
96
+
97
+ analysis_result = {
98
+ 'News_Article': article,
99
+ 'Sentiment': sentiment_result
100
+ }
101
+
102
+ return analysis_result
103
+
104
+
105
+ def generate_summary_of_sentiment(sentiment_analysis_results): #, dominant_sentiment):
106
+
107
+
108
+ news_article_sentiment = str(sentiment_analysis_results)
109
+ print("News article sentiment : " + news_article_sentiment)
110
+
111
+
112
+ os.environ["OPENAI_API_KEY"] = os.environ["OPENAI_API_KEY"]
113
+ model = ChatOpenAI(
114
+ model="gpt-4o",
115
+ temperature=0,
116
+ max_tokens=None,
117
+ timeout=None,
118
+ max_retries=2,
119
+ # api_key="...", # if you prefer to pass api key in directly instaed of using env vars
120
+ # base_url="...",
121
+ # organization="...",
122
+ # other params...
123
+ )
124
+
125
+ messages=[
126
+ {"role": "system", "content": "You are a helpful assistant that looks at all news articles, their sentiment, along with domainant sentiment and generates a summary rationalizing dominant sentiment. At the end of the summary, add URL links with dates for all the articles in the markdown format for streamlit. Example of adding the URLs: The Check out the links: [link](%s) % url, 2024-03-01 "},
127
+ {"role": "user", "content": f"News articles and their sentiments: {news_article_sentiment}"} #, and dominant sentiment is: {dominant_sentiment}"}
128
+ ]
129
+ response = model.invoke(messages)
130
+
131
+
132
+ summary = response.content
133
+ print ("+++++++++++++++++++++++++++++++++++++++++++++++")
134
+ print(summary)
135
+ print ("+++++++++++++++++++++++++++++++++++++++++++++++")
136
+ return summary
137
+
138
+
139
+ def plot_sentiment_graph(sentiment_analysis_results):
140
+ """
141
+ Plots a sentiment analysis graph
142
+
143
+ Args:
144
+ - sentiment_analysis_result): (dict): Dictionary containing 'Review Title : Summary', 'Rating', and 'Sentiment' keys.
145
+
146
+ Returns:
147
+ - dict: A dictionary containing sentiment analysis results.
148
+ """
149
+ df = pd.DataFrame(sentiment_analysis_results)
150
+ print(df)
151
+
152
+ #Group by Rating, sentiment value count
153
+ grouped = df['Sentiment'].value_counts()
154
+
155
+ sentiment_counts = df['Sentiment'].value_counts()
156
+
157
+ # Plotting pie chart
158
+ # fig = plt.figure(figsize=(5, 3))
159
+ # plt.pie(sentiment_counts, labels=sentiment_counts.index, autopct='%1.1f%%', startangle=140)
160
+ # plt.axis('equal') # Equal aspect ratio ensures that pie is drawn as a circle.
161
+
162
+ #Open below when u running this program locally and c
163
+ #plt.show()
164
+
165
+ return sentiment_counts
166
+
167
+
168
+ def get_dominant_sentiment (sentiment_analysis_results):
169
+ """
170
+ Returns overall sentiment, negative or positive or neutral depending on the count of negative sentiment vs positive sentiment
171
+
172
+ Args:
173
+ - sentiment_analysis_result): (dict): Dictionary containing 'summary', 'headline', and 'created_at' keys.
174
+
175
+ Returns:
176
+ - dict: A dictionary containing sentiment analysis results.
177
+ """
178
+ df = pd.DataFrame(sentiment_analysis_results)
179
+
180
+ # Group by the 'sentiment' column and count the occurrences of each sentiment value
181
+ print(df)
182
+ print(df['Sentiment'])
183
+ sentiment_counts = df['Sentiment'].value_counts().reset_index()
184
+ sentiment_counts.columns = ['sentiment', 'count']
185
+ print(sentiment_counts)
186
+
187
+ # Find the sentiment with the highest count
188
+ dominant_sentiment = sentiment_counts.loc[sentiment_counts['count'].idxmax()]
189
+
190
+ return dominant_sentiment['sentiment']
191
+
192
+ #starting point of the program
193
+ if __name__ == '__main__':
194
+
195
+ #fetch news
196
+ news_articles = fetch_news('AAPL')
197
+
198
+ analysis_results = []
199
+
200
+ #Perform sentiment analysis for each product review
201
+ for article in news_articles:
202
+ sentiment_analysis_result = analyze_sentiment(article['News_Article'])
203
+
204
+ # Display sentiment analysis results
205
+ print(f'News Article: {sentiment_analysis_result["News_Article"]} : Sentiment: {sentiment_analysis_result["Sentiment"]}', '\n')
206
+
207
+ result = {
208
+ 'News_Article': sentiment_analysis_result["News_Article"],
209
+ 'Sentiment': sentiment_analysis_result["Sentiment"][0]['label']
210
+ }
211
+
212
+ analysis_results.append(result)
213
+
214
+
215
+ #Graph dominant sentiment based on sentiment analysis data of reviews
216
+ dominant_sentiment = get_dominant_sentiment(analysis_results)
217
+ print(dominant_sentiment)
218
+
219
+ #Plot graph
220
+ plot_sentiment_graph(analysis_results)
221
+
utils.py ADDED
@@ -0,0 +1,177 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import matplotlib.pyplot as plt
2
+ import plotly.graph_objects as go
3
+ import pandas as pd
4
+ import numpy as np
5
+ from datetime import datetime, timedelta
6
+ import yfinance as yf
7
+ from plotly.subplots import make_subplots
8
+
9
+ def get_stock_price(stockticker: str) -> str:
10
+ ticker = yf.Ticker(stockticker)
11
+ todays_data = ticker.history(period='1d')
12
+ return str(round(todays_data['Close'][0], 2))
13
+
14
+ def plot_candlestick_stock_price(historical_data):
15
+ """Useful for plotting candlestick plot for stock prices.
16
+ Use historical stock price data from yahoo finance for the week and plot them."""
17
+ df=historical_data[['Close','Open','High','Low']]
18
+ df.index=pd.to_datetime(df.index)
19
+ df.index.names=['Date']
20
+ df=df.reset_index()
21
+
22
+ fig = go.Figure(data=[go.Candlestick(x=df['Date'],
23
+ open=df['Open'],
24
+ high=df['High'],
25
+ low=df['Low'],
26
+ close=df['Close'])])
27
+ fig.show()
28
+
29
+ def historical_stock_prices(stockticker, days_ago):
30
+ """Upload accurate data to accurate dates from yahoo finance."""
31
+ ticker = yf.Ticker(stockticker)
32
+ end_date = datetime.now()
33
+ start_date = end_date - timedelta(days=days_ago)
34
+ start_date = start_date.strftime('%Y-%m-%d')
35
+ end_date = end_date.strftime('%Y-%m-%d')
36
+ historical_data = ticker.history(start=start_date, end=end_date)
37
+ return historical_data
38
+
39
+ def plot_macd2(df):
40
+ try:
41
+ # Debugging: Print the dataframe columns and a few rows
42
+ print("DataFrame columns:", df.columns)
43
+ print("DataFrame head:\n", df.head())
44
+
45
+ # Convert DataFrame index and columns to numpy arrays
46
+ index = df.index.to_numpy()
47
+ close_prices = df['Close'].to_numpy()
48
+ macd = df['MACD'].to_numpy()
49
+ signal_line = df['Signal_Line'].to_numpy()
50
+ macd_histogram = df['MACD_Histogram'].to_numpy()
51
+
52
+ fig, (ax1, ax2) = plt.subplots(2, 1, sharex=True, figsize=(10, 8), gridspec_kw={'height_ratios': [3, 1]})
53
+
54
+ # Subplot 1: Candlestick chart
55
+ ax1.plot(index, close_prices, label='Close', color='black')
56
+ ax1.set_title("Candlestick Chart")
57
+ ax1.set_ylabel("Price")
58
+ ax1.legend()
59
+
60
+ # Subplot 2: MACD
61
+ ax2.plot(index, macd, label='MACD', color='blue')
62
+ ax2.plot(index, signal_line, label='Signal Line', color='red')
63
+
64
+ histogram_colors = np.where(macd_histogram >= 0, 'green', 'red')
65
+ ax2.bar(index, macd_histogram, color=histogram_colors, alpha=0.6)
66
+
67
+ ax2.set_title("MACD")
68
+ ax2.set_ylabel("MACD Value")
69
+ ax2.legend()
70
+
71
+ plt.xlabel("Date")
72
+ plt.tight_layout()
73
+
74
+ return fig
75
+ except Exception as e:
76
+ print(f"Error in plot_macd: {e}")
77
+ return None
78
+
79
+ def plot_macd(df):
80
+
81
+ # Create Figure
82
+ fig = make_subplots(rows=2, cols=1, shared_xaxes=True, row_heights=[0.2, 0.1],
83
+ vertical_spacing=0.15, # Adjust vertical spacing between subplots
84
+ subplot_titles=("Candlestick Chart", "MACD")) # Add subplot titles
85
+
86
+
87
+ # Subplot 1: Plot candlestick chart
88
+ fig.add_trace(go.Candlestick(
89
+ x=df.index,
90
+ open=df['Open'],
91
+ high=df['High'],
92
+ low=df['Low'],
93
+ close=df['Close'],
94
+ increasing_line_color='#00cc96', # Green for increasing
95
+ decreasing_line_color='#ff3e3e', # Red for decreasing
96
+ showlegend=False
97
+ ), row=1, col=1) # Specify row and column indices
98
+
99
+
100
+ # Subplot 2: Plot MACD
101
+ fig.add_trace(
102
+ go.Scatter(
103
+ x=df.index,
104
+ y=df['MACD'],
105
+ mode='lines',
106
+ name='MACD',
107
+ line=dict(color='blue')
108
+ ),
109
+ row=2, col=1
110
+ )
111
+
112
+ fig.add_trace(
113
+ go.Scatter(
114
+ x=df.index,
115
+ y=df['Signal_Line'],
116
+ mode='lines',
117
+ name='Signal Line',
118
+ line=dict(color='red')
119
+ ),
120
+ row=2, col=1
121
+ )
122
+
123
+ # Plot MACD Histogram with different colors for positive and negative values
124
+ histogram_colors = ['green' if val >= 0 else 'red' for val in df['MACD_Histogram']]
125
+
126
+ fig.add_trace(
127
+ go.Bar(
128
+ x=df.index,
129
+ y=df['MACD_Histogram'],
130
+ name='MACD Histogram',
131
+ marker_color=histogram_colors
132
+ ),
133
+ row=2, col=1
134
+ )
135
+
136
+ # Update layout with zoom and pan tools enabled
137
+ layout = go.Layout(
138
+ title='MSFT Candlestick Chart and MACD Subplots',
139
+ title_font=dict(size=12), # Adjust title font size
140
+ plot_bgcolor='#f2f2f2', # Light gray background
141
+ height=600,
142
+ width=1200,
143
+ xaxis_rangeslider=dict(visible=True, thickness=0.03),
144
+ )
145
+
146
+ # Update the layout of the entire figure
147
+ fig.update_layout(layout)
148
+ fig.update_yaxes(fixedrange=False, row=1, col=1)
149
+ fig.update_yaxes(fixedrange=True, row=2, col=1)
150
+ fig.update_xaxes(type='category', row=1, col=1)
151
+ fig.update_xaxes(type='category', nticks=10, row=2, col=1)
152
+
153
+ fig.show()
154
+ #return fig
155
+
156
+ def calculate_MACD(df, fast_period=12, slow_period=26, signal_period=9):
157
+ """
158
+ Calculates the MACD (Moving Average Convergence Divergence) and related indicators.
159
+
160
+ Parameters:
161
+ df (DataFrame): A pandas DataFrame containing at least a 'Close' column with closing prices.
162
+ fast_period (int): The period for the fast EMA (default is 12).
163
+ slow_period (int): The period for the slow EMA (default is 26).
164
+ signal_period (int): The period for the signal line EMA (default is 9).
165
+
166
+ Returns:
167
+ DataFrame: A pandas DataFrame with the original data and added columns for MACD, Signal Line, and MACD Histogram.
168
+ """
169
+
170
+ df['EMA_fast'] = df['Close'].ewm(span=fast_period, adjust=False).mean()
171
+ df['EMA_slow'] = df['Close'].ewm(span=slow_period, adjust=False).mean()
172
+ df['MACD'] = df['EMA_fast'] - df['EMA_slow']
173
+
174
+ df['Signal_Line'] = df['MACD'].ewm(span=signal_period, adjust=False).mean()
175
+ df['MACD_Histogram'] = df['MACD'] - df['Signal_Line']
176
+
177
+ return df