2021年4月23日星期五

Getting the datetime index of a value in a column

I am working on a technical analysis project for which I need to annotate the matplotlib chart for buy/sell signals. As I am getting data from the yfinance module, I automatically have a DateTimeIndex in my DataFrame. My DataFrame looks like this:

Date        Close       Upper       SMA         Lower       Buy  Sell  2020-05-21  231.389999  219.042175  207.178002  195.313829  NaN  231.389999   2020-05-22  234.910004  222.051354  209.420002  196.788650  NaN  234.910004  2020-05-26  232.199997  224.164115  211.655002  199.145889  NaN  NaN    2020-05-27  229.139999  225.151643  213.966502  202.781360  NaN  NaN   2020-05-28  225.460007  226.004370  215.530002  205.055633  NaN  NaN  2020-05-29  225.089996  226.911921  216.549001  206.186082  NaN  NaN  2020-06-01  231.910004  228.365279  218.031001  207.696723  NaN  NaN   

When there is a not NaN value in the Sell/Buy column I want to get the Date for it.

So if the sell price is at 231.389999, I want the date which is 2020-05-21.

So far I have tried:

for i in range(0, len(df['Sell'])):      if pd.notnull(df['Buy'][i]):          date = df[df['Buy'] == i].index   

But I get an empty list: DatetimeIndex([], dtype='datetime64[ns]', name='Date', freq=None)

Once I get the Date value, I can input is as a x-axis value and the y-axis value would be the notNaN value for annotating the chart.

What would be the right way to get the DateTimeIndex?

https://stackoverflow.com/questions/67239379/getting-the-datetime-index-of-a-value-in-a-column April 24, 2021 at 12:40PM

没有评论:

发表评论