Cuts columns in Pandas

I am trying to convert (well, a lot) a column of returned data into a column of closing prices. In Clojure, I would use reductionsone that is similar to reduce, but returns a sequence of all intermediate values.

eg.

$ c

0.12
-.13
0.23
0.17
0.29
-0.11

# something like this
$ c.reductions(init=1, lambda accumulator, ret: accumulator * (1 + ret)) 

1.12
0.97
1.20
1.40
1.81
1.61

NB: the actual closing price does not matter, therefore using 1 as the initial value. I just need a "mock" closing price.

The actual structure of my data is the DataFrame of the named columns of the TimeSeries. Iโ€™m probably looking for a function similar applymap, but I would prefer not to do something hacked with this function and reference the DF from the inside (which, I suppose, is one of the solutions to this problem?)

, , returns, ""? TimeSeries (returns, closing_price)?

+5
3

, ( ) pandas, reduce.

add, cumprod:

In [2]: c.add(1).cumprod()
Out[2]: 
0    1.120000
1    0.974400
2    1.198512
3    1.402259
4    1.808914
5    1.609934

, , init * c.add(1).cumprod().

. , , , , , , / , ( , , % timeit

+3

, expanding_apply :

In [1]: s
Out[1]:
0    0.12
1   -0.13
2    0.23
3    0.17
4    0.29
5   -0.11

In [2]: pd.expanding_apply(s ,lambda s: reduce(lambda x, y: x * (1+y), s, 1))

Out[2]:
0    1.120000
1    0.974400
2    1.198512
3    1.402259
4    1.808914
5    1.609934

100%, , expanding_apply , . reduce, , Clojure.

Docstring expanding_apply:

Generic expanding function application

Parameters
----------
arg : Series, DataFrame
func : function
    Must produce a single value from an ndarray input
min_periods : int
    Minimum number of observations in window required to have a value
freq : None or string alias / date offset object, default=None
    Frequency to conform to before computing statistic
center : boolean, default False
    Whether the label should correspond with center of window

Returns
-------
y : type of input argument
+4

For readability, I prefer the following solution:

returns = pd.Series([0.12, -.13, 0.23, 0.17, 0.29, -0.11])

initial_value = 100
cum_growth = initial_value * (1 + returns).cumprod()

>>> cum_growth
0    112.000000
1     97.440000
2    119.851200
3    140.225904
4    180.891416
5    160.993360
dtype: float64

If you want to include the initial value in a series:

>>> pd.concat([pd.Series(initial_value), cum_growth]).reset_index(drop=True)
0    100.000000
1    112.000000
2     97.440000
3    119.851200
4    140.225904
5    180.891416
6    160.993360
dtype: float64
0
source

All Articles