如何在熊猫数据框中为N天的损益百分比编写函数?

时间:2019-06-25 17:44:32

标签: python pandas math

我正在编写一个N天的损益函数,并将其在pandas数据框上实现。但是在我赋予代码的条件下,我做错了。

Date        Open Price High Price Low Price Last Price Close Price
2017-05-15  885.50     928.00     885.40     911.25     912.20
2017-05-16  908.20     909.00     890.20     894.00     894.70
2017-05-17  894.90     899.15     880.50     889.00     887.05
2017-05-18  888.00     917.90     865.20     866.15     871.35
2017-05-19  877.00     895.10     813.50     850.60     852.40
2017-06-01  802.00     817.95     794.00     803.40     803.70
2017-06-02  807.00     838.85     801.40     837.00     834.35

我必须确定每天是否有盈亏。然后编写一个函数,其中基于自定义参数N,该函数将在N天内返回损益百分比。 这是我到目前为止尝试过的 {注意:N天之间的利润/亏损百分比是2天收盘价之间的百分比变化}

def profit_loss_pct(N):
    df_n_days = df.tail(N)
    profit_loss_prcnt = ((df_n_days["Open Price"] - df_n_days["Close Price"])/df_n_days["Close Price"])
    if profit_loss_prcnt < 0:
        print("Loss: " + profit_loss_prcnt*100,"%")
    else:
        return print("Profit: " + profit_loss_prcnt*100,"%")

profit_loss_pct(20)

编辑1: 我尝试了Francesco Zambolin的代码

def profit_loss_pct(N):
    df_n_days = df.tail(N)
    profit_loss_prcnt = ((df_n_days["Open Price"] - df_n_days["Close Price"])/df_n_days["Close Price"])
    for n in range(N):
        if profit_loss_prcnt[n] < 0:
            print("Loss:", profit_loss_prcnt[n]*100,"%")
        else:
            print("Profit:", profit_loss_prcnt[n]*100,"%")

编辑2:

尝试以下方法:

def profit_loss_pct(N):
    total_days = len(df['Profit/Loss'])
    calc_pnl = df['Profit/Loss'][total_days-N:].sum()
    if calc_pnl.iloc[N] < 0:
          print("Loss pct is: {:5.2f}%". format(calc_pnl.iloc[N]*100));
    else:
         print("Profit pct is : {:5.2f}%". format(calc_pnl.iloc[N]*100));
    return 

我收到错误

AttributeError                            Traceback (most recent call last)
<ipython-input-21-ca9c4298a3c4> in <module>()
      1 #Average price and PNL pct for 1 week
      2 average_price(7)
----> 3 profit_loss_pct(7)
      4 print("")
      5 #Average price and PNL pct for 2 week

<ipython-input-20-6053bcd8e488> in profit_loss_pct(N)
     10     total_days = len(df['Profit/Loss'])
     11     calc_pnl = df['Profit/Loss'][total_days-N:].sum()
---> 12     if calc_pnl.iloc[N] < 0:
     13           print("Loss pct is: {:5.2f}%". format(calc_pnl.iloc[N]*100));
     14     else:

AttributeError: 'numpy.float64' object has no attribute 'iloc'

如果它是一个系列,应该找到正确的值吗?但这为什么不起作用?

5 个答案:

答案 0 :(得分:0)

您的profit_loss_prcnt是一系列N值。例如,您可以将if语句放在N个值的for循环中。当您遇到负pct时,您的if就可以了。

您有印刷错误:您可以将Profit_loss_prcnt作为字符串str(profit_loss_prcnt * 100)传递,这样+号就可以起作用,或者您可以这样输入逗号: 打印(“亏损:”,profit_loss_prcnt * 100,“%”)

您的功能将是:

def profit_loss_pct(N):
    df_n_days = df.tail(N)
    profit_loss_prcnt = ((df_n_days["Open Price"] - df_n_days["Close Price"])/df_n_days["Close Price"])
    for n in range(N):
        if profit_loss_prcnt[n] < 0:
            print("Loss:", profit_loss_prcnt[n]*100,"%")
        else:
            print("Profit:", profit_loss_prcnt[n]*100,"%")

答案 1 :(得分:0)

def profit_loss_pct(N):
    total_days = len(df['Profit/Loss'])
    calc_pnl = df['Profit/Loss'][total_days-N:].sum()
    if df["Profit/Loss"][N] < 0:
          print("Loss pct is: {:5.2f}%". format(df["Profit/Loss"][N]*100));
    else:
         print("Profit pct is : {:5.2f}%". format(df["Profit/Loss"][N]*100));
    return 

>>>Profit pct over  365 days is :  3.21%

我知道我要去哪里错了,这行得通。谢谢:)

答案 2 :(得分:0)

获取数据框

import pandas_datareader as web
df = web.data.get_data_yahoo('ibm', start='2019-01-01', end='2019-06-01')
df.head(3)

Date        High        Low          Open       Close       Volume                  
2019-01-02  115.980003  111.690002  112.010002  115.209999  4239900.0   
2019-01-03  114.879997  112.690002  114.529999  112.910004  4346700.0   
2019-01-04  117.489998  114.440002  114.910004  117.320000  4477800.0   
  

我必须确定每天是否有损益

df['Profit/Loss'] = (df['Close'] - df['Close'].shift(1)) / df['Close']

df.head(3)

Date        High        Low         Open        Close       Volume   Profit/Loss                        
2019-01-02  115.980003  111.690002  112.010002  115.209999  4239900.0   NaN
2019-01-03  114.879997  112.690002  114.529999  112.910004  4346700.0   -0.020370
2019-01-04  117.489998  114.440002  114.910004  117.320000  4477800.0   0.037589
  

稍后编写一个函数,其中基于自定义参数N,   函数将返回N天的损益百分比

def getPL(N):
  total_days = len(df['Profit/Loss'])
  return df['Profit/Loss'][total_days-N:].sum()

getPL(30)

-0.09336249871304825

答案 3 :(得分:0)

此功能将完成您​​的工作。

def profit_loss(data,n):
    change = data['Close Price'].iloc[-n] - data['Close Price'].iloc[-1]
    per  = (change*100)/data['Close Price'].iloc[-n]
    return per

答案 4 :(得分:0)

这将起作用

def plperct(N):
    tb3=tb.tail(N)
    t=((tb3['Close Price']-tb3['Prev Close'])/tb3['Prev Close'])*100
    return t