把for循环变成数据帧.apply问题

2024-09-27 00:17:59 发布

您现在位置:Python中文网/ 问答频道 /正文

这是我在这里的第一个问题,所以请原谅我,如果我没有解释清楚,或过度。任务是将包含2个if语句的for循环转换为数据帧.apply而不是循环。我认为这样做的方法是将for循环中的if语句转换为一个已定义的函数,然后在.apply行中调用该函数,但只能到此为止。我甚至不确定我是不是想用正确的方法解决这个问题。如果需要,可以提供原始For循环代码。提前谢谢。你知道吗

目标是导入股票价格的csv,将一列中的价格与需要创建的移动平均线进行比较,如果>;MA,则买入,如果<;MA,则卖出。跟踪所有买入/卖出,并最终确定整体财富/回报。它就像一个for循环:对于价格中的每个x,使用2个if,将价格附加到一个列表中,以确定最终的财富。我想我已经到了要将已定义的函数调用到.apply行中的时候了,错误就消失了。在我下面的代码中,for循环使用中可能仍有一些不必要的延迟代码,但不应干扰.apply尝试,在我弄清楚之前,只会造成混乱的编码。你知道吗

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)

Tags: csvtofordataifstockcashprice
1条回答
网友
1楼 · 发布于 2024-09-27 00:17:59

检查docs for ^{}似乎需要使用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()一个利用Buy/Sell信号列的函数。你知道吗

相关问题 更多 >

    热门问题