简体   繁体   中英

How to select single rows from a dataframe, calculate cumulative return and plot it in single figure

I have a dataframe (portbase) that contains multiple signals (signalname) and their returns.

数据框截图

I want to subset every single, calculate the cumulative return and then plot them in a single figure. I have done it step by step with on single as an example:

ChInvIA = portbase[portbase['signalname'] == 'ChInvIA']
cum_perf_ChInvIA = ChInvIA['return'].cumsum() + 100
cum_perf_ChInvIA.plot()
plt.show()

With multiple signals this would take me way too long and therefore i've tries to loop over my dataframe.

for i in signals:
    i = portbase[portbase['signalname'] == 'i']
    cum_perf_i = i['return'].cumsum() + 100
    cum_perf_i.plot()
    plt.show()

It doesn't work and i've tried to find a solution.

You are calling both the looping variable and a variable in the loop by the name i , and comparing signalname to a string containing i ( 'i' ) instead of the variable itself. You should do something like this instead:

for i in signals:
    signal_i = portbase[portbase['signalname'] == i]
    cum_perf_i = signal_i['return'].cumsum() + 100
    cum_perf_i.plot()
    plt.show()

To have all the plots in the same figure, you should use matplotlib's subplots function:

fig, ax = plt.subplots(len(signals))
for ind, i in enumerate(signals):
    signal_i = portbase[portbase['signalname'] == i]
    cum_perf_i = signal_i['return'].cumsum() + 100
    cum_perf_i.plot(ax=ax[ind])

plt.show()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM