I have the following code:
aapl = [10, 154.12]
goog = [ 2, 812.56]
tsla = [12, 342.12]
fb = [18, 209.0]
portfolio = [ aapl, goog, tsla, fb ]
market = [ 198.84, 1217.93, 267.66, 179.06 ]
print(portfolio[3][0])
# pnl=((market[0]-portfolio[0][1])*portfolio[0][0])+((market[1]-portfolio[1][1])*portfolio[1][0])+((market[2]-portfolio[2][1])*portfolio[2][0])+((market[3]-portfolio[3][1])*portfolio[3][0])
# print(pnl)
total_pnl = 0
for n in range(0, 3):
pnl=(market[n]-portfolio[n][1])*portfolio[n][0]
total_pnl += pnl
print(total_pnl)
The quoted out code returns the correct result: -174,5. The for-loop is the same equation, but looped over the different list items, yet it returns 364,42. I'm assuming this is because of the adding up of the results.
Please help me find my error, thank you!
range(0, 3)
is the mistake, it returns only 0, 1, 2.
But market has 4 items.
So use range(0, 4)
or range(0, len(market))