Reputation: 2501
I am attempting to do a monte carlo-esque projection using pandas on some stock prices. I used numpy to create some random correlated values for percentage price change, however I am struggling on how to use those values to create a 'running tally' of the actual asset price. So I have a DataFrame that looks like this:
abc xyz def
0 0.093889 0.113750 0.082923
1 -0.130293 -0.148742 -0.061890
2 0.062175 -0.005463 0.022963
3 -0.029041 -0.015918 0.006735
4 -0.048950 -0.010945 -0.034421
5 0.082868 0.080570 0.074637
6 0.048782 -0.030702 -0.003748
7 -0.027402 -0.065221 -0.054764
8 0.095154 0.063978 0.039480
9 0.059001 0.114566 0.056582
How can I create something like this, where abc_px = previous price * (1 + abc). I know I could iterate over, but I would rather not for performance reasons.
Something like, assuming the initial price on all of these was 100:
abc xyz def abc_px xyz_px def_px
0 0.093889 0.11375 0.082923 109.39 111.38 108.29
1 -0.130293 -0.148742 -0.06189 95.14 94.81 101.59
2 0.062175 -0.005463 0.022963 101.05 94.29 103.92
3 -0.029041 -0.015918 0.006735 98.12 92.79 104.62
4 -0.04895 -0.010945 -0.034421 93.31 91.77 101.02
5 0.082868 0.08057 0.074637 101.05 99.17 108.56
6 0.048782 -0.030702 -0.003748 105.98 96.12 108.15
7 -0.027402 -0.065221 -0.054764 103.07 89.85 102.23
8 0.095154 0.063978 0.03948 112.88 95.60 106.27
9 0.059001 0.114566 0.056582 119.54 106.56 112.28
Upvotes: 1
Views: 59
Reputation: 210832
Is that what you want?
In [131]: new = df.add_suffix('_px') + 1
In [132]: new
Out[132]:
abc_px xyz_px def_px
0 1.093889 1.113750 1.082923
1 0.869707 0.851258 0.938110
2 1.062175 0.994537 1.022963
3 0.970959 0.984082 1.006735
4 0.951050 0.989055 0.965579
5 1.082868 1.080570 1.074637
6 1.048782 0.969298 0.996252
7 0.972598 0.934779 0.945236
8 1.095154 1.063978 1.039480
9 1.059001 1.114566 1.056582
In [133]: df.join(new.cumprod() * 100)
Out[133]:
abc xyz def abc_px xyz_px def_px
0 0.093889 0.113750 0.082923 109.388900 111.375000 108.292300
1 -0.130293 -0.148742 -0.061890 95.136292 94.808860 101.590090
2 0.062175 -0.005463 0.022963 101.051391 94.290919 103.922903
3 -0.029041 -0.015918 0.006735 98.116758 92.789996 104.622824
4 -0.048950 -0.010945 -0.034421 93.313942 91.774410 101.021601
5 0.082868 0.080570 0.074637 101.046682 99.168674 108.561551
6 0.048782 -0.030702 -0.003748 105.975941 96.123997 108.154662
7 -0.027402 -0.065221 -0.054764 103.071989 89.854694 102.231680
8 0.095154 0.063978 0.039480 112.879701 95.603418 106.267787
9 0.059001 0.114566 0.056582 119.539716 106.556319 112.280631
Upvotes: 1