Calculate Bollinger Bands in Python

"""Bollinger Bands."""

import os
import pandas as pd
import matplotlib.pyplot as plt

def symbol_to_path(symbol, base_dir="data"):
"""Return CSV file path given ticker symbol."""
return os.path.join(base_dir, "{}.csv".format(str(symbol)))

def get_data(symbols, dates):
"""Read stock data (adjusted close) for given symbols from CSV files."""
df = pd.DataFrame(index=dates)
if 'NSE' not in symbols: # add SPY for reference, if absent
symbols.insert(0, 'NSE')

for symbol in symbols:
df_temp = pd.read_csv(symbol_to_path(symbol), index_col='Date',
parse_dates=True, usecols=['Date', 'Adj Close'], na_values=['nan'])
df_temp = df_temp.rename(columns={'Adj Close': symbol})
df = df.join(df_temp)
if symbol == 'NSE': # drop dates SPY did not trade
df = df.dropna(subset=["NSE"])

return df

def plot_data(df, title="Stock prices"):
"""Plot stock prices with a custom title and meaningful axis labels."""
ax = df.plot(title=title, fontsize=12)

def get_rolling_mean(values, window):
"""Return rolling mean of given values, using specified window size."""
return values.rolling(window).mean()

def get_rolling_std(values, window):
"""Return rolling standard deviation of given values, using specified window size."""
return values.rolling(window).std()

def get_bollinger_bands(rm, rstd):
"""Return upper and lower Bollinger Bands."""
lower_band = rm - rstd*2
upper_band = rm + rstd*2
return upper_band, lower_band

def test_run():
# Read data
dates = pd.date_range('2014-01-01', '2014-12-31')
symbols = ['NSE']
df = get_data(symbols, dates)

# Compute Bollinger Bands
# 1. Compute rolling mean
rm_SPY = get_rolling_mean(df['NSE'], window=20)

# 2. Compute rolling standard deviation
rstd_SPY = get_rolling_std(df['NSE'], window=20)

# 3. Compute upper and lower bands
upper_band, lower_band = get_bollinger_bands(rm_SPY, rstd_SPY)

# Plot raw SPY values, rolling mean and Bollinger Bands
ax = df['NSE'].plot(title="Bollinger Bands", label='NSE')
rm_SPY.plot(label='Rolling mean', ax=ax)
upper_band.plot(label='upper band', ax=ax)
lower_band.plot(label='lower band', ax=ax)

# Add axis labels and legend
ax.legend(loc='upper left')

if __name__ == "__main__":

Bollinger band

(Visited 160 times, 1 visits today)


Eyeing investment. Please note that the views given in this website are meant for reference and guidance of the readers to explore further on the topics and take informed decisions. These should not be construed as investment advice or legal opinion.

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *

Solve : *
19 − 17 =