I want to calculate portfolio weights based on their Fund value relative to the total fund value in each portfolio.
I have a 50,000 x 4 data frame. The fund value column should determine the weight of each fund within each draw.
draw Fund.ID Fund.Value..mn.USD. Net.Multiple..X.
(int) (int) (dbl) (dbl)
1 1 10678 1963.8 1.29
2 1 8812 9400.0 1.61
3 1 7236 7525.0 1.58
4 1 12702 5979.7 1.40
5 1 13715 3510.0 1.70
6 2 2060 334.8 1.42
7 2 2059 250.0 1.47
8 2 1151 202.0 2.12
9 2 1812 500.0 0.11
10 2 6822 151.2 2.09
For draw 1, the fund in row 2 should have the highest weight (33.12%), the fund in row 3 should have the second highest weight (26.52%) and the fund in row 1 the lowest weight (6.92%). The sum of weights from row 1-5 should equal 100%.
How can I create such a weight vector for 1,000 draws? I then want to multiply each weight with the respective Net Multiple (weight(fund1)*Net Multiple(fund1))
.
We can use dplyr
to get the fund weight, also, let's call your data.frame
df
, and make the column names single words so they're a bit easier to deal with.
library(dplyr)
head(df)
Draw Fund Value Multiple
1 1 10678 1963.8 1.29
2 1 8812 9400.0 1.61
3 1 7236 7525.0 1.58
4 1 12702 5979.7 1.40
5 1 13715 3510.0 1.70
6 2 2060 334.8 1.42
df <- df %>% group_by(Draw) %>% mutate(FundWeight = Value / sum(Value))
head(df)
Source: local data frame [6 x 5]
Groups: Draw [2]
Draw Fund Value Multiple FundWeight
(int) (int) (dbl) (dbl) (dbl)
1 1 10678 1963.8 1.29 0.06920027
2 1 8812 9400.0 1.61 0.33123668
3 1 7236 7525.0 1.58 0.26516553
4 1 12702 5979.7 1.40 0.21071234
5 1 13715 3510.0 1.70 0.12368518
6 2 2060 334.8 1.42 0.23282337
#multiply columns
df$WeightMultiple <- df$FundWeight * df$Multiple
df
Source: local data frame [10 x 6]
Groups: Draw [2]
Draw Fund Value Multiple FundWeight WeightMultiple
(int) (int) (dbl) (dbl) (dbl) (dbl)
1 1 10678 1963.8 1.29 0.06920027 0.08926835
2 1 8812 9400.0 1.61 0.33123668 0.53329105
3 1 7236 7525.0 1.58 0.26516553 0.41896154
4 1 12702 5979.7 1.40 0.21071234 0.29499727
5 1 13715 3510.0 1.70 0.12368518 0.21026481
6 2 2060 334.8 1.42 0.23282337 0.33060918
7 2 2059 250.0 1.47 0.17385257 0.25556328
8 2 1151 202.0 2.12 0.14047288 0.29780250
9 2 1812 500.0 0.11 0.34770515 0.03824757
10 2 6822 151.2 2.09 0.10514604 0.21975522
You can use data.table
,
library(data.table)
setDT(df)[, weight := prop.table(Fund.Value), by = draw]
df
# draw Fund.ID Fund.Value Net.Multiple..X. weight
# 1: 1 10678 1963.8 1.29 0.06920027
# 2: 1 8812 9400.0 1.61 0.33123668
# 3: 1 7236 7525.0 1.58 0.26516553
# 4: 1 12702 5979.7 1.40 0.21071234
# 5: 1 13715 3510.0 1.70 0.12368518
# 6: 2 2060 334.8 1.42 0.23282337
# 7: 2 2059 250.0 1.47 0.17385257
# 8: 2 1151 202.0 2.12 0.14047288
# 9: 2 1812 500.0 0.11 0.34770515
#10: 2 6822 151.2 2.09 0.10514604
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.