Home > Software design >  Get nearest date to a specific date from range of dates
Get nearest date to a specific date from range of dates

Time:12-15

I am trying to get the closest date (in a range of dates) to any given date. I tried to use the answer provided in this post - Find the closest date to a given date

It doesn't seem to work for my particular issue though. How could I compare one date to multiple dates and retrieve the date that is closest to the original given date from the range of dates? If you could give me some assistance I'd really appreciate it.

import yfinance as yf
import pandas as pd
import datetime
import time
from datetime import datetime
from datetime import timedelta, date

#Code to retrieve given date

EndDate = date.today()   timedelta(days=90)

Original_Date = str(EndDate.strftime("%Y%m%d"))


#Code to retrieve range of dates

ticker = yf.Ticker("MSFT")

Range_Of_Dates = ticker.options


#Code to retrieve nearest date to give date

def nearest(Range_Of_Dates, Original_Date):
    return min(Range_Of_Dates, key=lambda x: abs(x - Original_Date)) 

nearest_date = nearest(Range_Of_Dates, Original_Date)

print(nearest_date)

The issue is that I keep receiving this error

TypeError: unsupported operand type(s) for -: 'str' and 'str'

CodePudding user response:

You are comparing strings with strings. If you print out the Original_Date and Range_Of_Dates types. Then it will be:

print('Range_Of_Dates', type(Range_Of_Dates[0]), 'Original_Date', type(Original_Date))

Output

Range_Of_Dates <class 'str'> Original_Date <class 'str'>

The Original_Date variable is not needed. The dataframe also needs a Timestamp type for comparison. I converted the EndDate variable to the required format.

In the dataframe itself, you need an index for comparison (they are Timestamp format). You can get them like this:

df = yf.download('MSFT')

print(df.index)

Or

ticker.history(period="max").index

More details here and here.

As a result, the code should be:

import yfinance as yf
import pandas as pd
from datetime import timedelta, date


EndDate = pd.Timestamp(date.today()   timedelta(days=90))


ticker = yf.Ticker('MSFT')

Range_Of_Dates = ticker.history(period="max").index


def nearest(Range_Of_Dates, EndDate):
    return min(Range_Of_Dates, key=lambda x: abs(x - EndDate))

nearest_date = nearest(Range_Of_Dates, EndDate)

print(nearest_date)
  • Related