简体   繁体   中英

How to calculate with previous row value of a column if it can be declared only after it should be used in pandas dataframe?

The following is the dataframe I have:

import datetime
import pandas as pd
import numpy as np

todays_date = datetime.datetime.now().date()
index = pd.date_range(todays_date-datetime.timedelta(10), periods=10, freq='D')
data = pd.DataFrame(index=index)

data['Open'] = np.random.randint(20,40, size=len(data))
data['High'] = np.random.randint(40,50, size=len(data))
data['Low'] = np.random.randint(10,20, size=len(data))
data['Close'] = np.random.randint(10,20, size=len(data))

The calculations I would like to perform are the following:

capital = 30000

data['Shares'] = (capital * 0.05 / data['Close'].shift(1) - data['Low'].shift(1)).round(0)
data['Open_price'] = data['Open'] + 0.5 * (data['High'] - data['Open'])
data['Floating_P/L'] = data['Shares'] * data['Close']
data['Close_price'] = data['Close'] - 0.5 * (data['Close'] - data['Low'])
data['Closed_P/L'] = data['Shares'].shift(1) * data['Close_price']
data['Closed_Balance'] = capital + data['Closed_P/L'].cumsum()
data['Equity'] = data['Closed_Balance'] + data['Floating_P/L']

capital = data['Equity'].shift(1)

As you can see Equity is calculated from today's Shares number which is calculated from yesterday's Equity . I want to set capital to be the initial value of Equity at the first index and calculate Shares based on this number at the first index. From the second index, Shares should be calculated from the Equity shifted one row up. How can I do this?

In the code you have have given above, I see that initial value of Shares and first two values of Equity are Nans since first value of Shares is calculated using Close and Low columns shifted up. Assuming you can set up some values here,

try doing this?

  1. Create empty columns in data for Equity and Shares

     data['Equity']='' data['Shares']='' 
  2. set capital to be the initial value of Equity . Since you mentioned initial value of capital = 30000

     capital= 30000 data['Equity'][0]= 30000 
  3. Calculate initial value of Shares . Here try setting up values in place of Nans for Close and Low

     data['Shares'][0]= (capital * 0.05 / data['Close'].shift(1)[0] - data['Low'].shift(1))[0].round(0) 
  4. then use a for loop which iterates from second index to the length of data.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM