Help writing aggregation query using PyMongo instead of pandas

If calculated in excel
excel formula:

code date num price money hold total(middle)
2 2015-11-15 10 3.8 -38 =C2 =E2
2 2015-11-17 -10 3.7 37 =F2+C3 =G2+E3
2 2015-11-20 20 3.5 -70 =F3+C4 =G3+E4
2 2016-4-1 10 3.2 -32 =F4+C5 =G4+E5
2 2016-4-2 -30 3.6 108 =F5+C6 =G5+E6
2 2016-4-3 50 3.4 -170 =F6+C7 =G6+E7
2 2016-11-1 -40 3.5 140 =F7+C8 =G7+E8
3 2015-2-1 25 7 -175 =C9 =E9
3 2015-5-1 35 7.5 -262.5 =F9+C10 =G9+E10
3 2016-3-1 -15 8 120 =F10+C11 =G10+E11
5 2015-11-20 50 5 -250 =c12 =E12
5 2016-6-1 -50 5.5 275 =F12+C13 =G12+E13
6 2015-2-1 35 11.5 -402.5 =c14 =E14

Result of formula calculation in excel:

code date num price money hold total(middle)
2 2015-11-15 10 3.8 -38 10 -38
2 2015-11-17 -10 3.7 37 0 -1
2 2015-11-20 20 3.5 -70 20 -71
2 2016-4-1 10 3.2 -32 30 -103
2 2016-4-2 -30 3.6 108 0 5
2 2016-4-3 50 3.4 -170 50 -165
2 2016-11-1 -40 3.5 140 10 -25
3 2015-2-1 25 7 -175 25 -175
3 2015-5-1 35 7.5 -262.5 60 -437.5
3 2016-3-1 -15 8 120 45 -317.5
5 2015-11-20 50 5 -250 50 -250
5 2016-6-1 -50 5.5 275 0 25
6 2015-2-1 35 11.5 -402.5 35 -402.5

then
a=The last total (middle) of the code corresponding to the hold equal to 0
If the a of code does not exist
a=0

if the hold of code is not equal to 0
total=total(middle)-a
else
total=total(middle)

then take the last line of data for each code,that is the result i want