Skip to content

Commit 6326fd3

Browse files
authored
Added Bollinger Bands Tutorial File
1 parent f8801a1 commit 6326fd3

File tree

1 file changed

+56
-0
lines changed

1 file changed

+56
-0
lines changed

Tutorials/Bollinger Bands Tutorial.py

Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
# import needed libraries
2+
import pandas as pd
3+
import matplotlib.pyplot as plt
4+
from pandas_datareader import data as web
5+
6+
# Make function for calls to Yahoo Finance
7+
def get_adj_close(ticker, start, end):
8+
'''
9+
A function that takes ticker symbols, starting period, ending period
10+
as arguments and returns with a Pandas DataFrame of the Adjusted Close Prices
11+
for the tickers from Yahoo Finance
12+
'''
13+
start = start
14+
end = end
15+
info = web.DataReader(ticker, data_source='yahoo', start=start, end=end)['Adj Close']
16+
return pd.DataFrame(info)
17+
18+
# Get Adjusted Closing Prices for Facebook, Tesla and Amazon between 2016-2017
19+
fb = get_adj_close('fb', '1/2/2016', '31/12/2017')
20+
tesla = get_adj_close('tsla', '1/2/2016', '31/12/2017')
21+
amazon = get_adj_close('amzn', '1/2/2016', '31/12/2017')
22+
23+
# Calculate 30 Day Moving Average, Std Deviation, Upper Band and Lower Band
24+
for item in (fb, tesla, amazon):
25+
item['30 Day MA'] = item['Adj Close'].rolling(window=20).mean()
26+
item['30 Day STD'] = item['Adj Close'].rolling(window=20).std()
27+
item['Upper Band'] = item['30 Day MA'] + (item['30 Day STD'] * 2)
28+
item['Lower Band'] = item['30 Day MA'] - (item['30 Day STD'] * 2)
29+
30+
# Simple 30 Day Bollinger Band for Facebook (2016-2017)
31+
fb[['Adj Close', '30 Day MA', 'Upper Band', 'Lower Band']].plot(figsize=(12,6))
32+
plt.title('30 Day Bollinger Band for Facebook')
33+
plt.ylabel('Price (USD)')
34+
plt.show()
35+
36+
# set style, empty figure and axes
37+
plt.style.use('fivethirtyeight')
38+
fig = plt.figure(figsize=(12,6))
39+
ax = fig.add_subplot(111)
40+
41+
# Get index values for the X axis for facebook DataFrame
42+
x_axis = fb.index.get_level_values(0)
43+
44+
# Plot shaded 21 Day Bollinger Band for Facebook
45+
ax.fill_between(x_axis, fb['Upper Band'], fb['Lower Band'], color='grey')
46+
47+
# Plot Adjust Closing Price and Moving Averages
48+
ax.plot(x_axis, fb['Adj Close'], color='blue', lw=2)
49+
ax.plot(x_axis, fb['30 Day MA'], color='black', lw=2)
50+
51+
# Set Title & Show the Image
52+
ax.set_title('30 Day Bollinger Band For Facebook')
53+
ax.set_xlabel('Date (Year/Month)')
54+
ax.set_ylabel('Price(USD)')
55+
ax.legend()
56+
plt.show()

0 commit comments

Comments
 (0)