avatarFinancial Python

Free AI web copilot to create summaries, insights and extended knowledge, download it at here

2491

Abstract

pan class="hljs-string">'UB'</span>] = data[<span class="hljs-string">'SMA'</span>] + <span class="hljs-number">2</span> * data[<span class="hljs-string">'SD'</span>] data[<span class="hljs-string">'LB'</span>] = data[<span class="hljs-string">'SMA'</span>] - <span class="hljs-number">2</span> * data[<span class="hljs-string">'SD'</span>]</pre></div><h1 id="feea">Step 3: Interpreting Bollinger Bands</h1><p id="f081">Bollinger Bands can be interpreted as follows:</p><ul><li>When the price moves close to the upper band (UB), it may indicate overbought conditions, suggesting a potential price reversal to the downside.</li><li>Conversely, when the price approaches the lower band (LB), it may indicate oversold conditions, suggesting a potential price reversal to the upside.</li><li>The middle band (MA) represents the average price over the specified period and can serve as a reference point.</li></ul><p id="6cee">Traders often look for price crossovers of the bands or significant price deviations from the bands as potential trading signals.</p><h1 id="3d38">Step 4: Visualizing Bollinger Bands with Plotly</h1><p id="baf0">To gain better insights from the Bollinger Bands, let’s visualize them alongside the price chart using Plotly. Plotly is a versatile Python library for interactive data visualization. If you haven’t already, install Plotly with:</p><div id="094a"><pre>pip install plotly</pre></div><p id="478f">Now, let’s create a Plotly chart that displays the price chart along with the Upper Bollinger Band (UB), Lower Bollinger Band (LB), and the Middle Band (MA):</p><div id="9313"><pre><span class="hljs-keyword">import</span> plotly.graph_objs <span class="hljs-keyword">as</span> go

<span class="hljs-comment"># Create a Plotly figure</span> fig = go.Figure()

<span class="hljs-comment"># Add the price chart</span> fig.add_trace(go.Scatter(x=data.index, y=data[<span class="hljs-string">'Close'</span>], mode=<span class="hljs-string">'lines'</span>, name=<span class="hljs-string">'Price'</span>))

<span class="hljs-comment"># Add the Upper Bollinger Band (UB) and shade the area</span> fig.add_trace(go.Scatter(x=data.index, y=data[<span class="hljs-string">'UB'</span>], mode=<span class="hljs-string">'lines'</span>, name=<span class="hljs-string">'Upper Bollinger Band'</span>, line=<span class="hljs-built_in">dict</span>(color=<span class="hljs-string">'red'</span>))) fig.add_trace(go.Scatter(x=data.index, y=data[<span class="hljs-string">'LB'</span>],

Options

fill=<span class="hljs-string">'tonexty'</span>, mode=<span class="hljs-string">'lines'</span>, name=<span class="hljs-string">'Lower Bollinger Band'</span>, line=<span class="hljs-built_in">dict</span>(color=<span class="hljs-string">'green'</span>)))

<span class="hljs-comment"># Add the Middle Bollinger Band (MA)</span> fig.add_trace(go.Scatter(x=data.index, y=data[<span class="hljs-string">'SMA'</span>], mode=<span class="hljs-string">'lines'</span>, name=<span class="hljs-string">'Middle Bollinger Band'</span>, line=<span class="hljs-built_in">dict</span>(color=<span class="hljs-string">'blue'</span>)))

<span class="hljs-comment"># Customize the chart layout</span> fig.update_layout(title=<span class="hljs-string">'AAPL Stock Price with Bollinger Bands'</span>, xaxis_title=<span class="hljs-string">'Date'</span>, yaxis_title=<span class="hljs-string">'Price'</span>, showlegend=<span class="hljs-literal">True</span>)

<span class="hljs-comment"># Show the chart</span> fig.show()</pre></div><p id="00b6">In this code:</p><ul><li>We create a Plotly figure (<code>fig</code>) and add traces for the price chart, Upper Bollinger Band (UB), Lower Bollinger Band (LB), and Middle Bollinger Band (MA).</li><li>We use the <code>fill</code> option in the Lower Bollinger Band (LB) trace (<code>tonexty</code>) to fill the area between the LB and the x-axis, effectively shading it.</li><li>Each trace uses <code>go.Scatter</code> to create a line chart, with different line colors and names for clarity.</li><li>We customize the chart layout, including the title and axis labels.</li><li>Finally, we use <code>fig.show()</code> to display the interactive Plotly chart.</li></ul><p id="6f7e">And this is what it looks like:</p><figure id="9790"><img src="https://cdn-images-1.readmedium.com/v2/resize:fit:800/1*ZtsqLb5KFeO1avyZY2NA5Q.png"><figcaption></figcaption></figure><h1 id="8df3">Conclusion</h1><p id="0d17">In this article, we’ve coded a Bollinger Bands indicator in Python using AAPL stock data with a 1-hour timeframe. We’ve also discussed how to interpret and use Bollinger Bands for trading and investment decisions. Bollinger Bands are a valuable tool for assessing price volatility and identifying potential reversal points in the market.</p><p id="85a1">Feel free to adapt this code for other stocks, timeframes, or additional trading strategies.</p><p id="03f4">Hope you learned something.</p></article></body>

