---
title: "跨市场指数对比"
output:
flexdashboard::flex_dashboard:
orientation: rows
source_code: embed
social: menu
vertical_layout: fill
theme: yeti
---
```{r setup, include=FALSE}
# packages ----------------------------------------------------------------
library(tidyverse)
library(openxlsx)
library(lubridate)
library(echarts4r)
setwd("C:\\Users\\yuanhm\\Desktop\\cloudx\\北交所市场分析\\data")
# import data -------------------------------------------------------------
dta = read.xlsx("市场运行情况.xlsx", detectDates = T)
match_list = read.xlsx("分类指标.xlsx", sheet = 1)
market_index = read.xlsx("市场指数.xlsx", detectDates = T)
# function -----------------------------------------------------------------
index_func = function(
data = dta, by_item, join_file = match_list, digit = 2, weight = "market_value"
){
data %>%
group_by(`证券简称`) %>%
mutate(
market_value = `收盘价` * `总股本`,
ratio = `收盘价_前复权`/lag(`收盘价_前复权`, 1)-1
) %>%
replace_na(list(ratio = 0)) %>%
left_join(join_file, by = c("证券简称")) %>%
ungroup() %>%
group_by(.data[[by_item]], `交易日`) %>%
mutate(
weights = .data[[weight]] / sum(.data[[weight]], na.rm = T),
ratio_w = ratio * weights
) %>%
summarise(
ratio_w_sum = round(sum(ratio_w, na.rm = T), digits = 4)+1
) %>%
arrange(.data[[by_item]], `交易日`) %>%
mutate(
ratio_w_cum = cumprod(ratio_w_sum),
index = round(ratio_w_cum * 1000, digits = digit)
) %>%
ungroup()
}
# index -------------------------------------------------------------------
market_index = market_index %>%
mutate(
`科创50` = `科创板50`/.$科创板50[[1]]*1000,
`上证指数` = `上证指数`/.$上证指数[[1]]*1000,
`沪深300` = `沪深300`/.$沪深300[[1]]*1000
)
index_all = dta %>%
mutate(`ipo` = "x") %>%
index_func(by_item = "ipo") %>%
left_join(market_index, by = c("交易日" = "日期")) %>%
select(`交易日`, index, `科创50`, `上证指数`, `沪深300`)
```
Row
-----------------------------------------------------------------------
### Index
```{r}
index_all %>%
pivot_longer(
-c("交易日"), names_to = "index_name", values_to = "index_value"
) %>%
group_by(index_name) %>%
e_charts(`交易日`) %>%
e_line(index_value, symbol = "none") %>%
e_datazoom() %>%
e_tooltip(trigger = "axis") %>%
e_toolbox_feature(feature = c("saveAsImage", "dataView")) %>%
e_title(
"跨市场指数对比", "市值加权"
) %>%
e_legend(show = legend, type = "scroll") %>%
e_show_loading() %>%
e_theme("inspired")
```