Python - Draw Simple Moving Average using Tulip Indicators & Matplotlib

By xngo on April 1, 2019

Overview

Here is a simple example showing how to use Tulip Indicators and Matplotlib to draw Simple Moving Average. The data used here is from https://tulipindicators.org/sma.

Requirement

Code

#!/usr/bin/python3
 
import pandas as pd
import tulipy as ti
 
import matplotlib
matplotlib.use('Agg') # Bypass the need to install Tkinter GUI framework
import matplotlib.pyplot as plt
 
# Avoid FutureWarning: Pandas will require you to explicitly register matplotlib converters.
from pandas.plotting import register_matplotlib_converters
register_matplotlib_converters()
 
 
# Load data from CSV file.
##########################
my_headers = ['date', 'price']
my_dtypes = {'date': 'str', 'price': 'float'}
my_parse_dates = ['date']   # List columns that should be parsed as date.
loaded_data = pd.read_csv('data.csv', sep='\t', header=None, names=my_headers, 
                            dtype=my_dtypes, parse_dates=my_parse_dates)
 
# Plot the main graph.
##########################
x = loaded_data['date']
y = loaded_data['price']
plt.plot(x, y, label='Main graph')
 
# Plot Simple Moving Average. 
##########################
sma_input=loaded_data['price'].values   # Convert pandas dataframe to NumPy array.
sma_y = ti.sma(sma_input, period=5)     # Calculate SMA using Tulip Indicators.
sma_x = loaded_data['date'].values
sma_x = sma_x[4:]   # Skip 1st 4 due to period=5.
plt.plot(sma_x, sma_y, label='Simple Moving Average(5)')
 
# Customize graph
##########################
# Set graph labels & legend
plt.xlabel('Date')
plt.ylabel('Price ($)')
plt.title('Draw Simple Moving Average(5) \nusing Tulip Indicator & Matplotlib')
plt.legend()
plt.gcf().autofmt_xdate()   # Beautify the x-labels
plt.autoscale(tight=True)
 
# Save graph to file.
plt.savefig('sma-tulip-indicator-matplotlib.png')

Output chart

Screenshot of Simple Moving Average using Tulip Indicators & Matplotlib

Input data: data.csv

2005-11-01  81.59
2005-11-02  81.06
2005-11-03  82.87
2005-11-04  83.00
2005-11-07  83.61
2005-11-08  83.15
2005-11-09  82.84
2005-11-10  83.99
2005-11-11  84.55
2005-11-14  84.36
2005-11-15  85.53
2005-11-16  86.54
2005-11-17  86.89
2005-11-18  87.77
2005-11-21  87.29

About the author

Xuan Ngo is the founder of OpenWritings.net. He currently lives in Montreal, Canada. He loves to write about programming and open source subjects.