我正在使用MySQL来计算我的投资组合的回报。所以,我有一个投资组合表,持有期为6个月说:
table Portfolio
DATE_ TCIKER WEIGHT
2007-01-31 AAPL 0.2
2007-01-31 IBM 0.2
2007-01-31 FB 0.3
2007-01-31 MMM 0.3
2007-07-31 AAPL 0.1
2007-07-31 FB 0.8
2007-07-31 AMD 0.1
... ... ...
我有这些公司(整个股票市场)的月度统计表,包括月度回报:
table stats
DATE_ TICKER RETURN OTHER_STATS
2007-01-31 AAPL 0.01 ...
2007-01-31 IBM 0.03 ...
2007-01-31 FB 0.13 ...
2007-01-31 MMM -0.07 ...
2007-02-31 AAPL 0.03 ...
2007-02-31 IBM 0.04 ...
2007-02-31 FB 0.06 ...
2007-02-31 MMM -0.10 ...
我每6个月重新平衡投资组合。因此,在这6个月内,每只股票的权重不会改变。我想得到的是这样的:
ResultTable
DATE_ TICKER RETURN OTHER_STATS WEIGHT
2007-01-31 AAPL 0.01 ... 0.2
2007-01-31 IBM 0.03 ... 0.2
2007-01-31 FB 0.13 ... 0.3
2007-01-31 MMM -0.07 ... 0.3
2007-02-31 AAPL 0.03 ... 0.2
2007-02-31 IBM 0.04 ... 0.2
2007-02-31 FB 0.06 ... 0.3
2007-02-31 MMM -0.10 ... 0.3
2007-03-31 AAPL 0.03 ... 0.2
2007-03-31 IBM 0.14 ... 0.2
2007-03-31 FB 0.16 ... 0.3
2007-03-31 MMM -0.06 ... 0.3
... ... ... ... ...
2007-07-31 AAPL ... ... 0.1
2007-07-31 FB ... ... 0.8
2007-07-31 AMD ... ... 0.1
2007-08-31 AAPL ... ... 0.1
2007-08-31 FB ... ... 0.8
2007-08-31 AMD ... ... 0.1
我累了
select s.*, p.WEIGHT from portfolio p
left join stats s
on p.DATE_ = s.DATE_
and p.TICKER= s.TICKER;
它只会告诉我投资组合重新平衡日期的日期。 有没有有效的方法来计算月度回报?
答案 0 :(得分:0)
如果我理解你的公式,这可能会有效:
SELECT
p.`DATE_`,
p.`TICKER`,
SUM(s.`RETURN` * p.`WEIGHT`) as `return`,
p.WEIGHT
FROM `portfolio` p
LEFT JOIN `stats` s
ON p.`TICKER` = s.`TICKER`
WHERE s.`DATE_` BETWEEN p.`DATE_` AND DATE_ADD(DATE_ADD(p.`DATE_`, INTERVAL 6 MONTHS),INTERVAL -1 DAY)
GROUP BY p.`DATE_`, p.`TICKER`
ORDER BY p.`DATE_`, p.`TICKER`;