Python 将for循环转换为dataframe.apply问题

Python 将for循环转换为dataframe.apply问题,python,pandas,Python,Pandas,这是我在这里的第一个问题,所以如果我没有解释清楚,或者说我说得过火,请原谅我。任务是将包含2个if语句的for循环转换为dataframe.apply,而不是循环。我认为这样做的方法是将for循环中的if语句转换为一个已定义的函数,然后在.apply行中调用该函数,但只能到此为止。我甚至不确定我是不是在用正确的方法解决这个问题。如有必要,可以提供原始For循环代码。提前谢谢 目标是导入股票价格的csv,将一列中的价格与需要创建的移动平均值进行比较,如果>MA,买入,如果ma,现金==1:#如果股

这是我在这里的第一个问题,所以如果我没有解释清楚,或者说我说得过火,请原谅我。任务是将包含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)
df2=pd.read_csv(“MSFT.csv”,index_col=0,parse_dates=True)。sort_index(axis=0,ascending=True)#可以让yahoo工作,但不能让quandl工作,因此从类中导入了csv文件
买价=0
售价=0
maWealth=1.0
现金=1
股票=0
sma=200
ma=np.round(df2['AdjClose'].rolling(window=sma,center=False).mean(),2)#创建要比较的移动平均线
n_天=长(df2['AdjClose'])
closePrices=df2['AdjClose']#仅使用原始csv导入中的一列
购买数据=[]
销售数据=[]
交易价格=[]
财富=[]
def myiffunc(调整关闭):
如果收盘价>ma,现金==1:#如果股价>ma,买入&如果尚未买入
买入价格=收盘价格[0+1]
购买数据。追加(购买价格)
交易价格。附加(购买价格)
现金=0
股票=1
如果收盘价
检查指数似乎需要使用
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
df2=。。。
df2['MovingAverage']=。。。
have_shares=False
定义我的职能(世界其他地区):
全球金融股
如果没有共享和行['AdjClose']>行['MovingAverage']:
#购买股票
have_shares=True
elif拥有所有股份和第['AdjClose']
但是,值得指出的是,您也可以使用numpy/pandas进行比较,只需将结果存储在另一列中:

df2['BuySignal'] = (df2.AdjClose > df2.MovingAverage)
df2['SellSignal'] = (df2.AdjClose < df2.MovingAverage)
df2['BuySignal']=(df2.AdjClose>df2.MovingAverage)
df2['SellSignal']=(df2.AdjClose
然后您可以
.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
df2=。。。
df2['MovingAverage']=。。。
have_shares=False
定义我的职能(世界其他地区):
全球金融股
如果没有共享和行['AdjClose']>行['MovingAverage']:
#购买股票
have_shares=True
elif拥有所有股份和第['AdjClose']
但是,值得指出的是,您也可以使用numpy/pandas进行比较,只需将结果存储在另一列中:

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

然后,您可以
.apply()
一个利用买入/卖出信号列的函数。

如果closePrices>ma和…
将抛出,那么该代码肯定不会运行
?现在还不清楚这是怎么回事。。。也许您可以使用小示例数据帧(以及相应的预期结果),如果closePrices>ma和…
会抛出,那么该代码肯定不会运行?现在还不清楚这是怎么回事。。。也许您可以有一个小示例DataFrame(以及相应的预期结果)