edb_data_residual_analysis.go 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649
  1. package models
  2. import (
  3. "encoding/json"
  4. "eta/eta_index_lib/utils"
  5. "fmt"
  6. "github.com/beego/beego/v2/client/orm"
  7. "math"
  8. "sort"
  9. "strconv"
  10. "time"
  11. )
  12. type edbDataResidualAnalysis struct {
  13. EdbDataId int `orm:"column(edb_data_id);pk;auto" description:"自增id"`
  14. EdbInfoId int `orm:"column(edb_info_id)" description:"指标id"`
  15. EdbCode string `orm:"column(edb_code)" description:"指标编码"`
  16. DataTime string `orm:"column(data_time)" description:"数据日期"`
  17. Value float64 `orm:"column(value)" description:"数据值"`
  18. CreateTime time.Time `orm:"column(create_time)" description:"创建时间"`
  19. ModifyTime time.Time `orm:"column(modify_time)" description:"修改时间"`
  20. DataTimeStamp int64 `orm:"column(data_timestamp)"`
  21. }
  22. func init() {
  23. orm.RegisterModel(new(edbDataResidualAnalysis))
  24. }
  25. // AddResidualAnalysisData 新增指标数据
  26. func AddResidualAnalysisData(dataList []edbDataResidualAnalysis) (num int64, err error) {
  27. o := orm.NewOrm()
  28. num, err = o.InsertMulti(len(dataList), dataList)
  29. if err != nil {
  30. return 0, err
  31. }
  32. return num, nil
  33. }
  34. // RefreshAllCalculateResidualAnalysis 刷新残差分析
  35. func RefreshAllCalculateResidualAnalysis(edbInfoId, source, subSource, formulaInt, moveType int, fromEdbInfo *EdbInfo, edbCode, startDate, endDate, moveFrequency string) (err error) {
  36. to := orm.NewOrm()
  37. /*to, err := o.Begin()
  38. if err != nil {
  39. return
  40. }
  41. defer func() {
  42. if err != nil {
  43. fmt.Println("RefreshAllCalculateResidualAnalysis,Err:" + err.Error())
  44. _ = to.Rollback()
  45. } else {
  46. _ = to.Commit()
  47. }
  48. }()*/
  49. configMapping, err := GetConfigMappingListByConditionNotBase(edbInfoId)
  50. if err != nil {
  51. return err
  52. }
  53. var edbInfoIdList []int64
  54. for _, v := range configMapping {
  55. edbInfoIdList = append(edbInfoIdList, v.EdbInfoId)
  56. }
  57. //清空原有数据
  58. sql := ` DELETE FROM edb_data_residual_analysis WHERE edb_info_id in (` + utils.GetOrmInReplace(len(edbInfoIdList)) + `) `
  59. var params []interface{}
  60. for _, i := range edbInfoIdList {
  61. params = append(params, i)
  62. }
  63. _, err = to.Raw(sql, params...).Exec()
  64. if err != nil {
  65. return
  66. }
  67. //计算数据
  68. err = refreshAllCalculateResidualAnalysis(edbInfoId, source, subSource, formulaInt, moveType, fromEdbInfo, edbCode, startDate, endDate, moveFrequency, configMapping)
  69. return
  70. }
  71. // refreshAllCalculateResidualAnalysis 刷新所有残差分析
  72. func refreshAllCalculateResidualAnalysis(edbInfoId, source, subSource, formulaInt, moveType int, fromEdbInfo *EdbInfo, edbCode, startDate, endDate, moveFrequency string, configMapping []CalculateResidualAnalysisConfigMapping) (err error) {
  73. fmt.Println("refreshAllCalculateResidualAnalysis startDate:", startDate)
  74. calculateMappingList, err := GetCalculateMappingListByEdbInfoId(edbInfoId)
  75. if err != nil {
  76. return err
  77. }
  78. edbInfoIdA := calculateMappingList[0].FromEdbInfoId
  79. edbInfoIdB := calculateMappingList[1].FromEdbInfoId
  80. mappingList, err := GetEdbInfoListByIds([]int{edbInfoIdA, edbInfoIdB})
  81. if err != nil {
  82. return err
  83. }
  84. var edbInfoMappingA, edbInfoMappingB *EdbInfoList
  85. for _, v := range mappingList {
  86. if v.Unit == "无" {
  87. v.Unit = ""
  88. }
  89. if v.EdbInfoId == edbInfoIdA {
  90. edbInfoMappingA = v
  91. }
  92. if v.EdbInfoId == edbInfoIdB {
  93. edbInfoMappingB = v
  94. }
  95. }
  96. if edbInfoMappingA == nil {
  97. return fmt.Errorf("指标A不存在")
  98. }
  99. if edbInfoMappingB == nil {
  100. return fmt.Errorf("指标B不存在")
  101. }
  102. // 从配置中取出时间范围
  103. analysisConfig, err := GetResidualAnalysisConfigById(edbInfoId)
  104. if err != nil {
  105. return err
  106. }
  107. configString := analysisConfig.Config
  108. var config ResidualAnalysisConfig
  109. err = json.Unmarshal([]byte(configString), &config)
  110. // 时间处理
  111. switch config.DateType {
  112. case 0:
  113. startDate = config.StartDate
  114. endDate = config.EndDate
  115. case 1:
  116. startDate = config.StartDate
  117. endDate = ""
  118. default:
  119. startDate = utils.GetPreYearTime(config.DateType)
  120. endDate = ""
  121. }
  122. // 原始图表信息
  123. originalEdbList := make([]EdbInfoList, 0)
  124. originalEdbList, fullADataList, fullBDataList, err := fillOriginalChart(config, fromEdbInfo, mappingList, startDate, endDate, edbInfoMappingA, edbInfoMappingB, originalEdbList)
  125. if err != nil {
  126. return err
  127. }
  128. indexADataMap := map[string]*EdbData{}
  129. for _, indexData := range edbInfoMappingA.DataList {
  130. indexADataMap[indexData.DataTime] = indexData
  131. }
  132. // 映射图表信息
  133. mappingEdbList, _, _, _, err := fillMappingChartInfo(config, fromEdbInfo, edbInfoMappingA, edbInfoMappingB, originalEdbList, indexADataMap, startDate, endDate, fullADataList, fullBDataList)
  134. if err != nil {
  135. return err
  136. }
  137. // 残差图表信息
  138. residualEdbList, _, err := fillResidualChartInfo(config, fromEdbInfo, edbInfoMappingA, edbInfoMappingB, mappingEdbList)
  139. edbInfo, err := GetEdbInfoById(edbInfoId)
  140. if err != nil {
  141. return err
  142. }
  143. // 映射指标 与 残差指标 同步刷新
  144. for _, mapping := range configMapping {
  145. var edbDataResidualAnalysisList []edbDataResidualAnalysis
  146. if mapping.IndexType == 1 {
  147. for _, edbData := range mappingEdbList[1].DataList {
  148. value, _ := strconv.ParseFloat(edbData.Value, 64)
  149. edbDataResidualAnalysisList = append(edbDataResidualAnalysisList, edbDataResidualAnalysis{
  150. EdbInfoId: int(mapping.EdbInfoId),
  151. EdbCode: edbInfo.EdbCode,
  152. DataTime: edbData.DataTime,
  153. Value: value,
  154. CreateTime: time.Now(),
  155. ModifyTime: time.Now(),
  156. DataTimeStamp: edbData.DataTimestamp,
  157. })
  158. }
  159. _, err = AddResidualAnalysisData(edbDataResidualAnalysisList)
  160. if err != nil {
  161. return err
  162. }
  163. } else if mapping.IndexType == 2 {
  164. for _, edbData := range residualEdbList[1].DataList {
  165. value, _ := strconv.ParseFloat(edbData.Value, 64)
  166. edbDataResidualAnalysisList = append(edbDataResidualAnalysisList, edbDataResidualAnalysis{
  167. EdbInfoId: int(mapping.EdbInfoId),
  168. EdbCode: edbData.EdbCode,
  169. DataTime: edbData.DataTime,
  170. Value: value,
  171. CreateTime: time.Now(),
  172. ModifyTime: time.Now(),
  173. DataTimeStamp: edbData.DataTimestamp,
  174. })
  175. }
  176. _, err = AddResidualAnalysisData(edbDataResidualAnalysisList)
  177. if err != nil {
  178. return err
  179. }
  180. }
  181. }
  182. return
  183. }
  184. func fillResidualChartInfo(config ResidualAnalysisConfig, req *EdbInfo, edbInfoMappingA *EdbInfoList, edbInfoMappingB *EdbInfoList, mappingEdbList []EdbInfoList) ([]EdbInfoList, float64, error) {
  185. // 计算公式 映射残差 = 因变量指标 - 映射指标
  186. var edbInfoA, edbInfoB EdbInfoList
  187. if mappingEdbList[0].EdbInfoId == edbInfoMappingA.EdbInfoId {
  188. edbInfoA = mappingEdbList[0]
  189. edbInfoB = mappingEdbList[1]
  190. } else {
  191. edbInfoA = mappingEdbList[1]
  192. edbInfoB = mappingEdbList[0]
  193. }
  194. dataAList := edbInfoA.DataList
  195. edbData := make([]*EdbDataList, len(dataAList))
  196. for i, data := range dataAList {
  197. f, _ := strconv.ParseFloat(data.Value, 64)
  198. edbData[i] = &EdbDataList{
  199. Value: f,
  200. DataTimestamp: data.DataTimestamp,
  201. DataTime: data.DataTime,
  202. EdbInfoId: data.EdbInfoId,
  203. EdbDataId: data.EdbDataId,
  204. }
  205. }
  206. dataBList := edbInfoB.DataList
  207. // 映射指标开始时间
  208. var startTime string
  209. if len(dataBList) > 0 {
  210. startTime = dataBList[0].DataTime
  211. }
  212. var indexDataBMap = make(map[string]*EdbData)
  213. for _, data := range dataBList {
  214. indexDataBMap[data.DataTime] = data
  215. }
  216. // 求R2
  217. var valueB, sumValueA, averageValueA, residualQuadraticSum, totalQuadraticSum, R2 float64
  218. for _, indexData := range edbData {
  219. // 因变量的值总和
  220. sumValueA += indexData.Value
  221. }
  222. // 因变量平均值
  223. averageValueA = sumValueA / float64(len(edbData))
  224. var indexMax, indexMin float64
  225. var edbDataResp []*EdbDataList
  226. if len(edbData) > 0 {
  227. indexMax = edbData[0].Value
  228. indexMin = edbData[0].Value
  229. for _, indexData := range edbData {
  230. if dataB, ok := indexDataBMap[indexData.DataTime]; ok {
  231. f, _ := strconv.ParseFloat(dataB.Value, 64)
  232. valueB = f
  233. } else {
  234. continue
  235. }
  236. // 总因变量平方和
  237. totalQuadraticSum += math.Pow(indexData.Value-averageValueA, 2)
  238. // 补全残差值
  239. indexData.Value = math.Round((indexData.Value-valueB)*10000) / 10000
  240. // 残差平方和
  241. residualQuadraticSum += math.Pow(indexData.Value, 2)
  242. if indexData.Value > indexMax {
  243. indexMax = indexData.Value
  244. }
  245. if indexData.Value < indexMin {
  246. indexMin = indexData.Value
  247. }
  248. // 获取映射指标之后的数据
  249. if startTime != "" && utils.CompareDate(startTime, indexData.DataTime) {
  250. edbDataResp = append(edbDataResp, indexData)
  251. }
  252. }
  253. }
  254. // 计算R2 公式:R2=1-SSE/SST R2越大,越符合线性 R2 = 1 - 残差平方和/总平方和
  255. R2 = 1 - residualQuadraticSum/totalQuadraticSum
  256. mappingEdb := make([]EdbInfoList, len(mappingEdbList))
  257. copy(mappingEdb, mappingEdbList)
  258. for i, mapping := range mappingEdb {
  259. if mapping.EdbInfoId != edbInfoMappingA.EdbInfoId {
  260. toEdbData := convertEdbDataListToEdbData(edbDataResp)
  261. mappingEdb[i].DataList = toEdbData
  262. mappingEdb[i].EdbName = edbInfoMappingA.EdbName + "映射残差/" + edbInfoMappingB.EdbName
  263. if config.IndexType == 2 {
  264. if config.LeadValue > 0 {
  265. mappingEdb[i].EdbName = edbInfoMappingA.EdbName + "映射残差/" + edbInfoMappingB.EdbName + "(领先" + strconv.Itoa(config.LeadValue) + config.LeadFrequency + ")"
  266. }
  267. }
  268. }
  269. }
  270. return mappingEdb, R2, nil
  271. }
  272. func fillMappingChartInfo(config ResidualAnalysisConfig, req *EdbInfo, edbInfoMappingA *EdbInfoList, edbInfoMappingB *EdbInfoList, originalEdbList []EdbInfoList, indexADataMap map[string]*EdbData, startDate string, endDate string, fullADataList []*EdbDataList, fullBDataList []*EdbDataList) ([]EdbInfoList, float64, float64, float64, error) {
  273. // 计算公式:Y=aX+b,Y为映射后的指标,X为自变量指标
  274. // 正序:a=(L2-L1)/(R2-R1) b=L2-R2*a
  275. // 逆序:a=(L2-L1)/(R1-R2) b=L2-R1*a
  276. // L2:左轴下限 R2:右轴上限 L1:左轴上限 R1:右轴下限
  277. var a, b, r float64
  278. // 映射残差 计算a,b
  279. if config.ResidualType == 1 {
  280. if config.IsOrder {
  281. a = (config.LeftIndexMax - config.LeftIndexMin) / (config.RightIndexMin - config.RightIndexMax)
  282. b = config.LeftIndexMax - config.RightIndexMin*a
  283. } else {
  284. a = (config.LeftIndexMax - config.LeftIndexMin) / (config.RightIndexMax - config.RightIndexMin)
  285. b = config.LeftIndexMax - config.RightIndexMax*a
  286. }
  287. }
  288. dataList := edbInfoMappingB.DataList
  289. // 指标B数据补充
  290. // 新建一个切片来保存补充的数据
  291. var replenishDataList []*EdbData
  292. for index := 0; index < len(dataList)-1; index++ {
  293. // 获取当前数据和下一个数据
  294. beforeIndexData := dataList[index]
  295. afterIndexData := dataList[index+1]
  296. // 从最早时间开始,补充时间为自然日
  297. for utils.IsMoreThanOneDay(beforeIndexData.DataTime, afterIndexData.DataTime) {
  298. // 创建补充数据
  299. nextDay := utils.GetNextDay(beforeIndexData.DataTime)
  300. toTime := utils.StringToTime(nextDay)
  301. replenishIndexData := EdbData{
  302. DataTime: nextDay, // 计算下一个自然日
  303. DataTimestamp: toTime.UnixMilli(),
  304. Value: beforeIndexData.Value, // 可以选择使用前一天的值,或者其他逻辑来计算值
  305. }
  306. // 将补充数据加入补充数据列表
  307. replenishDataList = append(replenishDataList, &replenishIndexData)
  308. // 更新 beforeIndexData 为新创建的补充数据
  309. beforeIndexData = &replenishIndexData
  310. }
  311. }
  312. // 将补充数据插入原始数据列表
  313. dataList = append(dataList, replenishDataList...)
  314. // 排序
  315. sort.Sort(ByDataTime(dataList))
  316. // 拟合残差 计算a,b
  317. var coordinateList []utils.Coordinate
  318. var replenishADataList []*EdbDataList
  319. var replenishBDataList []*EdbDataList
  320. if config.ResidualType == 2 {
  321. //
  322. // 因变量指标也转换为日度
  323. for index := 0; index < len(fullADataList)-1; index++ {
  324. // 获取当前数据和下一个数据
  325. beforeIndexData := fullADataList[index]
  326. afterIndexData := fullADataList[index+1]
  327. replenishADataList = append(replenishADataList, beforeIndexData)
  328. // 从最早时间开始,补充时间为自然日
  329. if utils.IsMoreThanOneDay(beforeIndexData.DataTime, afterIndexData.DataTime) {
  330. for {
  331. // 创建补充数据
  332. nextDay := utils.GetNextDay(beforeIndexData.DataTime)
  333. toTime := utils.StringToTime(nextDay)
  334. replenishIndexData := EdbDataList{
  335. DataTime: nextDay, // 计算下一个自然日
  336. DataTimestamp: toTime.UnixMilli(),
  337. Value: beforeIndexData.Value, // 可以选择使用前一天的值,或者其他逻辑来计算值
  338. }
  339. // 将补充数据加入补充数据列表
  340. replenishADataList = append(replenishADataList, &replenishIndexData)
  341. // 更新 beforeIndexData 为新创建的补充数据
  342. beforeIndexData = &replenishIndexData
  343. // 检查是否还需要继续补充数据
  344. if !utils.IsMoreThanOneDay(beforeIndexData.DataTime, afterIndexData.DataTime) {
  345. break
  346. }
  347. }
  348. }
  349. }
  350. replenishADataList = append(replenishADataList, fullADataList[len(fullADataList)-1])
  351. // 自变量指标也转换为日度
  352. for index := 0; index < len(fullBDataList)-1; index++ {
  353. // 获取当前数据和下一个数据
  354. beforeIndexData := fullBDataList[index]
  355. afterIndexData := fullBDataList[index+1]
  356. replenishBDataList = append(replenishBDataList, beforeIndexData)
  357. // 从最早时间开始,补充时间为自然日
  358. if utils.IsMoreThanOneDay(beforeIndexData.DataTime, afterIndexData.DataTime) {
  359. for {
  360. // 创建补充数据
  361. nextDay := utils.GetNextDay(beforeIndexData.DataTime)
  362. toTime := utils.StringToTime(nextDay)
  363. replenishIndexData := EdbDataList{
  364. DataTime: nextDay, // 计算下一个自然日
  365. DataTimestamp: toTime.UnixMilli(),
  366. Value: beforeIndexData.Value, // 可以选择使用前一天的值,或者其他逻辑来计算值
  367. }
  368. // 将补充数据加入补充数据列表
  369. replenishBDataList = append(replenishBDataList, &replenishIndexData)
  370. // 更新 beforeIndexData 为新创建的补充数据
  371. beforeIndexData = &replenishIndexData
  372. // 检查是否还需要继续补充数据
  373. if !utils.IsMoreThanOneDay(beforeIndexData.DataTime, afterIndexData.DataTime) {
  374. break
  375. }
  376. }
  377. }
  378. }
  379. replenishBDataList = append(replenishBDataList, fullBDataList[len(fullBDataList)-1])
  380. // replenishADataList --> map
  381. replenishADataMap := make(map[string]*EdbDataList)
  382. for _, indexData := range replenishADataList {
  383. if (utils.StringToTime(indexData.DataTime).After(utils.StringToTime(startDate)) || utils.StringToTime(indexData.DataTime).Equal(utils.StringToTime(startDate))) && (endDate == "" || utils.StringToTime(indexData.DataTime).Before(utils.StringToTime(endDate))) {
  384. replenishADataMap[indexData.DataTime] = indexData
  385. }
  386. }
  387. for _, indexData := range replenishBDataList {
  388. if _, ok := replenishADataMap[indexData.DataTime]; ok {
  389. coordinate := utils.Coordinate{
  390. X: indexData.Value,
  391. Y: replenishADataMap[indexData.DataTime].Value,
  392. }
  393. coordinateList = append(coordinateList, coordinate)
  394. }
  395. }
  396. a, b = utils.GetLinearResult(coordinateList)
  397. r = utils.ComputeCorrelation(coordinateList)
  398. }
  399. // 填充映射指标值 使得时间长度一致
  400. dataList = FillDataBList(dataList, edbInfoMappingA)
  401. // 根据指标A的时间key,在B的映射指标中筛选出对应的值
  402. var dataBList []*EdbDataList
  403. var indexMax, indexMin string
  404. if len(dataList) > 0 {
  405. indexMax = dataList[0].Value
  406. indexMin = dataList[0].Value
  407. for _, indexData := range dataList {
  408. if _, ok := indexADataMap[indexData.DataTime]; ok {
  409. indexDataCopy := *indexData
  410. // 计算指标B映射值
  411. f, _ := strconv.ParseFloat(indexData.Value, 64)
  412. indexDataCopy.Value = fmt.Sprintf("%f", math.Round((a*f+b)*10000)/10000)
  413. // 比较最大值
  414. if indexData.Value > indexMax {
  415. indexMax = indexData.Value
  416. }
  417. // 比较最小值
  418. if indexData.Value < indexMin {
  419. indexMin = indexData.Value
  420. }
  421. // 将副本添加到 dataBList
  422. copyValue, _ := strconv.ParseFloat(indexDataCopy.Value, 64)
  423. dataBList = append(dataBList, &EdbDataList{
  424. DataTime: indexDataCopy.DataTime,
  425. DataTimestamp: indexDataCopy.DataTimestamp,
  426. EdbDataId: indexDataCopy.EdbDataId,
  427. EdbInfoId: indexDataCopy.EdbInfoId,
  428. Value: copyValue,
  429. })
  430. }
  431. }
  432. }
  433. mappingEdbList := make([]EdbInfoList, len(originalEdbList))
  434. copy(mappingEdbList, originalEdbList)
  435. for i, mapping := range mappingEdbList {
  436. if mapping.EdbInfoId != edbInfoMappingA.EdbInfoId {
  437. mappingEdbList[i].EdbInfoId = 0
  438. mappingEdbList[i].EdbCode = ""
  439. mappingEdbList[i].EdbName = edbInfoMappingB.EdbName + "映射" + edbInfoMappingA.EdbName
  440. if config.IndexType == 2 {
  441. if config.LeadValue > 0 {
  442. mappingEdbList[i].EdbName = edbInfoMappingB.EdbName + "映射" + edbInfoMappingA.EdbName + "(领先" + strconv.Itoa(config.LeadValue) + config.LeadFrequency + ")"
  443. }
  444. }
  445. edbData := convertEdbDataListToEdbData(dataBList)
  446. mappingEdbList[i].DataList = edbData
  447. }
  448. }
  449. return mappingEdbList, a, b, r, nil
  450. }
  451. // FillDataBList 填充B的数据 使得与A的时间保持一致
  452. func FillDataBList(dataList []*EdbData, edbInfoMappingA *EdbInfoList) []*EdbData {
  453. dataAList := edbInfoMappingA.DataList
  454. for utils.StringToTime(dataList[len(dataList)-1].DataTime).Before(utils.StringToTime(dataAList[len(dataAList)-1].DataTime)) {
  455. // 使用A的时间填充时间差
  456. timeDiff := utils.GetNextDayN(dataList[len(dataList)-1].DataTime, 1)
  457. // 创建新的数据点并填充 前值填充
  458. newDataPoint := &EdbData{
  459. DataTime: timeDiff,
  460. Value: dataList[len(dataList)-1].Value,
  461. DataTimestamp: utils.StringToTime(timeDiff).UnixMilli(),
  462. }
  463. // 将新数据点添加到dataList末尾
  464. dataList = append(dataList, newDataPoint)
  465. }
  466. return dataList
  467. }
  468. func fillOriginalChart(config ResidualAnalysisConfig, req *EdbInfo, mappingList []*EdbInfoList, startDate string, endDate string, edbInfoMappingA *EdbInfoList, edbInfoMappingB *EdbInfoList, originalEdbList []EdbInfoList) ([]EdbInfoList, []*EdbDataList, []*EdbDataList, error) {
  469. var fullADataList, fullBDataList []*EdbDataList
  470. for _, v := range mappingList {
  471. var edbInfoMapping EdbInfoList
  472. edbInfoMapping.EdbName = v.EdbName
  473. // 获取图表中的指标数据
  474. dataList, err := GetEdbDataList(v.Source, v.SubSource, v.EdbInfoId, startDate, endDate)
  475. if err != nil {
  476. return nil, nil, nil, fmt.Errorf("获取指标数据失败,Err:%s", err.Error())
  477. }
  478. data := convertEdbDataListToEdbData(dataList)
  479. // 重新获取指标数据 产品要求需要和计算指标-拟合残差逻辑保持一致
  480. fullDataList, err := GetEdbDataList(v.Source, v.SubSource, v.EdbInfoId, "", "")
  481. if err != nil {
  482. return nil, nil, nil, fmt.Errorf("获取指标数据失败,Err:%s", err.Error())
  483. }
  484. if v.EdbInfoId == edbInfoMappingB.EdbInfoId {
  485. // 领先指标 dataList进行数据处理
  486. if config.IndexType == 1 {
  487. if config.LeadValue < 0 {
  488. return nil, nil, nil, fmt.Errorf("领先值不能小于0")
  489. } else if config.LeadValue > 0 {
  490. edbInfoMapping.EdbName = v.EdbName + "(领先" + strconv.Itoa(config.LeadValue) + config.LeadFrequency + ")"
  491. for _, indexData := range dataList {
  492. switch config.LeadFrequency {
  493. case "天":
  494. indexData.DataTime = utils.GetNextDayN(indexData.DataTime, config.LeadValue)
  495. case "周":
  496. indexData.DataTime = utils.GetNextDayN(indexData.DataTime, config.LeadValue*7)
  497. case "月":
  498. indexData.DataTime = utils.TimeToString(utils.AddDate(utils.StringToTime(indexData.DataTime), 0, config.LeadValue), utils.YearMonthDay)
  499. case "季":
  500. indexData.DataTime = utils.TimeToString(utils.AddDate(utils.StringToTime(indexData.DataTime), 0, config.LeadValue*3), utils.YearMonthDay)
  501. case "年":
  502. indexData.DataTime = utils.TimeToString(utils.AddDate(utils.StringToTime(indexData.DataTime), config.LeadValue, 0), utils.YearMonthDay)
  503. }
  504. indexData.DataTimestamp = utils.StringToTime(indexData.DataTime).UnixMilli()
  505. }
  506. }
  507. }
  508. edbInfoMappingB.DataList = data
  509. fullBDataList = fullDataList
  510. } else {
  511. edbInfoMappingA.DataList = data
  512. fullADataList = fullDataList
  513. }
  514. edbInfoMapping.EdbInfoId = v.EdbInfoId
  515. edbInfoMapping.EdbCode = v.EdbCode
  516. edbInfoMapping.Unit = v.Unit
  517. edbInfoMapping.Frequency = v.Frequency
  518. edbInfoMapping.Source = v.Source
  519. edbInfoMapping.SourceName = v.SourceName
  520. edbInfoMapping.LatestDate = v.LatestDate
  521. edbInfoMapping.LatestValue = v.LatestValue
  522. edbInfoMapping.DataList = data
  523. originalEdbList = append(originalEdbList, edbInfoMapping)
  524. }
  525. return originalEdbList, fullADataList, fullBDataList, nil
  526. }
  527. func convertEdbDataListToEdbData(edbDataLists []*EdbDataList) []*EdbData {
  528. var edbDataList []*EdbData
  529. for _, edbData := range edbDataLists {
  530. data := &EdbData{
  531. DataTime: edbData.DataTime,
  532. DataTimestamp: edbData.DataTimestamp,
  533. EdbDataId: edbData.EdbDataId,
  534. EdbInfoId: edbData.EdbInfoId,
  535. Value: fmt.Sprintf("%f", edbData.Value),
  536. }
  537. edbDataList = append(edbDataList, data)
  538. }
  539. return edbDataList
  540. }
  541. type ByDataTime []*EdbData
  542. func (a ByDataTime) Len() int {
  543. return len(a)
  544. }
  545. func (a ByDataTime) Swap(i, j int) {
  546. a[i], a[j] = a[j], a[i]
  547. }
  548. func (a ByDataTime) Less(i, j int) bool {
  549. t1 := utils.StringToTime(a[i].DataTime)
  550. t2 := utils.StringToTime(a[j].DataTime)
  551. return t1.Before(t2)
  552. }