首页 > 解决方案 > Python Pandas 迭代和索引

问题描述

我正在计算处于 1 年高点的股票数量的每日价值 - 处于 1 年低点的股票。stocks我有一个用股票价格调用的 DataFrame 。

以下是正确的(我认为),但效率极低。

#get output frame
high_minus_low = pd.DataFrame(columns = ["High minus Low"], index = stocks.index)


no_highs=0
no_lows=0


#assume 260 trading days in the year
for row in range(260):
    row = 260 + row

    #iterate over stocks in the index
    for col in range(len(stocks.columns)):
        latest = stocks.iloc[row,col]
        high = stocks.iloc[(row-260):row, col].max()
        low = stocks.iloc[(row-260):row, col].min()
        if latest >= high: no_highs = no_highs +1
        if latest <= low: no_lows = no_lows + 1

    #write to output
    high_minus_low.iloc[row,0] = no_highs - no_lows
    no_highs=0
    no_lows=0
    print(".\n")

任何人都可以提出更有效的实施方案吗?

任何人都可以建议一个依赖于索引(在日期中完成)而不是像我一样增加/减少坐标的实现吗?

提前谢谢你 - 我非常喜欢 python/编码初学者。

[编辑:]

输入样本:

Instrument     @AMZN  U:ABT  U:AES     @ABMD  ...  @MNST   U:LIN   @SBAC     @CHTR
Field              P      P      P         P  ...      P       P       P         P
Dates                                         ...                                 
2018-04-27  1572.620  59.56  12.31  301.7400  ...  56.19  153.23  158.95  263.3250
2018-04-30  1566.130  58.13  12.24  300.9500  ...  55.00  152.52  160.23  271.2900
2018-05-01  1582.260  58.82  12.21  310.5000  ...  55.20  153.30  157.50  279.3999
2018-05-02  1569.680  57.85  12.19  302.1399  ...  52.72  151.24  155.85  274.7800
2018-05-03  1572.075  57.93  12.30  335.5701  ...  52.31  152.84  156.16  271.3601

输出:

Dates                    
2018-04-27            NaN
2018-04-30            NaN
2018-05-01            NaN
2018-05-02            NaN
2018-05-03            NaN
                  ...
2020-04-07              0
2020-04-08              3
2020-04-09              6
2020-04-10              6
2020-04-13              4

输出简单的意思是:13 日的股票处于高位 - 4 日的股票处于低位。

标签: pythonpandasfor-loopindexingiteration

解决方案


# assume 260 Trading days in a year
df_min = stocks.rolling(window=260).min() 
df_max = stocks.rolling(window=260).max() 

#compare and sum
df_is_peak   = (stocks == df_max).sum(axis=1)
df_is_trough = (stocks == df_min).sum(axis=1)

#Compute the indicator. use only the last 260 days
high_minus_low = df_is_peak - df_is_trough
high_minus_low = high_minus_low[260:]

呸!


推荐阅读