Market Sentiment Dashboard: Visualizing Market Sentiment Using Technical Indicators
In this tutorial, we will explore how to create a market sentiment dashboard using Python. Market sentiment refers to the overall attitude or feeling of investors towards a particular market or asset. By analyzing market sentiment, traders and investors can gain insights into the potential direction of the market.
We will use various technical indicators to gauge market sentiment and visualize the results using Python. Technical indicators are mathematical calculations based on historical price and volume data that can help identify trends, momentum and potential reversal points in the market.
To download financial data, we will use the yfinance
library, which allows us to retrieve historical data for various financial assets. We will focus on real assets such as stocks, banking tickers and cryptocurrencies. We will download data until the end of October 2023 to ensure we have enough data for meaningful visualizations.
Let’s get started by installing the necessary libraries and importing the required modules.
!pip install yfinance
!pip install numpy
!pip install matplotlib
!pip install plotly
!pip install mplfinance
import yfinance as yf
import numpy as np
import matplotlib.pyplot as plt
from plotly.subplots import make_subplots
import plotly.graph_objects as go
import mplfinance as mpf
import talib
Step 1: Downloading Financial Data
To begin, we need to download financial data for the assets we want to analyze. We will use the yfinance
library to retrieve the data. Let's start by downloading the data for a specific asset.
# Download data for a specific asset
ticker = "GS"
start_date = "2018-01-01"
end_date = "2023-10-31"
data = yf.download(ticker, start=start_date, end=end_date)
In the above code, we specify the ticker symbol for the asset we want to analyze (in this case, “GS” for the asset). We also provide the start and end dates for the data. Adjust these values according to your needs.
Next, let’s take a look at the downloaded data.
print(data.head())
print(data.tail())
The head()
function displays the first few rows of the data, while the tail()
function shows the last few rows. This allows us to verify that the data has been downloaded correctly.
Step 2: Calculating Technical Indicators
Now that we have the financial data, we can calculate various technical indicators to gauge market sentiment. In this tutorial, we will focus on three popular indicators: Moving Average Convergence Divergence (MACD), Relative Strength Index (RSI) and Bollinger Bands.
Moving Average Convergence Divergence (MACD)
The Moving Average Convergence Divergence (MACD) is a trend-following momentum indicator that shows the relationship between two moving averages of an asset’s price. It consists of three components: the MACD line, the signal line and the histogram.
To calculate the MACD, we need to calculate the 12-day exponential moving average (EMA) and the 26-day EMA. We then subtract the 26-day EMA from the 12-day EMA to obtain the MACD line. The signal line is typically a 9-day EMA of the MACD line.
Let’s calculate the MACD for our downloaded data.
# Calculate MACD using TA-Lib
macd, macd_signal, macd_hist = talib.MACD(data["Close"], fastperiod=12, slowperiod=26, signalperiod=9)
data["macd"] = macd
data["signal"] = macd_signal
data["hist"] = macd_hist
# Plot MACD
plt.figure(figsize=(12, 6))
plt.plot(data.index, data["macd"], label="MACD Line")
plt.plot(data.index, data["signal"], label="Signal Line")
plt.bar(data.index, data["hist"], label="Histogram")
plt.title("MACD")
plt.xlabel("Date")
plt.ylabel("MACD")
plt.legend()
plt.show()
In the above code, we calculate the MACD using the talib.MACD()
function from the talib
library. We then plot the MACD line, signal line and histogram using matplotlib
.
Relative Strength Index (RSI)
The Relative Strength Index (RSI) is a momentum oscillator that measures the speed and change of price movements. It oscillates between 0 and 100 and is typically used to identify overbought or oversold conditions in the market.
To calculate the RSI, we need to calculate the average gain and average loss over a specified period. We then use these values to calculate the relative strength (RS) and the RSI.
Let’s calculate the RSI for our downloaded data.
# Calculate RSI
delta = data["Close"].diff()
gain = delta.copy()
loss = delta.copy()
gain[gain < 0] = 0
loss[loss > 0] = 0
avg_gain = gain.rolling(window=14).mean()
avg_loss = abs(loss.rolling(window=14).mean())
rs = avg_gain / avg_loss
data["rsi"] = 100 - (100 / (1 + rs))
# Plot RSI
plt.figure(figsize=(12, 6))
plt.plot(data.index, data["rsi"])
plt.axhline(y=70, color="r", linestyle="--", label="Overbought")
plt.axhline(y=30, color="g", linestyle="--", label="Oversold")
plt.title("RSI")
plt.xlabel("Date")
plt.ylabel("RSI")
plt.legend()
plt.show()
In the above code, we calculate the RSI using the formula mentioned earlier. We then plot the RSI values along with the overbought and oversold levels (70 and 30, respectively).
Bollinger Bands
Bollinger Bands are a volatility indicator that consists of a middle band (usually a 20-day simple moving average) and two outer bands that are standard deviations away from the middle band. The outer bands expand and contract based on market volatility.
To calculate the Bollinger Bands, we need to calculate the middle band, upper band and lower band. The upper band is typically two standard deviations above the middle band, while the lower band is two standard deviations below the middle band.
Let’s calculate the Bollinger Bands for our downloaded data.
# Calculate Bollinger Bands
data["middle_band"] = data["Close"].rolling(window=20).mean()
data["upper_band"] = data["middle_band"] + 2 * data["Close"].rolling(window=20).std()
data["lower_band"] = data["middle_band"] - 2 * data["Close"].rolling(window=20).std()
# Plot Bollinger Bands
plt.figure(figsize=(12, 6))
plt.plot(data.index, data["Close"], label="Close")
plt.plot(data.index, data["middle_band"], label="Middle Band")
plt.plot(data.index, data["upper_band"], label="Upper Band")
plt.plot(data.index, data["lower_band"], label="Lower Band")
plt.fill_between(data.index, data["upper_band"], data["lower_band"], alpha=0.2)
plt.title("Bollinger Bands")
plt.xlabel("Date")
plt.ylabel("Price")
plt.legend()
plt.show()
In the above code, we calculate the middle band, upper band and lower band using the rolling mean and standard deviation functions. We then plot the closing prices along with the Bollinger Bands.
Step 3: Creating the Market Sentiment Dashboard
Now that we have calculated the technical indicators, let’s create the market sentiment dashboard. We will use the plotly
library to create interactive plots that allow users to zoom in and explore the data in more detail.
Candlestick Chart
A candlestick chart is a popular chart type used in technical analysis to represent price movements over time. It provides information about the opening, closing, high and low prices for each period.
Let’s create a candlestick chart for our downloaded data.
# Create Candlestick Chart
fig = go.Figure(data=[go.Candlestick(x=data.index,
open=data["Open"],
high=data["High"],
low=data["Low"],
close=data["Close"])])
fig.update_layout(title="Candlestick Chart",
xaxis_title="Date",
yaxis_title="Price")
In the above code, we use the go.Candlestick()
function from the plotly.graph_objects
module to create the candlestick chart.
Combined Plot
Finally, let’s combine all the plots we have created so far into a single dashboard. This will allow us to visualize the market sentiment using different technical indicators.
# Create Combined Plot
fig = make_subplots(rows=3, cols=1, shared_xaxes=True)
# Add MACD plot
fig.add_trace(go.Scatter(x=data.index, y=data["macd"], name="MACD Line"), row=1, col=1)
fig.add_trace(go.Scatter(x=data.index, y=data["signal"], name="Signal Line"), row=1, col=1)
fig.add_trace(go.Bar(x=data.index, y=data["hist"], name="Histogram"), row=1, col=1)
# Add RSI plot
fig.add_trace(go.Scatter(x=data.index, y=data["rsi"], name="RSI"), row=2, col=1)
fig.add_shape(type="line", x0=data.index[0], y0=70, x1=data.index[-1], y1=70, line=dict(color="red", dash="dash"), row=2, col=1)
fig.add_shape(type="line", x0=data.index[0], y0=30, x1=data.index[-1], y1=30, line=dict(color="green", dash="dash"), row=2, col=1)
# Add Bollinger Bands plot
fig.add_trace(go.Scatter(x=data.index, y=data["Close"], name="Close"), row=3, col=1)
fig.add_trace(go.Scatter(x=data.index, y=data["middle_band"], name="Middle Band"), row=3, col=1)
fig.add_trace(go.Scatter(x=data.index, y=data["upper_band"], name="Upper Band"), row=3, col=1)
fig.add_trace(go.Scatter(x=data.index, y=data["lower_band"], name="Lower Band"), row=3, col=1)
fig.add_shape(type="rect", x0=data.index[0], y0=data["lower_band"].min(), x1=data.index[-1], y1=data["upper_band"].max(), fillcolor="lightgray", opacity=0.2, line=dict(width=0), row=3, col=1)
# Update layout
fig.update_layout(title="Market Sentiment Dashboard",
xaxis_title="Date",
height=800)
In the above code, we use the make_subplots()
function from the plotly.subplots
module to create a grid of subplots. We then add the MACD, RSI and Bollinger Bands plots to the respective subplots. Finally, we update the layout.
Conclusion
In this tutorial, we have learned how to create a market sentiment dashboard using Python. We used various technical indicators such as MACD, RSI and Bollinger Bands to gauge market sentiment and visualize the results. By analyzing market sentiment, traders and investors can make more informed decisions and potentially improve their trading strategies.
Remember to adjust the ticker symbol, start date and end date according to your needs. Experiment with different technical indicators and customize the dashboard to suit your preferences.