Notebook error

Course Name: Options Trading Strategies In Python: Advanced, Section No: 3, Unit No: 6, Unit type: Notebook
when running:
def strategy_pnl(opt, df):
opt = pd.merge(opt, df[[‘positions’]], left_on=‘Date’,
right_index=True, how=‘left’)
opt[‘strategy_pnl’] = opt.positions * opt.daily_straddle_pnl
return opt

BankNifty_Opt = strategy_pnl(BankNifty_Opt, df)
BankNifty_Opt.head()

it always gets:


AttributeError Traceback (most recent call last)
/tmp/ipykernel_25/1893443800.py in ?()
4 opt[‘strategy_pnl’] = opt.positions * opt.daily_straddle_pnl
5 return opt
6
7
----> 8 BankNifty_Opt = strategy_pnl(BankNifty_Opt, df)
9 BankNifty_Opt.head()

/tmp/ipykernel_25/1893443800.py in ?(opt, df)
1 def strategy_pnl(opt, df):
2 opt = pd.merge(opt, df[[‘positions’]], left_on=‘Date’,
3 right_index=True, how=‘left’)
----> 4 opt[‘strategy_pnl’] = opt.positions * opt.daily_straddle_pnl
5 return opt

~/.conda/envs/quantra_py/lib/python3.11/site-packages/pandas/core/generic.py in ?(self, name)
6295 and name not in self._accessors
6296 and self._info_axis._can_hold_identifiers_and_holds_name(name)
6297 ):
6298 return self[name]
→ 6299 return object.getattribute(self, name)

AttributeError: ‘DataFrame’ object has no attribute ‘positions’

Hi Sebastian,

the error occurs because after the merge, your opt DataFrame does not contain a positions column. This happens when the positions column is missing in df, or when the merge does not match the dates due to mismatched indices or wrong date formats. Convert both dates to datetime, ensure df actually has a positions column, and use plain quotes- then the function will work.