Compute a compounded return series in Python

后端 未结 3 1777
礼貌的吻别
礼貌的吻别 2021-02-02 02:21

Greetings all, I have two series of data: daily raw stock price returns (positive or negative floats) and trade signals (buy=1, sell=-1, no trade=0).

The raw price retur

3条回答
  •  旧巷少年郎
    2021-02-02 03:24

    imagine I have a DataMatrix with closing prices, some indicator value, and a trade signal like this:

     >>> data_matrix
                            close          dvi            signal
     2008-01-02 00:00:00    144.9          0.6504         -1             
     2008-01-03 00:00:00    144.9          0.6603         -1             
     2008-01-04 00:00:00    141.3          0.7528         -1             
     2008-01-07 00:00:00    141.2          0.8226         -1             
     2008-01-08 00:00:00    138.9          0.8548         -1             
     2008-01-09 00:00:00    140.4          0.8552         -1             
     2008-01-10 00:00:00    141.3          0.846          -1             
     2008-01-11 00:00:00    140.2          0.7988         -1             
     2008-01-14 00:00:00    141.3          0.6151         -1             
     2008-01-15 00:00:00    138.2          0.3714         1   
    

    I use the signal to create a DataMatrix of returns based on the trade signal:

    >>> get_indicator_returns()
    
                       indicator_returns    
    2008-01-02 00:00:00    NaN            
    2008-01-03 00:00:00    0.000483       
    2008-01-04 00:00:00    0.02451        
    2008-01-07 00:00:00    0.0008492      
    2008-01-08 00:00:00    0.01615        
    2008-01-09 00:00:00    -0.01051       
    2008-01-10 00:00:00    -0.006554      
    2008-01-11 00:00:00    0.008069       
    2008-01-14 00:00:00    -0.008063      
    2008-01-15 00:00:00    0.02201 
    

    What I ended up doing is this:

    def get_compounded_indicator_cumulative(self):
    
        indicator_dm = self.get_indicator_returns()
        dates = indicator_dm.index
    
        indicator_returns = indicator_dm['indicator_returns']
        compounded = array(zeros(size(indicator_returns)))
    
        compounded[1] = indicator_returns[1]
    
        for i in range(2, len(indicator_returns)):
    
            compounded[i] = (1 + compounded[i-1]) * (1 + indicator_returns[i]) - 1
    
        data = {
            'compounded_returns': compounded
        }
    
        return DataMatrix(data, index=dates)
    

    For some reason I really struggled with this one...

    I'm in the process of converting all my price series to PyTables. Looks promising so far.

提交回复
热议问题