0

I am not quite advance in python and pandas yet.

I have a function which calculates returns of stocks under one strategy then outputs as Dataframe. E.g, if I want to calculate return from 2017 to 2019, the function output returns from 2017 to 2019, and if I want to calculates returns from 2010 to 2019, the function output returns from 2010 to 2019. And this function calculates one stock at a time.

Now, I have multiple stocks, I used this function in a for loop which loops through stocks to get its returns. I want to put all returns of different stocks into one dataframe. So I am thinking of pre-define a zeros Dataframe before the loop, then put returns into that Dataframe once at a loop.

The question I am having now is that its not easy to know in advance how many rows in returns Dataframe, so I could not define the row of the zero Dataframe which will contain all returns later (only know the number of columns as easily know number of stocks), so I wonder is there a way I could put return series as a whole into the zero Dataframe? (like put data column by column)???

Hope I stated my question clear enough.....

Thanks very much!!

Please don't advise me not to use loops at this stage ....now I re-state my question as: In the code below:

for k in ticker:
    stock_price = dataprepare(start_date, end_date, k)
    mask_end, mask_beg = freq(stock_price, trading_period)
    signal_trade = singals(fast_window, slow_window, stock_price, mask_end)
    a = basiccomponent(fast_window, slow_window, stock_price, mask_beg, mask_end, year, signal_trade, v)[2]

dataprepare, freq, singals and basiccomponent are self defined functions. a is a return Dataframe, I want to save all 'a's from each loop in a Dataframe, something like append, but append on the columns after each loop, such as:

a.append(a)

instead of appending rows, I want to append columns, so how can I do it?

Esther Li
  • 25
  • 1
  • 6
  • First, if you're doing anything in Pandas with a `for-loop`, it's probably not the correct implementation. Second, please provide a [Minimal, Reproducible Example](https://stackoverflow.com/help/minimal-reproducible-example). It's possible to `.groupby` the stock and aggregate some function. Also, [Apply multiple functions to multiple groupby columns](https://stackoverflow.com/questions/14529838/apply-multiple-functions-to-multiple-groupby-columns). – Trenton McKinney Nov 02 '19 at 01:23
  • what is the correct implementation for replacing for loops in pandas ? – Esther Li Nov 02 '19 at 01:37
  • Calculations should be vectorized, not `for-loops`. [Fast, Flexible, Easy and Intuitive: How to Speed Up Your Pandas Projects](https://realpython.com/fast-flexible-pandas/) – Trenton McKinney Nov 02 '19 at 01:38

0 Answers0