-
Notifications
You must be signed in to change notification settings - Fork 658
New issue
Have a question about this project? # for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “#”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? # to your account
X-Axis Date and Time series #573
Comments
So, I am making progress albeit with great difficulty. With the help of this I have managed to get the first attachement by show and then manually saving. However, when using savefig I get the second attachement. My questions now are code:
|
This is not a trivial problem, but it is do-able, just a bit tricky. Also, for what it's worth, I am hoping at some point to build a more generalized solution into mplfinance to make it easier for users to do things like this. In the meantime this is what we have and you are mostly on the right track. First, I have some questions about your questions because I don't understand them entirely.
That said, ultimately what do you want? Would you be satisfied with one date label per day at the beginning of each day, or maybe at the middle of each day? I'm going to play around and see what I can get to work. |
I worked up some sample code. Let me know if this works for you: import mplfinance as mpf
import yfinance as yf
import datetime
df = yf.download('DIA',start='2022-11-07',end='2022-11-15',interval='15m')
ticks = []
tlabs = []
dates = sorted(list(set([d.date() for d in df.index])))
for d1 in dates:
d2 = d1 + datetime.timedelta(days=1)
ts = df.loc[d1:d2].index[0] # first timestamp of each day
ticks.append(df.index.get_loc(ts))
tlabs.append(d1.strftime('%b %d'))
fig, axlist = mpf.plot(df,type='candle',xrotation=0,style='yahoo',tight_layout=True,returnfig=True)
axlist[-2].set_xticks(ticks,labels=tlabs,ha='left')
mpf.show() |
Hello Daniel and thanks for the response, a great relief to get some help with this.
I copied your exact code, but get the following error when executed:
C:\TEMP\PYTHON>python test_multiple_days.py
[*********************100%***********************] 1 of 1 completed
Traceback (most recent call last):
File "test_multiple_days.py", line 17, in <module>
axlist[-2].set_xticks(ticks,labels=tlabs,ha='left')
TypeError: set_xticks() got an unexpected keyword argument 'labels'
…________________________________
From: Daniel Goldfarb ***@***.***>
Sent: Friday, December 2, 2022 2:29 PM
To: matplotlib/mplfinance ***@***.***>
Cc: tdavidge ***@***.***>; Author ***@***.***>
Subject: Re: [matplotlib/mplfinance] X-Axis Date and Time series (Issue #573)
I worked up some sample code. Let me know if this works for you:
import mplfinance as mpf
import yfinance as yf
import datetime
df = yf.download('DIA',start='2022-11-07',end='2022-11-15',interval='15m')
ticks = []
tlabs = []
dates = sorted(list(set([d.date() for d in df.index])))
for d1 in dates:
d2 = d1 + datetime.timedelta(days=1)
ts = df.loc[d1:d2].index[0] # first timestamp of each day
ticks.append(df.index.get_loc(ts))
tlabs.append(d1.strftime('%b %d'))
fig, axlist = mpf.plot(df,type='candle',xrotation=0,style='yahoo',tight_layout=True,returnfig=True)
axlist[-2].set_xticks(ticks,labels=tlabs,ha='left')
mpf.show()
[image]<https://na01.safelinks.protection.outlook.com/?url=https%3A%2F%2Fuser-images.githubusercontent.com%2F11164790%2F205370405-1439ae45-0ce1-4eea-8925-d56904ec36ef.png&data=05%7C01%7C%7C9859036347e54cb1c81908dad49b8b66%7C84df9e7fe9f640afb435aaaaaaaaaaaa%7C1%7C0%7C638056061764653292%7CUnknown%7CTWFpbGZsb3d8eyJWIjoiMC4wLjAwMDAiLCJQIjoiV2luMzIiLCJBTiI6Ik1haWwiLCJXVCI6Mn0%3D%7C3000%7C%7C%7C&sdata=jSVLLPNSIyvW%2FBjiHjrPMtZjCa7F21RToKm6%2F8btass%3D&reserved=0>
—
Reply to this email directly, view it on GitHub<https://na01.safelinks.protection.outlook.com/?url=https%3A%2F%2Fgithub.heygears.com%2Fmatplotlib%2Fmplfinance%2Fissues%2F573%23issuecomment-1335718597&data=05%7C01%7C%7C9859036347e54cb1c81908dad49b8b66%7C84df9e7fe9f640afb435aaaaaaaaaaaa%7C1%7C0%7C638056061764653292%7CUnknown%7CTWFpbGZsb3d8eyJWIjoiMC4wLjAwMDAiLCJQIjoiV2luMzIiLCJBTiI6Ik1haWwiLCJXVCI6Mn0%3D%7C3000%7C%7C%7C&sdata=D4RA0qwN3eoFeg43Bw6qfE40Ob5NQb2E6BWZ6WC%2F2ns%3D&reserved=0>, or unsubscribe<https://na01.safelinks.protection.outlook.com/?url=https%3A%2F%2Fgithub.heygears.com%2Fnotifications%2Funsubscribe-auth%2FA4OQSNZYIIR2URMXHETKUTDWLJEZ5ANCNFSM6AAAAAASNRL6PM&data=05%7C01%7C%7C9859036347e54cb1c81908dad49b8b66%7C84df9e7fe9f640afb435aaaaaaaaaaaa%7C1%7C0%7C638056061764653292%7CUnknown%7CTWFpbGZsb3d8eyJWIjoiMC4wLjAwMDAiLCJQIjoiV2luMzIiLCJBTiI6Ik1haWwiLCJXVCI6Mn0%3D%7C3000%7C%7C%7C&sdata=NdukdCd%2FRwUBawalP7Y7F3fk6blboORbni5qVpSrgKI%3D&reserved=0>.
You are receiving this because you authored the thread.Message ID: ***@***.***>
|
Perhaps you have an older version of matplotlib. Don't upgrade just yet as that may introduce too many new changes. Rather try splitting up setting ticks and labels as in your code: axlist[-2].xaxis.set_ticks(ticks)
axlist[-2].set_xticklabels(tlabs) ( |
Hey Daniel, to try to clarify my somewhat cryptic issues .. heh
a) I'd like to be able to retain the x-axis time ticks, but add the date as a say 2nd sub-label below them. So your chart would be great, if it also included vertical hourly time ticks in the grid. I remember seeing this done somewhere (I think it was with plotly). In the end I need to be able to save same to a full page A4 landscaped jpg, which will be printed and also included in a xlsx spreadsheet. I've just spoken with my partner and at this point, it is more important to get the date right and leave the time ticks for another effort.
b) There is definately something not right with the savefig, as you can tell from the two images I posted. They were created with the exactly the same code, with and without a savefig attribute in the mpf.plot command. I tried with just savefig(filename) and it still came out different.
Ultimately, your chart would be great, date to the beginning of the day is just fine thanks, albeit, show and savefig need to be the same result .. heh.
…________________________________
From: Daniel Goldfarb ***@***.***>
Sent: Friday, December 2, 2022 1:41 PM
To: matplotlib/mplfinance ***@***.***>
Cc: tdavidge ***@***.***>; Author ***@***.***>
Subject: Re: [matplotlib/mplfinance] X-Axis Date and Time series (Issue #573)
This is not a trivial problem, but it is do-able, just a bit tricky. Also, for what it's worth, I am hoping at some point to build a more generalized solution into mplfinance to make it easier for users to do things like this. In the meantime this is what we have and you are mostly on the right track.
First, I have some questions about your questions because I don't understand them entirely.
"a) how to get the short date (no year) to appear horizontally centered below each of the 5 days time bars"
Is your question about formatting (not showing a year) or about where the tick appears (in the middle of each day vs the beginning of each day)? I am fairly certain that the tick label must appear where the tick itself is. But there may be a matplotlib work-around (that I have not tried yet) such as this<https://na01.safelinks.protection.outlook.com/?url=https%3A%2F%2Fstackoverflow.com%2Fquestions%2F28615887%2Fhow-to-move-a-tick-label-in-matplotlib&data=05%7C01%7C%7C64e804c8239441abe1fd08dad494c2ec%7C84df9e7fe9f640afb435aaaaaaaaaaaa%7C1%7C0%7C638056032632281954%7CUnknown%7CTWFpbGZsb3d8eyJWIjoiMC4wLjAwMDAiLCJQIjoiV2luMzIiLCJBTiI6Ik1haWwiLCJXVCI6Mn0%3D%7C3000%7C%7C%7C&sdata=A9AYWPDgPQ3u1Tclq3YEIlteBWKDg7Fu3K6S2BskdnE%3D&reserved=0>. If that is what this question is about (shifting the tick labels left or right relative to the ticks themselves) it can be done but lets first focus on getting the exact ticks that you want.
"b) why the difference between showing and saving the output ?"
What exactly is the difference between the First Image<https://na01.safelinks.protection.outlook.com/?url=https%3A%2F%2Fuser-images.githubusercontent.com%2F119343415%2F204861777-c07bea76-f492-44a7-aabe-f6fdff19c9f4.png&data=05%7C01%7C%7C64e804c8239441abe1fd08dad494c2ec%7C84df9e7fe9f640afb435aaaaaaaaaaaa%7C1%7C0%7C638056032632281954%7CUnknown%7CTWFpbGZsb3d8eyJWIjoiMC4wLjAwMDAiLCJQIjoiV2luMzIiLCJBTiI6Ik1haWwiLCJXVCI6Mn0%3D%7C3000%7C%7C%7C&sdata=TFTjlGNsWs3p4wT%2FvB5yDjHPgyKPmqNjGQl19QfEHjM%3D&reserved=0>, and this Second Image<https://na01.safelinks.protection.outlook.com/?url=https%3A%2F%2Fuser-images.githubusercontent.com%2F119343415%2F204861780-16b3aacd-dc5a-44ae-8bf5-48f936898d1e.jpg&data=05%7C01%7C%7C64e804c8239441abe1fd08dad494c2ec%7C84df9e7fe9f640afb435aaaaaaaaaaaa%7C1%7C0%7C638056032632281954%7CUnknown%7CTWFpbGZsb3d8eyJWIjoiMC4wLjAwMDAiLCJQIjoiV2luMzIiLCJBTiI6Ik1haWwiLCJXVCI6Mn0%3D%7C3000%7C%7C%7C&sdata=CQTGs783QCIIeZNww59K%2BGqfqnrCxM1cTyghsegCqPE%3D&reserved=0>? It sounds like you are implying that the code is exactly the same except for how you saved the plot, which at first doesn't make sense to me because the x-axis is clearly formatted differently. Maybe I'm missing something. On the other hand, indeed it could be ... I faintly recall (will have to try to find the issue/discussion) seeing something, maybe a year ago, about matplotlib's savefig method doing it's own axis formatting, ignoring what you otherwise specified when calling .show(). I will see if I can find that.
"c) why is the show result offset to the right ? in the display window I cannot see the full price, not is there a ylabel"
It could be due to tight_layout. Try it without tight_layout. If that is the issue, you may be able to use tight_layout in combination with scale_padding. See this answer for more information about scale_padding<https://na01.safelinks.protection.outlook.com/?url=https%3A%2F%2Fgithub.heygears.com%2Fmatplotlib%2Fmplfinance%2Fissues%2F212%23issuecomment-655603896&data=05%7C01%7C%7C64e804c8239441abe1fd08dad494c2ec%7C84df9e7fe9f640afb435aaaaaaaaaaaa%7C1%7C0%7C638056032632281954%7CUnknown%7CTWFpbGZsb3d8eyJWIjoiMC4wLjAwMDAiLCJQIjoiV2luMzIiLCJBTiI6Ik1haWwiLCJXVCI6Mn0%3D%7C3000%7C%7C%7C&sdata=rRcM31ybThUgisosdgh5y20FbI6hOjnYbJBh0difXiI%3D&reserved=0>
That said, ultimately what do you want? Would you be satisfied with one date label per day at the beginning of each day, or maybe at the middle of each day? I'm going to play around and see what I can get to work.
—
Reply to this email directly, view it on GitHub<https://na01.safelinks.protection.outlook.com/?url=https%3A%2F%2Fgithub.heygears.com%2Fmatplotlib%2Fmplfinance%2Fissues%2F573%23issuecomment-1335668401&data=05%7C01%7C%7C64e804c8239441abe1fd08dad494c2ec%7C84df9e7fe9f640afb435aaaaaaaaaaaa%7C1%7C0%7C638056032632281954%7CUnknown%7CTWFpbGZsb3d8eyJWIjoiMC4wLjAwMDAiLCJQIjoiV2luMzIiLCJBTiI6Ik1haWwiLCJXVCI6Mn0%3D%7C3000%7C%7C%7C&sdata=xi%2BbOEcdYYElaqcsTnQIrArOpQfjBzXOiFi1wmY8Sjc%3D&reserved=0>, or unsubscribe<https://na01.safelinks.protection.outlook.com/?url=https%3A%2F%2Fgithub.heygears.com%2Fnotifications%2Funsubscribe-auth%2FA4OQSN6NIULE7BNLBMAZPK3WLI7D3ANCNFSM6AAAAAASNRL6PM&data=05%7C01%7C%7C64e804c8239441abe1fd08dad494c2ec%7C84df9e7fe9f640afb435aaaaaaaaaaaa%7C1%7C0%7C638056032632281954%7CUnknown%7CTWFpbGZsb3d8eyJWIjoiMC4wLjAwMDAiLCJQIjoiV2luMzIiLCJBTiI6Ik1haWwiLCJXVCI6Mn0%3D%7C3000%7C%7C%7C&sdata=ZK4q3z96Vczn%2FYooonPBbakNG6JUk4ZGACR%2FxANT4VQ%3D&reserved=0>.
You are receiving this because you authored the thread.Message ID: ***@***.***>
|
a) I saw once that there is a way (in matplotlib) to create "two level" axis labels, so that you have one level showing the times (perhaps every two hours) and another level showing the date, but I would have to research how to do it. A simpler solution, that may not be exactly what you want, would be to format the datetime to include both date and time and modify the code to show maybe 2 or 3 ticks per day (instead of 1 tick per day as I had it). Alternatively, do major ticks as I showed (one per day with date), and do minor ticks perhaps hourly. b) Yes, as I mentioned before there is definitely some kind of a problem with savefig() tries to do its own axis formatting. I ran into the once before and can't remember what the solution was. I am going to spend a little time looking into this savefig issue, |
I did some playing around, and I was able to get both dates and times on separate levels of the tick labels, using major and minor ticks. Please let me know if this is something like what you are trying to do: ticks = []
tlabs = []
mitks = []
milab = []
dates = sorted(list(set([d.date() for d in df.index])))
for d1 in dates:
# Major Ticks:
d2 = d1 + datetime.timedelta(days=1)
ts = df.loc[d1:d2].index[0]
ticks.append(df.index.get_loc(ts))
# line feed at beginning of label so it appears a lower below the x-axis:
tlabs.append('\n'+d1.strftime('%b %d'))
# Minor Ticks:
mitks.append(ticks[-1]+0.1)
milab.append('09:30')
ts = df.loc[str(d1)+' 13:00':d2].index[0]
mitks.append(df.index.get_loc(ts))
milab.append('13:00')
fig, axlist = mpf.plot(df,type='candle',xrotation=0,style='yahoo',tight_layout=True,returnfig=True,figratio=(2,1))
axlist[-2].set_xticks(ticks)
axlist[-2].set_xticklabels(tlabs, ha='left')
axlist[-2].set_xticks(mitks,minor=True)
axlist[-2].set_xticklabels(milab, ha='center', minor=True, rotation=0)
mpf.show() The result: |
Hey Daniel,
Thank you so much for your efforts, that is excellent and if we can resolve the savefig issues is exactly what I was after.
I am however still getting that weird right hand offset when showing the figure and am losing the y axis and labels as a result.
The savefig behavior has also changed and now shows the attached. Note savefig displays the y axis correctly, but messes with the timing ticks.
|
@tdavidge Regarding savefig, please try the following. It worked for me. Do not use the savefig kwarg of fig, axlist = mpf.plot(df,type='candle',xrotation=0,style='yahoo',tight_layout=True,returnfig=True,figratio=(2,1))
axlist[-2].set_xticks(ticks)
axlist[-2].set_xticklabels(tlabs, ha='left')
axlist[-2].set_xticks(mitks,minor=True)
axlist[-2].set_xticklabels(milab, ha='center', minor=True, rotation=0)
fig.savefig( 'myplot.pdf', bbox_inches='tight' ) That should work OK. If not, please post the images from the two ways of saving (using the above code). But again, do not post via email since that doesn't work. Please post directly to the GitHub website. Thanks. |
Hi Daniel, that worked great. Duly noted on the email reply, my apologies. Thanks again for all the assistance, I am now trying to port your code to some existing charts that I was struggling with that use a different dataframe format to be able to plot multiple series across a similar timeframe. Will let you know how I get on. |
Glad to hear it.
Good luck. If you are willing, please share the charts once you get them looking the way you want. It's always exciting to see the things people are doing with mplfinance. All the best. --Daniel |
I am trying to create a 5 day chart of Intraday Stock data using mplfinance. From Open to Close only, no data gaps. I can get a chart to save and/or show but am struggling with formatting the grid spacing and the x-axis interval/labels. I have been trying to get this working in matplotlib for what seems like an age now and I just cannot get it work. At least with mplfinance I was able to get a chart to work. I'm simply not good enough at python coding to understand how to format the xaxis I am afraid.
My question obviously is how to format grid and x-axis to line the grid with at least the open of the day (as in on change of date) so I can see the overnight GAP, and say a frequency of hourly between 09:30am and 4:00pm. I apologize in advance for my ignorance but this is all kinda new to me and having been trying all manner of examples that I do not understand, this is my last resort.
Any assistance would be very much appreciated.
Using python 3.7 and mplfinance v0.12.9b5 on windows 11 pro.
This gives me the attached chart.
The text was updated successfully, but these errors were encountered: