Dynamic trailing one year request

For the following code, how to I set the end date as today and the start date as one year previous? I would like the formula to be dynamic so that I can run this daily and it always generates the request for the trailing previous year.

df, e = ek.get_data(['AEFS.L'], 
['TR.RNSFilerName',     
'TR.RNSAnnouncedDate',                     
'TR.RNSTransactionType',                     
'TR.RNSARNumShrsTransacted',                     
'TR.RNSARPctOSTransacted',                     
'TR.RNSARTransactionPrice',                     
'TR.RNSARMktValTransaction',                     
'TR.RNSARTotShrsPostTrans',                     
'TR.RNSARPctOSPostTrans'])

start_date = '2019-01-31'
end_date = '2020-01-31'

df['RNS Announced Date'] = pd.to_datetime(df['RNS Announced Date'])mask = (df['RNS Announced Date'] > start_date) & (df['RNS Announced Date'] <= end_date)

df = df.loc[mask]

df

Best Answer

  • Hi @bill39

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

    df, e = ek.get_data(['AEFS.L'],
                        ['TR.RNSFilerName',
                         'TR.RNSAnnouncedDate',
                         'TR.RNSTransactionType',
                         'TR.RNSARNumShrsTransacted',
                         'TR.RNSARPctOSTransacted',
                         'TR.RNSARTransactionPrice',
                         'TR.RNSARMktValTransaction',
                         'TR.RNSARTotShrsPostTrans',
                         'TR.RNSARPctOSPostTrans'])
    end_date = date.today()
    start_date = end_date - timedelta(days=365)

    end_date_str = datetime.strftime(end_date, "%Y-%m-%d")
    start_date_str = datetime.strftime(start_date, "%Y-%m-%d")

    df['RNS Announced Date'] = pd.to_datetime(df['RNS Announced Date'])
    mask = (df['RNS Announced Date'] > start_date_str) & (df['RNS Announced Date'] <= end_date_str)
    df = df.loc[mask]
    df