【发布时间】:2020-10-20 09:02:49
【问题描述】:
我正在尝试从原点(或 Y 轴上的任何点)绘制一条与黄土曲线相切的直线(一条仅与曲线接触一次的线)。
The black line is the smoothed curve of the points, and I wish to draw that yellow line.
我将发布我的代码以获得下面的平滑曲线。
'''
library(quantmod)
library(plotly)
library(PerformanceAnalytics)
library(timetk)
library(tidyverse)
ticker = c('AMZN', 'AAPL', 'NFLX', 'XOM', 'T')
price_data = getSymbols(ticker, from = '2014-01-01', to = '2018-05-31')
prices = do.call(cbind,
lapply(ticker, function(x) Ad(get(x))))
rets = Return.calculate(prices, method = 'log') %>%
na.omit()
num_port = 1000
all_wts = matrix(nrow = num_port, ncol = length(ticker))
port_returns = vector('numeric', length = num_port)
port_risk = vector('numeric', length = num_port)
port_sr = vector('numeric', length = num_port)
for (i in seq_along(port_returns)) {
wts = runif(n = length(ticker))
wts = wts/sum(wts)
all_wts[i,] = wts
port = Return.portfolio(R = rets, weights = wts, verbose = TRUE)
a = StdDev.annualized(port$returns)[1]
b = SharpeRatio.annualized(port$returns, Rf = 0)[1]
c = a*b
port_returns[i] = c
port_risk[i] = a
port_sr[i] = b
}
all_wts = tk_tbl(all_wts)
colnames(all_wts) = colnames(rets)
pf_val = tibble(ret = port_returns, risk = port_risk, sr = port_sr)
pf_val = tk_tbl(cbind(all_wts, pf_val))
min_var = pf_val[which.min(pf_val$risk),]
max_sr = pf_val[which.max(pf_val$sr),]
library(tidyverse)
pf_line2 = pf_val[which((pf_val$ret %in% d$ret)),]
p3 = ggplot(aes(x = risk, y = ret, color = sr), data = pf_line2) +
geom_point() + theme_classic() +
scale_y_continuous(labels = scales::percent) +
scale_x_continuous(labels = scales::percent) +
labs(x = 'risk', y = 'return') +
geom_smooth(method = 'loess', col='black', level=0.5, alpha=0.1)
ggplotly(p3)
'''
【问题讨论】:
-
我不知道任何与此相关的 ggplot 函数 - 但我的直觉是获取黄土多项式并取导数(在某一点)得到一条切线。根据您的示例,黄土很有可能会返回一条看起来不像 2 次多项式的曲线。在这种情况下,选择一个切线点显然很重要。