简体   繁体   中英

How do i multiply a list of values by a dataframe of values then use those results to multiply by the next row of values in the dataframe?

I'm trying to code a daily stock price return simulator. I need to take a starting allocation of funds (across say, three stocks) and multiply by a dataframe of returns for those stocks. So for example, let's say I have an allocation of [1000, 2000, 7000] dollars, I multiply those values by the first row of returns, for example [-.01, .05, .009] . How do I then take that result and multiply that by the next row of returns in the data frame then append each value to a dictionary?

Example code below:

import pandas as pd
import numpy as np

df_dict = {'ba': [.001588,.001540, .001001, .001206, .001338], 'gs':[0.001064,0.001232, 0.001748, 0.001642, 0.001616],
          'ge': [0.001030, 0.000876, 0.001335, 0.000756, .000880]}

df = pd.DataFrame(df_dict)

allocation = [1000, 2000, 7000]

So I would look to multiply 1000 (first value in the allocation) by .001588 (first value of the first column of df) and 2000 (send value in allocation) by .001064 (first value in 2nd column of df) and the same for the third allocation/first value of the 3rd column and append the results to a dictionary with today's date as a key.

How do I take those results and multiply them by the next row's values, append them to the dictionary with today() + 1 and then do the same until I have gone through the whole data set?

You can let pandas do the full operations by building a dataframe from the allocation list indexed by the expected dates:

ix = pd.date_range(datetime.date.today(), freq='D', periods = len(df))
df1 = pd.DataFrame(data = [allocation], index=ix, columns = df.columns)

df1 is:

              ba    gs    ge
2020-03-23  1000  2000  7000
2020-03-24  1000  2000  7000
2020-03-25  1000  2000  7000
2020-03-26  1000  2000  7000
2020-03-27  1000  2000  7000

You can use same index for the initial df , use a cumprod to multiply the rows and finally have the product of both dataframes:

df.set_index(ix).cumprod() * df1

to obtain:

                      ba            gs            ge
2020-03-23  1.588000e+00  2.128000e+00  7.210000e+00
2020-03-24  2.445520e-03  2.621696e-03  6.315960e-03
2020-03-25  2.447966e-06  4.582725e-06  8.431807e-06
2020-03-26  2.952246e-09  7.524834e-09  6.374446e-09
2020-03-27  3.950106e-12  1.216013e-11  5.609512e-12

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