小编use*_*048的帖子

使用 numpy 广播/矢量化从其他数组构建新数组

我正在研究 Quantopian 模型的股票排名因素。他们建议避免在自定义因子中使用循环。但是,我不确定在这种情况下如何避免循环。

def GainPctInd(offset=0, nbars=2):  
    class GainPctIndFact(CustomFactor):  
        window_length = nbars + offset  
        inputs = [USEquityPricing.close, ms.asset_classification.morningstar_industry_code]  
        def compute(self, today, assets, out, close, industries):
            # Compute the gain percents for all stocks
            asset_gainpct = (close[-1] - close[offset]) / close[offset] * 100  

            # For each industry, build a list of the per-stock gains over the given window  
            gains_by_industry = {}  
            for i in range(0, len(industries)):  
                industry = industries[0,i]  
                if industry in gains_by_industry:  
                    gains_by_industry[industry].append(asset_gainpct[i])  
                else:  
                    gains_by_industry[industry] = [asset_gainpct[i]]

            # Loop through each …
Run Code Online (Sandbox Code Playgroud)

python arrays optimization numpy vectorization

5
推荐指数
1
解决办法
290
查看次数

标签 统计

arrays ×1

numpy ×1

optimization ×1

python ×1

vectorization ×1