将for循环变成dataframe.apply问题

时间:2019-02-08 05:01:16

标签: python pandas

这是我在此遇到的第一个问题,因此,如果我不清楚或解释不清,请原谅我。任务是将一个包含2个if语句的for循环转入dataframe.apply而不是循环。我认为这样做的方法是将for循环内的if语句转换为已定义的函数,然后在.apply行中调用该函数,但只能做到这一点。甚至不确定我是否试图以正确的方式解决这个问题。如有必要,可以提供原始的For循环代码。预先感谢。

目标是导入一个csv的股票价格,将一栏中的价格与需要创建的移动平均线进行比较,如果> MA,则购买,如果

df2 = pd.read_csv("MSFT.csv", index_col=0, parse_dates=True).sort_index(axis=0 ,ascending=True)      #could get yahoo to work but not quandl, so imported the csv file from class

buyPrice = 0
sellPrice = 0
maWealth = 1.0
cash = 1
stock = 0
sma = 200

ma = np.round(df2['AdjClose'].rolling(window=sma, center=False).mean(), 2)   #to create the moving average to compare to
n_days = len(df2['AdjClose'])

closePrices = df2['AdjClose']  #to only work with one column from original csv import

buy_data = []
sell_data = []
trade_price = []
wealth = []

def myiffunc(adjclose):
    if closePrices > ma and cash == 1:    # Buy if stock price > MA & if not bought yet
        buyPrice = closePrices[0+ 1]
        buy_data.append(buyPrice)
        trade_price.append(buyPrice)
        cash = 0
        stock = 1

    if closePrices < ma and stock == 1:     # Sell if stock price < MA and if you have a stock to sell
        sellPrice = closePrices[0+ 1]
        sell_data.append(sellPrice)
        trade_price.append(sellPrice)
        cash = 1
        stock = 0

        wealth.append(1*(sellPrice / buyPrice))

closePrices.apply(myiffunc)

1 个答案:

答案 0 :(得分:0)

检查docs for apply,似乎需要使用index=1版本来一次处理每一行,并传递两列:移动平均线和收盘价。

类似这样的东西:

df2 = ...
df2['MovingAverage'] = ...

have_shares = False

def my_func(row):
    global have_shares

    if not have_shares and row['AdjClose'] > row['MovingAverage']:
        # buy shares
        have_shares = True
    elif have_shares and row['AdjClose'] < row['MovingAverage']:
        # sell shares
        have_shares = False

但是,值得指出的是,您也可以使用numpy / pandas进行比较,只需将结果存储在另一列中即可。

df2['BuySignal'] = (df2.AdjClose > df2.MovingAverage)
df2['SellSignal'] = (df2.AdjClose < df2.MovingAverage)

然后,您可以.apply()使用买/卖信号列的功能。