Python Pandas迭代和索引编制

问题描述 投票:0回答:1

我正在计算处于其1年高点的股票的每日价值-处于其1年低点的股票的每日价值。我有一个名为stocks的股票价格数据框。

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

#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。

python pandas for-loop indexing iteration
1个回答
0
投票
# 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:]

Booyah!

© www.soinside.com 2019 - 2024. All rights reserved.