How to plot Bollinger Bands in Python

Introduction

Bollinger Bands are a popular technical indicator used by traders and investors to analyze price volatility and potential price reversals. In this article, we’ll explore how to calculate Bollinger Bands in Python using AAPL stock data from yfinance with a 1-hour timeframe. We’ll also discuss how to interpret and use Bollinger Bands as a tool for trading and investment decisions.

Step 1: Fetching AAPL Stock Data from yfinance

Let’s use yfinance to fetch AAPL stock data with a 1-hour timeframe. Import the required libraries and fetch the data:

import yfinance as yf

# Fetch AAPL stock data with a 1-hour timeframe
aapl = yf.Ticker("AAPL")
data = aapl.history(period="60d", interval="1h")  # Adjust the period as needed

Step 2: Calculating Bollinger Bands

Bollinger Bands consist of three lines:

  1. Middle Band (MA): This is the simple moving average (SMA) of the closing prices over a specified period. A common choice is a 20-period SMA.
  2. Upper Band (UB): This is the sum of the 20-period SMA and two times the 20-period standard deviation (SD) of the closing prices.
  3. Lower Band (LB): This is the 20-period SMA minus two times the 20-period SD of the closing prices.

Let’s calculate Bollinger Bands in Python:

# Calculate the 20-period Simple Moving Average (SMA)
data['SMA'] = data['Close'].rolling(window=20).mean()

# Calculate the 20-period Standard Deviation (SD)
data['SD'] = data['Close'].rolling(window=20).std()

# Calculate the Upper Bollinger Band (UB) and Lower Bollinger Band (LB)
data['UB'] = data['SMA'] + 2 * data['SD']
data['LB'] = data['SMA'] - 2 * data['SD']

Step 3: Interpreting Bollinger Bands

Bollinger Bands can be interpreted as follows:

  • When the price moves close to the upper band (UB), it may indicate overbought conditions, suggesting a potential price reversal to the downside.
  • Conversely, when the price approaches the lower band (LB), it may indicate oversold conditions, suggesting a potential price reversal to the upside.
  • The middle band (MA) represents the average price over the specified period and can serve as a reference point.

Traders often look for price crossovers of the bands or significant price deviations from the bands as potential trading signals.

Step 4: Visualizing Bollinger Bands with Plotly

To gain better insights from the Bollinger Bands, let’s visualize them alongside the price chart using Plotly. Plotly is a versatile Python library for interactive data visualization. If you haven’t already, install Plotly with:

pip install plotly

Now, let’s create a Plotly chart that displays the price chart along with the Upper Bollinger Band (UB), Lower Bollinger Band (LB), and the Middle Band (MA):

import plotly.graph_objs as go

# Create a Plotly figure
fig = go.Figure()

# Add the price chart
fig.add_trace(go.Scatter(x=data.index, y=data['Close'], mode='lines', name='Price'))

# Add the Upper Bollinger Band (UB) and shade the area
fig.add_trace(go.Scatter(x=data.index, y=data['UB'], mode='lines', name='Upper Bollinger Band', line=dict(color='red')))
fig.add_trace(go.Scatter(x=data.index, y=data['LB'], fill='tonexty', mode='lines', name='Lower Bollinger Band', line=dict(color='green')))

# Add the Middle Bollinger Band (MA)
fig.add_trace(go.Scatter(x=data.index, y=data['SMA'], mode='lines', name='Middle Bollinger Band', line=dict(color='blue')))

# Customize the chart layout
fig.update_layout(title='AAPL Stock Price with Bollinger Bands',
                  xaxis_title='Date',
                  yaxis_title='Price',
                  showlegend=True)

# Show the chart
fig.show()

In this code:

  • We create a Plotly figure (fig) and add traces for the price chart, Upper Bollinger Band (UB), Lower Bollinger Band (LB), and Middle Bollinger Band (MA).
  • We use the fill option in the Lower Bollinger Band (LB) trace (tonexty) to fill the area between the LB and the x-axis, effectively shading it.
  • Each trace uses go.Scatter to create a line chart, with different line colors and names for clarity.
  • We customize the chart layout, including the title and axis labels.
  • Finally, we use fig.show() to display the interactive Plotly chart.

And this is what it looks like:

Conclusion

In this article, we’ve coded a Bollinger Bands indicator in Python using AAPL stock data with a 1-hour timeframe. We’ve also discussed how to interpret and use Bollinger Bands for trading and investment decisions. Bollinger Bands are a valuable tool for assessing price volatility and identifying potential reversal points in the market.

Feel free to adapt this code for other stocks, timeframes, or additional trading strategies.

Hope you learned something.

Python
Bollinger Bands
Technical Analysis
Plotly
Recommended from ReadMedium