Reputation: 37
I can't seem to figure out how to get my y-axis labels to position to the right, despite trying a variety of matplotlib approaches, including:
My script is below in its entirety. Can't figure out what I'm missing here.
import matplotlib
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
import matplotlib.ticker as mticker
from matplotlib.finance import plot_day_summary
from matplotlib.dates import DateFormatter, WeekdayLocator, DayLocator, MonthLocator, MONDAY
import indicators
import datetime
from datetime import timedelta
matplotlib.rcParams.update({'font.size': 9})
import numpy as np
import urllib2
import datetime as dt
# Setup charting
mondays = WeekdayLocator(MONDAY) # major ticks on the mondays
alldays = DayLocator() # minor ticks on the days
firstDay = DayLocator(1)
weekFormatter = DateFormatter('%b %d') # Eg, Jan 12
dayFormatter = DateFormatter('%d') # Eg, 12
monthFormatter = DateFormatter('%b %y')
# every Nth month
months = MonthLocator(range(1,13), bymonthday=1, interval=1)
def bytespdate2num(fmt, encoding='utf-8'):
strconverter = mdates.strpdate2num(fmt)
def bytesconverter(b):
s = b.decode(encoding)
return strconverter(s)
return bytesconverter
def graph_data(stock, MA1, MA2):
################Get the stock data from yahoo################
stock_price_url = 'http://chartapi.finance.yahoo.com/instrument/1.0/'+stock+'/chartdata;type=quote;range=2y/csv'
source_code = urllib2.urlopen(stock_price_url).read().decode()
#print 'source_code: ', source_code
stock_data = []
split_source = source_code.split('\n')
#Loop through each row of csv and add to the stock_data array
for line in split_source:
split_line = line.split(',')
if len(split_line) == 6:
if 'values' not in line and 'labels' not in line:
stock_data.append(line)
date, closep, highp, lowp, openp, volume = np.loadtxt(stock_data,
delimiter=',',
unpack=True,
converters={0: bytespdate2num('%Y%m%d')})
#Add values to ohlc array
x = 0
y = len(date)
ohlc = []
while x < y:
append_me = date[x], openp[x], closep[x], highp[x], lowp[x], volume[x]
ohlc.append(append_me)
x+=1
################END OF DATA MANIPULATION################
Av1 = indicators.movingaverage(closep, MA1)
Av2 = indicators.movingaverage(closep, MA2)
SP = len(date[MA2-1:])
fig = plt.figure()
ohlc_axis = plt.subplot2grid((1,1), (0,0))
#Draw OHLC
plot_day_summary(ohlc_axis, ohlc, ticksize=2, colorup='k', colordown='k')
Label1 = str(MA1)+' SMA'
Label2 = str(MA2)+' SMA'
ohlc_axis.grid(True, color='black', which='minor')
ohlc_axis.xaxis.set_major_formatter(mdates.DateFormatter('%b'))
ohlc_axis.xaxis.set_minor_locator(mondays)
ohlc_axis.xaxis.set_major_locator(mticker.MaxNLocator(15))
ohlc_axis.xaxis.set_major_formatter(mdates.DateFormatter('%b'))
ohlc_axis.yaxis.set_major_locator(mticker.MaxNLocator(8))
ohlc_axis.yaxis.set_minor_locator(mticker.MaxNLocator(40))
#ohlc_axis.tick_params(axis='y', colors='k', labelleft='off', labelright='on')
ohlc_axis.yaxis.set_ticks_position('right')
ohlc_axis.yaxis.set_label_position('right')
#Draw MA1 and MA2
ohlc_axis.plot(date[-SP:],Av1[-SP:],'black', linewidth=1.5, linestyle='dashed')
ohlc_axis.plot(date[-SP:],Av2[-SP:],'black', linewidth=1.5, linestyle='dotted')
#draw RSI
rsi = indicators.rsiFunc(closep)
rsiCol = 'black'
rsi_axis = ohlc_axis.twinx()
rsi_axis.set_ylim(0, 4*rsi.max())
rsi_axis.plot(date[-SP:], rsi[-SP:], rsiCol, linewidth=.5)
rsi_axis.axes.yaxis.set_ticklabels([])
#draw Volume bar chart
volume_axis = ohlc_axis.twinx()
volume_axis.bar(date[-SP:], volume[-SP:], color="k", width=.5, align='center')
volume_axis.axes.yaxis.set_ticklabels([])
volume_axis.set_ylim(0, 5*volume.max())
volume_axis.tick_params(axis='y', colors='b', labelleft='off', labelright='on')
plt.xlim([datetime.date.today() - timedelta(days=365), datetime.date.today() + timedelta(days=30)])
plt.show()
fig.savefig('chart.png', facecolor=fig.get_facecolor())
graph_data('BAC', 50, 150)
I reference a script called indicators in the above. indicators.py is below:
import numpy as np
import matplotlib
import pylab
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
Here's my chart as it appears now. I want the y-axis price label to be moved to the right hand side.
Upvotes: 1
Views: 1307
Reputation: 1345
Your first attempt seems to work fine with a simple plot:
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
p = [n for n in xrange(5)]
ax.plot(p, p)
ax.yaxis.tick_right()
plt.draw()
Alternatively this works as well with multiple data:
import matplotlib.pyplot as plt
fig, ax1 = plt.subplots()
p1 = [n for n in xrange(5)]
p2 = [i**2 for i in p1]
ax1.plot(p1, p1, 'o')
ax2 = ax1.twinx()
ax2.plot(p1, p2)
plt.draw()
Without being able to run your script it is difficult to say why your y-axis won't switch to the right.
Upvotes: 1