dimanche 3 juillet 2016

Pandas: reindex with custom function

I am looking for a way to reindex data with custom a function. My data looks as follows:

                        AAA   BBB   CCC   DDD
Time                                             
2009-01-30 09:30:00  6407.04  43.90  44.01  85.11
2009-01-30 09:39:00  6403.20  43.82  44.01  84.93
2009-01-30 09:40:00  6400.00  43.90  44.03  84.90
2009-01-30 09:45:00  6396.16  43.97  44.04  84.91
2009-01-30 09:48:00  6393.60  44.02  44.07  84.81
2009-01-30 09:55:00  6400.00  44.31  44.14  84.78
2009-01-30 09:56:00  6406.40  44.36  44.16  84.57
2009-01-30 09:59:00  6426.24  44.36  44.11  84.25
2009-01-30 10:00:00  6438.40  44.32  44.09  84.32
2009-01-30 10:06:00  6495.36  44.43  44.16  84.23  

Its a minute data of some stocks prices. I would like to split the trading day into 5 parts and resample my data. I start with creating custom index:

index_date = pd.date_range('2009-01-30', '2016-03-01')
    index_date = pd.Series(index_date)
    index_time = pd.date_range('09:30:00', '16:00:00', freq='78min')
    index_time = pd.Series(index_time.time)

    index = index_date.apply(
        lambda d: index_time.apply(
            lambda t: datetime.combine(d, t)
            )
        ).unstack().sort_values().reset_index(drop=True)

Lets assume that I want to apply basic percent change function:

def percent_change(x):
    if len(x):
        return (x[-1]-x[0])/x[0]

How could I do that?

Aucun commentaire:

Enregistrer un commentaire