Skip to content

Commit 029e3fb

Browse files
new method for volume exponent (per issue#296)
1 parent 987b530 commit 029e3fb

File tree

4 files changed

+152
-10
lines changed

4 files changed

+152
-10
lines changed

examples/scratch_pad/issue296.a.py

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
import pandas as pd
2+
import mplfinance as mpf
3+
import matplotlib
4+
import numpy as np
5+
6+
print(matplotlib.__version__)
7+
print(matplotlib.get_backend())
8+
print(mpf.__version__)
9+
10+
#idf = pd.read_csv('abc.csv',index_col=0,parse_dates=True)
11+
idf = pd.read_csv('../data/SPY_20110701_20120630_Bollinger.csv',index_col=0,parse_dates=True)
12+
idf.shape
13+
idf.head(3)
14+
idf.tail(3)
15+
df = idf.loc['2011-07-01':'2011-12-30',:]
16+
17+
# df.loc[:,'Volume'] *= (0.003*0.9869459423651993)
18+
# df.loc[:,'Volume'] *= (0.003*0.9869459423651994)
19+
# df.loc[:,'Volume'] *= (0.003*90000000000000.)
20+
# df.loc[:,'Volume'] *= (0.003*90000000000.)
21+
# df.loc[:,'Volume'] *= (0.003*90000000.)
22+
# df.loc[:,'Volume'] *= (0.003*900000.)
23+
# df.loc[:,'Volume'] *= (0.003*30000.)
24+
# df.loc[:,'Volume'] *= (0.003*3000.)
25+
# df.loc[:,'Volume'] *= (0.003*300.)
26+
# df.loc[:,'Volume'] *= (0.003*30.)
27+
# df.loc[:,'Volume'] *= (0.003*10.)
28+
# df.loc[:,'Volume'] *= (0.003*1.0)
29+
# df.loc[:,'Volume'] *= (0.003*0.1)
30+
# df.loc[:,'Volume'] *= (0.003*0.01)
31+
df.loc[:,'Volume'] *= (0.003*0.001)
32+
33+
vmin = np.nanmin(df.iloc[0:20]['Volume'])
34+
vmax = np.nanmax(df.iloc[0:20]['Volume'])
35+
36+
print('vmin=',vmin,' vmax=',vmax)
37+
38+
mpf.plot(df.iloc[0:20],volume=True,type='candle')

examples/scratch_pad/issue296.b.py

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
import pandas as pd
2+
import matplotlib
3+
print(matplotlib.__version__)
4+
print(matplotlib.get_backend())
5+
6+
import matplotlib.pyplot as plt
7+
8+
import mplfinance as mpf
9+
print(mpf.__version__)
10+
11+
#idf = pd.read_csv('abc.csv',index_col=0,parse_dates=True)
12+
idf = pd.read_csv('../data/SPY_20110701_20120630_Bollinger.csv',index_col=0,parse_dates=True)
13+
idf.shape
14+
idf.head(3)
15+
idf.tail(3)
16+
df = idf.loc['2011-07-01':'2011-12-30',:]*1000000.
17+
18+
x = [0,1,2,3,4,5,6,7,8,9]
19+
y = [n*1000000 for n in x]
20+
21+
22+
fig = plt.figure()
23+
24+
ax = fig.add_subplot(1,1,1)
25+
26+
#ax.ticklabel_format(useOffset=False)
27+
ax.ticklabel_format(useOffset=False,scilimits=(5,5),axis='y')
28+
ax.ticklabel_format(useOffset=False,scilimits=(0,0),axis='x')
29+
#ax.yaxis.offsetText.set_visible(False)
30+
31+
32+
ax.plot(x,y)
33+
34+
plt.show()
35+

examples/scratch_pad/issue296.py

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
import pandas as pd
2+
import mplfinance as mpf
3+
import matplotlib.animation as animation
4+
import tkinter
5+
from matplotlib.backends.backend_tkagg import (
6+
FigureCanvasTkAgg, NavigationToolbar2Tk)
7+
import matplotlib
8+
print(matplotlib.__version__)
9+
print(matplotlib.get_backend())
10+
11+
import mplfinance as mpf
12+
print(mpf.__version__)
13+
14+
#idf = pd.read_csv('abc.csv',index_col=0,parse_dates=True)
15+
idf = pd.read_csv('../data/SPY_20110701_20120630_Bollinger.csv',index_col=0,parse_dates=True)
16+
idf.shape
17+
idf.head(3)
18+
idf.tail(3)
19+
df = idf.loc['2011-07-01':'2011-12-30',:]
20+
21+
fig = mpf.figure(style='yahoo', figsize=(7, 8))
22+
ax1 = fig.add_subplot(2,1,1)
23+
ax2 = fig.add_subplot(3,1,3)
24+
25+
def animate(ival):
26+
if (20+ival) > len(df):
27+
print('no more data to plot')
28+
ani.event_source.interval *= 3
29+
if ani.event_source.interval > 12000:
30+
exit()
31+
return
32+
#return
33+
data = df.iloc[0:(20+ival)]
34+
ax1.clear()
35+
ax2.clear()
36+
mpf.plot(data,ax=ax1,volume=ax2,type='candle')
37+
38+
root = tkinter.Tk()
39+
canvas = FigureCanvasTkAgg(fig, master=root) # A tk.DrawingArea.
40+
canvas.draw()
41+
canvas.get_tk_widget().pack(side=tkinter.TOP, fill=tkinter.BOTH, expand=1)
42+
ani = animation.FuncAnimation(fig, animate, interval=250)
43+
mpf.plot(df.iloc[0:20],ax=ax1,volume=ax2,type='candle')
44+
45+
root.mainloop()

src/mplfinance/plotting.py

Lines changed: 34 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -253,6 +253,9 @@ def _valid_plot_kwargs():
253253

254254
'ax' : { 'Default' : None,
255255
'Validator' : lambda value: isinstance(value,mpl_axes.Axes) },
256+
257+
'volume_exponent' : { 'Default' : None,
258+
'Validator' : lambda value: isinstance(value,int) or value == 'legacy'},
256259
}
257260

258261
_validate_vkwargs_dict(vkwargs)
@@ -484,9 +487,9 @@ def plot( data, **kwargs ):
484487

485488
adjc = _adjust_color_brightness(vcolors,0.90)
486489
volumeAxes.bar(xdates,volumes,width=w,linewidth=lw,color=vcolors,ec=adjc)
487-
miny = 0.3 * np.nanmin(volumes)
488-
maxy = 1.1 * np.nanmax(volumes)
489-
volumeAxes.set_ylim( miny, maxy )
490+
vymin = 0.3 * np.nanmin(volumes)
491+
vymax = 1.1 * np.nanmax(volumes)
492+
volumeAxes.set_ylim(vymin,vymax)
490493

491494
xrotation = config['xrotation']
492495
if not external_axes_mode:
@@ -609,21 +612,42 @@ def plot( data, **kwargs ):
609612
axA1.set_ylabel(config['ylabel'])
610613

611614
if config['volume']:
612-
volumeAxes.figure.canvas.draw() # This is needed to calculate offset
613-
offset = volumeAxes.yaxis.get_major_formatter().get_offset()
615+
if external_axes_mode:
616+
volumeAxes.tick_params(axis='x',rotation=xrotation)
617+
volumeAxes.xaxis.set_major_formatter(formatter)
618+
vxp = config['volume_exponent']
619+
if vxp == 'legacy':
620+
volumeAxes.figure.canvas.draw() # This is needed to calculate offset
621+
offset = volumeAxes.yaxis.get_major_formatter().get_offset()
622+
if len(offset) > 0:
623+
offset = (' x '+offset)
624+
elif isinstance(vxp,int) and vxp > 0:
625+
volumeAxes.ticklabel_format(useOffset=False,scilimits=(vxp,vxp),axis='y')
626+
offset = ' $10^{'+str(vxp)+'}$'
627+
elif isinstance(vxp,int) and vxp == 0:
628+
volumeAxes.ticklabel_format(useOffset=False,style='plain',axis='y')
629+
offset = ''
630+
else:
631+
offset = ''
632+
scilims = plt.rcParams['axes.formatter.limits']
633+
if scilims[0] < scilims[1]:
634+
for power in (5,4,3,2,1):
635+
xp = scilims[1]*power
636+
if vymax >= 10.**xp:
637+
volumeAxes.ticklabel_format(useOffset=False,scilimits=(xp,xp),axis='y')
638+
offset = ' $10^{'+str(xp)+'}$'
639+
break
640+
elif scilims[0] == scilims[1] and scilims[1] != 0:
641+
volumeAxes.ticklabel_format(useOffset=False,scilimits=scilims,axis='y')
642+
offset = ' $10^'+str(scilims[1])+'$'
614643
volumeAxes.yaxis.offsetText.set_visible(False)
615-
if len(offset) > 0:
616-
offset = (' x '+offset)
617644
if config['ylabel_lower'] is None:
618645
vol_label = 'Volume'+offset
619646
else:
620647
if len(offset) > 0:
621648
offset = '\n'+offset
622649
vol_label = config['ylabel_lower'] + offset
623650
volumeAxes.set_ylabel(vol_label)
624-
if external_axes_mode:
625-
volumeAxes.tick_params(axis='x',rotation=xrotation)
626-
volumeAxes.xaxis.set_major_formatter(formatter)
627651

628652
if config['title'] is not None:
629653
if config['tight_layout']:

0 commit comments

Comments
 (0)