Howdy
Howdy

Reputation: 25

Using a function in a loop and storing all the results

So I created a function that returns the returns of quantile portfolios as a time series.

If I call Quantile_Returns(2014), the result (DataFrame) looks like this.

Date        Q1      Q2      Q3      Q4      Q5          
2014-02-28  6.20    4.87    5.41    5.04    4.91
2014-03-31  -0.50   0.05    1.55    1.36    1.49
2014-04-30  -0.17   0.20    0.33    -0.26   1.76
2014-05-30  2.69    1.95    1.95    2.11    2.29
2014-06-30  3.12    3.40    2.81    1.82    2.36
2014-07-31  -2.52   -2.34   -1.92   -2.36   -1.80
2014-08-29  4.60    3.87    4.50    4.65    3.58
2014-09-30  -3.29   -3.25   -3.51   -0.96   -1.76
2014-10-31  2.55    4.63    2.37    3.60    2.10
2014-11-28  0.88    2.08    1.26    4.46    2.83
2014-12-31  0.35    0.20    -0.19   1.01    0.34
2015-01-30  -2.97   -2.63   -3.44   -2.32   -2.61

Now I would want to call this function for a number of years time_period = list(range(1960,2021)) and get a result that is a time series which goes from 1960 to 2021.

I tried like this

time_period = list(range(1960,2021))
for j in time_period:
    if j == 1960:
        Quantile = pd.DataFrame(Quantile_Returns(j))
    else:
        Quantile = pd.concat(Quantile, Quantile_Returns(j+1))

But It did not work. The Error is:

TypeError: first argument must be an iterable of pandas objects, you passed an object of type "DataFrame"

How can I implement this?

Thank you!

Upvotes: 1

Views: 57

Answers (1)

Nick Matteo
Nick Matteo

Reputation: 4553

Try replacing the whole loop with

Quantile = pd.concat(Quantile_Returns(j) for j in range(1960, 2021))

pd.concat is expecting a sequence of pandas objects, and in the second pass through your loop you are giving it a DataFrame as the first argument (not a sequence of DataFrames). Also, the second argument should be an axis to concatenate on, not another DataFrame.

Here, I just passed it the sequence of all the DataFrames for different years as the first argument (using a generator expression).

Upvotes: 1

Related Questions