Introduction
If you want to earn money from stock market, you have to use some charting technique to analysis their history data. There are many free web sites to provide analysis chart, such as google, yahoo, etc; however, because I am an IT guy, I like to tailor-make the chart myself , for example as the below diagram.
Software Requirement:
Python with Anaconda version 3-2.4.1
Program Coding as below with filename as stockchart.py:
import urllib.request, urllib.error, urllib.parse
import time
import datetime
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.ticker as mticker
import matplotlib.dates as mdates
from matplotlib.finance import candlestick_ohlc
import matplotlib
import pylab
matplotlib.rcParams.update({‘font.size’: 9})
def rsiFunc(prices, n=14):
deltas = np.diff(prices)
seed = deltas[:n+1]
up = seed[seed>=0].sum()/n
down = -seed[seed<0].sum()/n
rs = up/down
rsi = np.zeros_like(prices)
rsi[:n] = 100. – 100./(1.+rs)
for i in range(n, len(prices)):
delta = deltas[i-1] # cause the diff is 1 shorter
if delta>0:
upval = delta
downval = 0.
else:
upval = 0.
downval = -delta
up = (up*(n-1) + upval)/n
down = (down*(n-1) + downval)/n
rs = up/down
rsi[i] = 100. – 100./(1.+rs)
return rsi
def movingaverage(values,window):
weigths = np.repeat(1.0, window)/window
smas = np.convolve(values, weigths, ‘valid’)
return smas # as a numpy array
def ExpMovingAverage(values, window):
weights = np.exp(np.linspace(-1., 0., window))
weights /= weights.sum()
a = np.convolve(values, weights, mode=’full’)[:len(values)]
a[:window] = a[window]
return a
def computeMACD(x, slow=26, fast=12):
“””
compute the MACD (Moving Average Convergence/Divergence) using a fast and slow exponential moving avg’
return value is emaslow, emafast, macd which are len(x) arrays
“””
emaslow = ExpMovingAverage(x, slow)
emafast = ExpMovingAverage(x, fast)
return emaslow, emafast, emafast – emaslow
def bytespdate2num(fmt, encoding=’utf-8′):
strconverter = mdates.strpdate2num(fmt)
def bytesconverter(b):
s = b.decode(encoding)
return strconverter(s)
return bytesconverter
def graphData(MA1,MA2):
”’
Use this to dynamically pull a stock:
”’
try:
print(‘Currently Pulling’)
urlToVisit = ‘http://chartapi.finance.yahoo.com/instrument/1.0/2800.hk/chartdata;type=quote;range=5y/csv’
stockFile =[]
try:
sourceCode = urllib.request.urlopen(urlToVisit).read().decode()
splitSource = sourceCode.split(‘\n’)
for eachLine in splitSource:
splitLine = eachLine.split(‘,’)
if len(splitLine)==6:
if ‘values’ not in eachLine:
stockFile.append(eachLine)
except Exception as e:
print(str(e), ‘failed to organize pulled 2800.hk data.’)
urlToVisit1 = ‘http://chartapi.finance.yahoo.com/instrument/1.0/0005.hk/chartdata;type=quote;range=5y/csv’
stockFile1 =[]
try:
sourceCode1 = urllib.request.urlopen(urlToVisit1).read().decode()
splitSource1 = sourceCode1.split(‘\n’)
for eachLine in splitSource1:
splitLine = eachLine.split(‘,’)
if len(splitLine)==6:
if ‘values’ not in eachLine:
stockFile1.append(eachLine)
except Exception as e:
print(str(e), ‘failed to organize pulled 0005.hk data.’)
urlToVisit2 = ‘http://chartapi.finance.yahoo.com/instrument/1.0/2828.hk/chartdata;type=quote;range=5y/csv’
stockFile2 =[]
try:
sourceCode2 = urllib.request.urlopen(urlToVisit2).read().decode()
splitSource2 = sourceCode2.split(‘\n’)
for eachLine in splitSource2:
splitLine = eachLine.split(‘,’)
if len(splitLine)==6:
if ‘values’ not in eachLine:
stockFile2.append(eachLine)
except Exception as e:
print(str(e), ‘failed to organize pulled 2828.hk data.’)
urlToVisit3 = ‘http://chartapi.finance.yahoo.com/instrument/1.0/0941.hk/chartdata;type=quote;range=5y/csv’
stockFile3 =[]
try:
sourceCode3 = urllib.request.urlopen(urlToVisit3).read().decode()
splitSource3 = sourceCode3.split(‘\n’)
for eachLine in splitSource3:
splitLine = eachLine.split(‘,’)
if len(splitLine)==6:
if ‘values’ not in eachLine:
stockFile3.append(eachLine)
except Exception as e:
print(str(e), ‘failed to organize pulled 0941.hk data.’)
urlToVisit4 = ‘http://chartapi.finance.yahoo.com/instrument/1.0/0939.hk/chartdata;type=quote;range=5y/csv’
stockFile4 =[]
try:
sourceCode4 = urllib.request.urlopen(urlToVisit4).read().decode()
splitSource4 = sourceCode4.split(‘\n’)
for eachLine in splitSource4:
splitLine = eachLine.split(‘,’)
if len(splitLine)==6:
if ‘values’ not in eachLine:
stockFile4.append(eachLine)
except Exception as e:
print(str(e), ‘failed to organize pulled 0939.hk data.’)
except Exception as e:
print(str(e), ‘failed to pull pricing data’)
try:
”’
Use this to draw chart0:
”’
date, closep, highp, lowp, openp, volume = np.loadtxt(stockFile,delimiter=’,’, unpack=True,
converters={ 0: bytespdate2num(‘%Y%m%d’)})
x = 0
y = len(date)
newAr = []
while x < y:
appendLine = date[x],openp[x],highp[x],lowp[x],closep[x],volume[x]
newAr.append(appendLine)
x+=1
Av1 = movingaverage(closep, MA1)
Av2 = movingaverage(closep, MA2)
SP = len(date[MA2-1:])
fig = plt.figure(facecolor=’#07000d’)
ax0 = plt.subplot2grid((15,15), (0,0), rowspan=3, colspan=15, axisbg=’#07000d’)
candlestick_ohlc(ax0, newAr[-SP:], width=.6, colorup=’#53c156′, colordown=’#ff1717′)
Label1 = str(MA1)+’ SMA’
Label2 = str(MA2)+’ SMA’
ax0.plot(date[-SP:],Av1[-SP:],’#e1edf9′,label=Label1, linewidth=1.5)
ax0.plot(date[-SP:],Av2[-SP:],’#4ee6fd’,label=Label2, linewidth=1.5)
ax0.grid(True, color=’w’)
ax0.xaxis.set_major_locator(mticker.MaxNLocator(10))
ax0.xaxis.set_major_formatter(mdates.DateFormatter(‘%Y-%m-%d’))
ax0.yaxis.label.set_color(“w”)
ax0.spines[‘bottom’].set_color(“#5998ff”)
ax0.spines[‘top’].set_color(“#5998ff”)
ax0.spines[‘left’].set_color(“#5998ff”)
ax0.spines[‘right’].set_color(“#5998ff”)
ax0.tick_params(axis=’y’, colors=’w’)
plt.gca().yaxis.set_major_locator(mticker.MaxNLocator(prune=’upper’))
ax0.tick_params(axis=’x’, colors=’w’)
plt.ylabel(‘2800’)
maLeg = plt.legend(loc=9, ncol=2, prop={‘size’:7},
fancybox=True, borderaxespad=0.)
maLeg.get_frame().set_alpha(0.4)
textEd = pylab.gca().get_legend().get_texts()
pylab.setp(textEd[0:5], color = ‘w’)
volumeMin = 0
ax0v = ax0.twinx()
ax0v.fill_between(date[-SP:],volumeMin, volume[-SP:], facecolor=’#00ffe8′, alpha=.4)
ax0v.axes.yaxis.set_ticklabels([])
ax0v.grid(False)
###Edit this to 3, so it’s a bit larger
ax0v.set_ylim(0, 3*volume.max())
ax0v.spines[‘bottom’].set_color(“#5998ff”)
ax0v.spines[‘top’].set_color(“#5998ff”)
ax0v.spines[‘left’].set_color(“#5998ff”)
ax0v.spines[‘right’].set_color(“#5998ff”)
ax0v.tick_params(axis=’x’, colors=’w’)
ax0v.tick_params(axis=’y’, colors=’w’)
”’
Use this to draw chart1:
”’
date1, closep1, highp1, lowp1, openp1, volume1 = np.loadtxt(stockFile1,delimiter=’,’, unpack=True,
converters={ 0: bytespdate2num(‘%Y%m%d’)})
x1 = 0
y1 = len(date1)
newAr1 = []
while x1 < y1:
appendLine1 = date1[x1],openp1[x1],highp1[x1],lowp1[x1],closep1[x1],volume1[x1]
newAr1.append(appendLine1)
x1+=1
Av11 = movingaverage(closep1, MA1)
Av21 = movingaverage(closep1, MA2)
SP1 = len(date1[MA2-1:])
ax1 = plt.subplot2grid((15,15), (3,0), sharex=ax0, rowspan=3, colspan=15, axisbg=’#07000d’)
candlestick_ohlc(ax1, newAr1[-SP1:], width=.6, colorup=’#53c156′, colordown=’#ff1717′)
Label11 = str(MA1)+’ SMA’
Label21 = str(MA2)+’ SMA’
ax1.plot(date1[-SP1:],Av11[-SP1:],’#e1edf9′,label=Label11, linewidth=1.5)
ax1.plot(date1[-SP1:],Av21[-SP1:],’#4ee6fd’,label=Label21, linewidth=1.5)
ax1.grid(True, color=’w’)
ax1.xaxis.set_major_locator(mticker.MaxNLocator(10))
ax1.xaxis.set_major_formatter(mdates.DateFormatter(‘%Y-%m-%d’))
ax1.yaxis.label.set_color(“w”)
ax1.spines[‘bottom’].set_color(“#5998ff”)
ax1.spines[‘top’].set_color(“#5998ff”)
ax1.spines[‘left’].set_color(“#5998ff”)
ax1.spines[‘right’].set_color(“#5998ff”)
ax1.tick_params(axis=’y’, colors=’w’)
plt.gca().yaxis.set_major_locator(mticker.MaxNLocator(prune=’upper’))
ax1.tick_params(axis=’x’, colors=’w’)
plt.ylabel(‘0005’)
maLeg = plt.legend(loc=9, ncol=2, prop={‘size’:7},
fancybox=True, borderaxespad=0.)
maLeg.get_frame().set_alpha(0.4)
textEd = pylab.gca().get_legend().get_texts()
pylab.setp(textEd[0:5], color = ‘w’)
volumeMin = 0
ax1v = ax1.twinx()
ax1v.fill_between(date1[-SP1:],volumeMin, volume1[-SP1:], facecolor=’#00ffe8′, alpha=.4)
ax1v.axes.yaxis.set_ticklabels([])
ax1v.grid(False)
###Edit this to 3, so it’s a bit larger
ax1v.set_ylim(0, 3*volume1.max())
ax1v.spines[‘bottom’].set_color(“#5998ff”)
ax1v.spines[‘top’].set_color(“#5998ff”)
ax1v.spines[‘left’].set_color(“#5998ff”)
ax1v.spines[‘right’].set_color(“#5998ff”)
ax1v.tick_params(axis=’x’, colors=’w’)
ax1v.tick_params(axis=’y’, colors=’w’)
”’
Use this to draw chart2:
”’
date2, closep2, highp2, lowp2, openp2, volume2 = np.loadtxt(stockFile2,delimiter=’,’, unpack=True,
converters={ 0: bytespdate2num(‘%Y%m%d’)})
x2 = 0
y2 = len(date2)
newAr2 = []
while x2 < y2:
appendLine2 = date2[x2],openp2[x2],highp2[x2],lowp2[x2],closep2[x2],volume2[x2]
newAr2.append(appendLine2)
x2+=1
Av12 = movingaverage(closep2, MA1)
Av22 = movingaverage(closep2, MA2)
SP2 = len(date2[MA2-1:])
ax2 = plt.subplot2grid((15,15), (6,0), sharex=ax0, rowspan=3, colspan=15, axisbg=’#07000d’)
candlestick_ohlc(ax2, newAr2[-SP2:], width=.6, colorup=’#53c156′, colordown=’#ff1717′)
Label12 = str(MA1)+’ SMA’
Label22 = str(MA2)+’ SMA’
ax2.plot(date2[-SP2:],Av12[-SP2:],’#e1edf9′,label=Label12, linewidth=1.5)
ax2.plot(date2[-SP2:],Av22[-SP2:],’#4ee6fd’,label=Label22, linewidth=1.5)
ax2.grid(True, color=’w’)
ax2.xaxis.set_major_locator(mticker.MaxNLocator(10))
ax2.xaxis.set_major_formatter(mdates.DateFormatter(‘%Y-%m-%d’))
ax2.yaxis.label.set_color(“w”)
ax2.spines[‘bottom’].set_color(“#5998ff”)
ax2.spines[‘top’].set_color(“#5998ff”)
ax2.spines[‘left’].set_color(“#5998ff”)
ax2.spines[‘right’].set_color(“#5998ff”)
ax2.tick_params(axis=’y’, colors=’w’)
plt.gca().yaxis.set_major_locator(mticker.MaxNLocator(prune=’upper’))
ax2.tick_params(axis=’x’, colors=’w’)
plt.ylabel(‘2828’)
maLeg = plt.legend(loc=9, ncol=2, prop={‘size’:7},
fancybox=True, borderaxespad=0.)
maLeg.get_frame().set_alpha(0.4)
textEd = pylab.gca().get_legend().get_texts()
pylab.setp(textEd[0:5], color = ‘w’)
volumeMin = 0
ax2v = ax2.twinx()
ax2v.fill_between(date2[-SP2:],volumeMin, volume2[-SP2:], facecolor=’#00ffe8′, alpha=.4)
ax2v.axes.yaxis.set_ticklabels([])
ax2v.grid(False)
###Edit this to 3, so it’s a bit larger
ax2v.set_ylim(0, 3*volume2.max())
ax2v.spines[‘bottom’].set_color(“#5998ff”)
ax2v.spines[‘top’].set_color(“#5998ff”)
ax2v.spines[‘left’].set_color(“#5998ff”)
ax2v.spines[‘right’].set_color(“#5998ff”)
ax2v.tick_params(axis=’x’, colors=’w’)
ax2v.tick_params(axis=’y’, colors=’w’)
”’
Use this to draw chart3:
”’
date3, closep3, highp3, lowp3, openp3, volume3 = np.loadtxt(stockFile3,delimiter=’,’, unpack=True,
converters={ 0: bytespdate2num(‘%Y%m%d’)})
x3 = 0
y3 = len(date3)
newAr3 = []
while x3 < y3:
appendLine3 = date3[x3],openp3[x3],highp3[x3],lowp3[x3],closep3[x3],volume3[x3]
newAr3.append(appendLine3)
x3+=1
Av13 = movingaverage(closep3, MA1)
Av23 = movingaverage(closep3, MA2)
SP3 = len(date3[MA2-1:])
ax3 = plt.subplot2grid((15,15), (9,0), sharex=ax0, rowspan=3, colspan=15, axisbg=’#07000d’)
candlestick_ohlc(ax3, newAr3[-SP3:], width=.6, colorup=’#53c156′, colordown=’#ff1717′)
Label13 = str(MA1)+’ SMA’
Label23 = str(MA2)+’ SMA’
ax3.plot(date3[-SP3:],Av13[-SP3:],’#e1edf9′,label=Label13, linewidth=1.5)
ax3.plot(date3[-SP3:],Av23[-SP3:],’#4ee6fd’,label=Label23, linewidth=1.5)
ax3.grid(True, color=’w’)
ax3.xaxis.set_major_locator(mticker.MaxNLocator(10))
ax3.xaxis.set_major_formatter(mdates.DateFormatter(‘%Y-%m-%d’))
ax3.yaxis.label.set_color(“w”)
ax3.spines[‘bottom’].set_color(“#5998ff”)
ax3.spines[‘top’].set_color(“#5998ff”)
ax3.spines[‘left’].set_color(“#5998ff”)
ax3.spines[‘right’].set_color(“#5998ff”)
ax3.tick_params(axis=’y’, colors=’w’)
plt.gca().yaxis.set_major_locator(mticker.MaxNLocator(prune=’upper’))
ax3.tick_params(axis=’x’, colors=’w’)
plt.ylabel(‘941’)
maLeg = plt.legend(loc=9, ncol=2, prop={‘size’:7},
fancybox=True, borderaxespad=0.)
maLeg.get_frame().set_alpha(0.4)
textEd = pylab.gca().get_legend().get_texts()
pylab.setp(textEd[0:5], color = ‘w’)
volumeMin = 0
ax3v = ax3.twinx()
ax3v.fill_between(date3[-SP3:],volumeMin, volume3[-SP3:], facecolor=’#00ffe8′, alpha=.4)
ax3v.axes.yaxis.set_ticklabels([])
ax3v.grid(False)
###Edit this to 3, so it’s a bit larger
ax3v.set_ylim(0, 3*volume3.max())
ax3v.spines[‘bottom’].set_color(“#5998ff”)
ax3v.spines[‘top’].set_color(“#5998ff”)
ax3v.spines[‘left’].set_color(“#5998ff”)
ax3v.spines[‘right’].set_color(“#5998ff”)
ax3v.tick_params(axis=’x’, colors=’w’)
ax3v.tick_params(axis=’y’, colors=’w’)
”’
Use this to draw chart4:
”’
date4, closep4, highp4, lowp4, openp4, volume4 = np.loadtxt(stockFile4,delimiter=’,’, unpack=True,
converters={ 0: bytespdate2num(‘%Y%m%d’)})
x4 = 0
y4 = len(date4)
newAr4 = []
while x4 < y4:
appendLine4 = date4[x4],openp4[x4],highp4[x4],lowp4[x4],closep4[x4],volume4[x4]
newAr4.append(appendLine4)
x4+=1
Av14 = movingaverage(closep4, MA1)
Av24 = movingaverage(closep4, MA2)
SP4 = len(date4[MA2-1:])
ax4 = plt.subplot2grid((15,15), (12,0), sharex=ax0, rowspan=3, colspan=15, axisbg=’#07000d’)
candlestick_ohlc(ax4, newAr4[-SP4:], width=.6, colorup=’#53c156′, colordown=’#ff1717′)
Label14 = str(MA1)+’ SMA’
Label24 = str(MA2)+’ SMA’
ax4.plot(date4[-SP4:],Av14[-SP4:],’#e1edf9′,label=Label14, linewidth=1.5)
ax4.plot(date4[-SP4:],Av24[-SP4:],’#4ee6fd’,label=Label24, linewidth=1.5)
ax4.grid(True, color=’w’)
ax4.xaxis.set_major_locator(mticker.MaxNLocator(10))
ax4.xaxis.set_major_formatter(mdates.DateFormatter(‘%Y-%m-%d’))
ax4.yaxis.label.set_color(“w”)
ax4.spines[‘bottom’].set_color(“#5998ff”)
ax4.spines[‘top’].set_color(“#5998ff”)
ax4.spines[‘left’].set_color(“#5998ff”)
ax4.spines[‘right’].set_color(“#5998ff”)
ax4.tick_params(axis=’y’, colors=’w’)
plt.gca().yaxis.set_major_locator(mticker.MaxNLocator(prune=’upper’))
ax4.tick_params(axis=’x’, colors=’w’)
plt.ylabel(‘939’)
maLeg = plt.legend(loc=9, ncol=2, prop={‘size’:7},
fancybox=True, borderaxespad=0.)
maLeg.get_frame().set_alpha(0.4)
textEd = pylab.gca().get_legend().get_texts()
pylab.setp(textEd[0:5], color = ‘w’)
volumeMin = 0
ax4v = ax4.twinx()
ax4v.fill_between(date4[-SP4:],volumeMin, volume4[-SP4:], facecolor=’#00ffe8′, alpha=.4)
ax4v.axes.yaxis.set_ticklabels([])
ax4v.grid(False)
###Edit this to 3, so it’s a bit larger
ax4v.set_ylim(0, 3*volume4.max())
ax4v.spines[‘bottom’].set_color(“#5998ff”)
ax4v.spines[‘top’].set_color(“#5998ff”)
ax4v.spines[‘left’].set_color(“#5998ff”)
ax4v.spines[‘right’].set_color(“#5998ff”)
ax4v.tick_params(axis=’x’, colors=’w’)
ax4v.tick_params(axis=’y’, colors=’w’)
”’
Use this to display all charts:
”’
plt.subplots_adjust(left=.09, bottom=.14, right=.94, top=.95, wspace=.20, hspace=0)
plt.show()
fig.savefig(‘example.png’,facecolor=fig.get_facecolor())
except Exception as e:
print(‘main loop’,str(e))
graphData(10,50)
