df = pd.DataFrame({'price': [9.8, 9.78, 9.81, 9.76, 9.78, 9.65,], 'quantity': [3,4,5,6,1,4], 'operation': ['in','in','out','in','out','in']})
price | quantity | operation | |
---|---|---|---|
0 | 9.80 | 3 | in |
1 | 9.78 | 4 | in |
2 | 9.81 | 5 | out |
3 | 9.76 | 6 | in |
4 | 9.78 | 1 | out |
5 | 9.65 | 4 | in |
def getOstatokLIFO(df):
try:
df2 = df.copy()
df2.loc[df2.operation == 'out', 'quantity'] = -df2.quantity
df2['needRM'] = False
for i in df2.index:
row = df2.iloc[i].copy()
if row.quantity < 0:
k = i
row.needRM = True
df2.iloc[i] = row
quantitySell = row.quantity * -1
while quantitySell > 0:
k -= 1
if k < 0:
break
rowBack = df2.iloc[k].copy()
if rowBack.quantity < 0:
continue
quantitySell = rowBack.quantity - quantitySell
if quantitySell > 0:
rowBack.quantity = quantitySell
df2.iloc[k] = rowBack
break
elif quantitySell < 0:
rowBack.quantity = 0
rowBack.needRM = True
df2.iloc[k] = rowBack
quantitySell = quantitySell * -1
else:
rowBack.quantity = 0
rowBack.needRM = True
df2.iloc[k] = rowBack
break
return df2[df2.needRM == False][['price', 'quantity', 'operation']].copy()
except Exception as e:
raise e
price | quantity | operation | |
---|---|---|---|
0 | 9.80 | 2 | in |
3 | 9.76 | 5 | in |
5 | 9.65 | 4 | in |
def getOstatokLIFO(df):
stack = [];
for index, row in df.iterrows():
if row.operation == "in":
stack.append([row.price, row.quantity])
continue
left = row.quantity
while left > 0:
if left >= stack[-1][1]:
left -= stack[-1][1]
stack.pop()
else:
stack[-1][1] -= left
left = 0
return stack