1

I have hourly stock data. I need a) to format it so that matplotlib ignores weekends and non-business hours and b) an hourly frequency.

The problem: Currently, the graph looks crammed and I suspect it is because matplotlib is taking into account 24 hours instead of 8, and 7 days a week instead of business days.

How do I tell pandas to only take into account business hours, M- F?

How I am graphing the data: I am looping through a list of price data dataframes, graphing each data frame:

mm = 0
for ii in df:

    Ddate = ii['Date']
    Pprice = ii['Price']
    d = Ddate.to_list()
    p = Pprice.to_list()

    dates = make_dt(d)
    prices = unstring(p)
    plt.figure()
    plt.plot(dates,prices)
    plt.title(stocks[mm])
    plt.grid(True)
    plt.xlabel('Dates')
    plt.ylabel('Prices')
    mm += 1

the graph: enter image description here

Rahel Miz
  • 159
  • 1
  • 9
  • I dont know if looping is required, since there is no sample data, but pandas offers a business hours offset : https://pandas.pydata.org/pandas-docs/stable/user_guide/timeseries.html#dateoffset-objects. – sammywemmy Feb 02 '20 at 22:06
  • but we are using matplotlib – Rahel Miz Feb 02 '20 at 22:10
  • Can you post a sample dataframe? Or share the plot data? – SKPS Feb 03 '20 at 01:47
  • Possible duplicate of: https://stackoverflow.com/questions/1273472/how-to-skip-empty-dates-weekends-in-a-financial-matplotlib-python-graph – SKPS Feb 03 '20 at 01:49
  • Does this answer your question? [How to skip empty dates (weekends) in a financial Matplotlib Python graph?](https://stackoverflow.com/questions/1273472/how-to-skip-empty-dates-weekends-in-a-financial-matplotlib-python-graph) – SKPS Feb 03 '20 at 02:35

1 Answers1

0

To fetch business days, you can use below function:

df["IsBDay"] = bool(len(pd.bdate_range(df['date'], df['date'])))

//Above line should add a new column into the DF as IsBday. //You can also use Lambda expression to check and have new column for BDay.

df['IsBDay'] = df['date'].apply(lambda x: 'True' if bool(len(pd.bdate_range(x, x))) else 'False')

Now create a new DF that will have only True IsBday column value and other columns.

df[df.IsBday != 'False']

Now your DF is ready for ploting. Hope this helps.

user2056463
  • 143
  • 1
  • 5