Skip to content

Feature Request: stack another indicator on the mpf.plot() with axes.twinx() #282

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
ggg5269 opened this issue Oct 26, 2020 · 8 comments
Closed
Labels
question Further information is requested

Comments

@ggg5269
Copy link

ggg5269 commented Oct 26, 2020

Is it able to plot a data from pd.DataFrame() (or pd.Series()) object on the axes after mpf.plot()? like plot on to the secondary y axis.

actually the figure i'm going to plot is place a drought index on to corn futures ohlc candlestick plot, somehow it shows up an error with datetime format.

sorry about my grammar, i can post the error message tomorrow and also source data or screenshots.

@ggg5269 ggg5269 added the enhancement New feature or request label Oct 26, 2020
@DanielGoldfarb
Copy link
Collaborator

Did you read the documentation?

Please read, completely, the following, in this order, and then see if maybe your question is answered:

  1. https://github.com/matplotlib/mplfinance/blob/master/examples/addplot.ipynb
  2. https://github.com/matplotlib/mplfinance/blob/master/examples/panels.ipynb
  3. https://github.com/matplotlib/mplfinance/blob/master/markdown/subplots.md

Thanks. All the best. --Daniel

@DanielGoldfarb DanielGoldfarb added question Further information is requested and removed enhancement New feature or request labels Oct 26, 2020
@ggg5269
Copy link
Author

ggg5269 commented Oct 27, 2020

Hi Daniel,
thanks for your reply.
I've read all the doc and example code, and make some adjustment of my code.

fig = mpf.figure(figsize=(16, 7), tight_layout=True,style='default')
ax1 = fig.add_subplot(111)
apds = [
    mpf.make_addplot(drought.sum(1), ax=ax1, secondary_y=True),
]

mpf.plot(c,addplot=apds, ax=ax1,volume=False)

image

this is what i get after setting secondary y axis, but still have the candlestick at the bottom.
where is my mistake?

@DanielGoldfarb
Copy link
Collaborator

@ggg5269
In my experience, problems similar to this are usually caused by data (not code), either because of the data itself, or possibly the way the data is formatted. I do not see anything obviously wrong with the code.

(That said, as a general rule I would strongly recommend against creating and using Figure and Axes, as you are, unless you are trying to accomplish something that is otherwise not supported by mplfinance; however it appears to me that what you are trying to do is definitely supported by a simple use of mpf.make_addplot() and mpf.plot() without any need to access the Figure or Axes directly. But, for now, don't bother changing the code, because it should be working the way you have it. First let's address the problem you are seeing.)

So in order to help you solve this problem, I would need to see the data you are using, and the code that processes the data.

Please attach you data (preferably as csv files, or as whatever format you are using), and include also all of the code that prepares that data, reading it in, and placing it into the variables that get passed to mplfinance.

Thank you. --Daniel

@ggg5269
Copy link
Author

ggg5269 commented Oct 28, 2020

agri.xlsx
here's how iI read the excel file for corn future price.

import pandas as pd

c = pd.read_excel("price_data/agri.xlsx", sheet_name='C 1 Comdty')
c.columns = ['Date', 'Open', 'High', 'Low', 'Close', 'Volume']
c = c.set_index('Date')

And for the drought index,
dm_export_20000101_20201026.zip

drought_df = pd.read_csv("dm_export_20000101_20201026.csv", parse_dates=['MapDate']).sort_values('MapDate').iloc[:, [0, 3, 4, 5, 6, 7]]
drought_df.columns = ['Date', 'D0', 'D1', 'D2', 'D3', 'D4']
drought_df = drought_df.set_index("Date")

drought_df = drought_df.apply(lambda x: x.str.replace(',','')).astype(float, errors='ignore')

And then I do some manipulation to make sure they got same index range

drought = pd.DataFrame(index=c.index)
drought = pd.concat([drought, drought_df], 1).fillna(method='ffill')

Finally I get the fig which was shown in the previous comment.

@DanielGoldfarb
Copy link
Collaborator

DanielGoldfarb commented Oct 28, 2020

And then I do some manipulation to make sure they got same index range

Can you please show this code too? I just want to make sure it is not having some unexpected, accidental side-effect on the data. I want to be able to completely reproduce, on my own machine, the problem you are seeing. Thank you.

NEVER MIND I see it now. Please ignore this comment.

@DanielGoldfarb
Copy link
Collaborator

OK. I was able to reproduce and I found the problem.
The problem is indeed that you are passing in your own Axes objects, in which case mplfinance can only assume you want to use the specific Axes objects that you pass, which means secondary_y=True must be ignored (because a secondary_y is actually another Axes object).

I strongly recommend that you do not create your own Figure and Axes.

Instead, keep your code simple, as shown in "Fix Number 1" below.
(However if you really want to create and use your own Axes, it can still be done that way; see "Fix Number 2" below.)


To fix the problem, do ONE of the following:


Fix Number 1 (preferred)

Instead of:

fig = mpf.figure(figsize=(16, 7), tight_layout=True,style='default')
ax1 = fig.add_subplot(111)
apds = [mpf.make_addplot(drought.sum(1), ax=ax1, secondary_y=True),]
mpf.plot(c,addplot=apds, ax=ax1,volume=False)

Do the following:

apds = mpf.make_addplot(drought.sum(1),secondary_y=True)
mpf.plot(c,addplot=apds,volume=False,figsize=(16, 7),tight_layout=True)

Here is the result:

image


Fix Number 2 (NOT preferred)

Add the line: ax2 = ax1.twinx() and use ax2 in make_addplot(), thus:

fig = mpf.figure(figsize=(16, 7), tight_layout=True,style='default')
ax1 = fig.add_subplot(111)
ax2 = ax1.twinx()
apds = [mpf.make_addplot(drought.sum(1), ax=ax2, secondary_y=True),]
mpf.plot(c,addplot=apds, ax=ax1,volume=False)

Here is the result:

image


NOTICE THAT in "Fix Number 2" you can see a vertical line on the left side at the beginning of the drought data. This is because the first row in the drought data is all NaN. (Therefore, you may want to drop the first row from both data sets). You can see this more clearly if you plot only the first 150 rows (and use plot type='candle') ...

image

@ggg5269
Copy link
Author

ggg5269 commented Oct 28, 2020

wow, thanks for your detailed answer.
now I know what's going on with the axes,
I'll change my code to the first one~

@ggg5269 ggg5269 closed this as completed Oct 28, 2020
DanielGoldfarb added a commit that referenced this issue Dec 22, 2020
New handling of volume exponent; and assorted scratch_pad additions:

This PR is primarily to implement a new way to handle the volume exponent; the new way avoids calling `.draw()` which in turn eliminates the bug mentioned in issue #296, and also mentioned/described in a previous email from S.G. ([commit 2c88663](2c88663))

This PR also includes a lot of scratch_pad work for investigations of various issues (#282, #236, #241), and for an mplfinance presentation: including comparison of old and new api's, intraday animation with volumes, generation of animation gifs, etc.
@ChrisChiasson
Copy link

This is the most outstanding help from a package maintainer I have read in a very very long time.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
question Further information is requested
Projects
None yet
Development

No branches or pull requests

3 participants