edb_data_residual_analysis.go 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654
  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. // 映射指标 与 残差指标 同步刷新
  140. for _, mapping := range configMapping {
  141. var edbDataResidualAnalysisList []edbDataResidualAnalysis
  142. if mapping.IndexType == 1 {
  143. edbInfo, err := GetEdbInfoById(int(mapping.EdbInfoId))
  144. if err != nil {
  145. return err
  146. }
  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. edbInfo, err := GetEdbInfoById(int(mapping.EdbInfoId))
  165. if err != nil {
  166. return err
  167. }
  168. for _, edbData := range residualEdbList[1].DataList {
  169. value, _ := strconv.ParseFloat(edbData.Value, 64)
  170. edbDataResidualAnalysisList = append(edbDataResidualAnalysisList, edbDataResidualAnalysis{
  171. EdbInfoId: int(mapping.EdbInfoId),
  172. EdbCode: edbInfo.EdbCode,
  173. DataTime: edbData.DataTime,
  174. Value: value,
  175. CreateTime: time.Now(),
  176. ModifyTime: time.Now(),
  177. DataTimeStamp: edbData.DataTimestamp,
  178. })
  179. }
  180. _, err = AddResidualAnalysisData(edbDataResidualAnalysisList)
  181. if err != nil {
  182. return err
  183. }
  184. }
  185. }
  186. return
  187. }
  188. func fillResidualChartInfo(config ResidualAnalysisConfig, req *EdbInfo, edbInfoMappingA *EdbInfoList, edbInfoMappingB *EdbInfoList, mappingEdbList []EdbInfoList) ([]EdbInfoList, float64, error) {
  189. // 计算公式 映射残差 = 因变量指标 - 映射指标
  190. var edbInfoA, edbInfoB EdbInfoList
  191. if mappingEdbList[0].EdbInfoId == edbInfoMappingA.EdbInfoId {
  192. edbInfoA = mappingEdbList[0]
  193. edbInfoB = mappingEdbList[1]
  194. } else {
  195. edbInfoA = mappingEdbList[1]
  196. edbInfoB = mappingEdbList[0]
  197. }
  198. dataAList := edbInfoA.DataList
  199. edbData := make([]*EdbDataList, len(dataAList))
  200. for i, data := range dataAList {
  201. f, _ := strconv.ParseFloat(data.Value, 64)
  202. edbData[i] = &EdbDataList{
  203. Value: f,
  204. DataTimestamp: data.DataTimestamp,
  205. DataTime: data.DataTime,
  206. EdbInfoId: data.EdbInfoId,
  207. EdbDataId: data.EdbDataId,
  208. }
  209. }
  210. dataBList := edbInfoB.DataList
  211. // 映射指标开始时间
  212. var startTime string
  213. if len(dataBList) > 0 {
  214. startTime = dataBList[0].DataTime
  215. }
  216. var indexDataBMap = make(map[string]*EdbData)
  217. for _, data := range dataBList {
  218. indexDataBMap[data.DataTime] = data
  219. }
  220. // 求R2
  221. var valueB, sumValueA, averageValueA, residualQuadraticSum, totalQuadraticSum, R2 float64
  222. for _, indexData := range edbData {
  223. // 因变量的值总和
  224. sumValueA += indexData.Value
  225. }
  226. // 因变量平均值
  227. averageValueA = sumValueA / float64(len(edbData))
  228. var indexMax, indexMin float64
  229. var edbDataResp []*EdbDataList
  230. if len(edbData) > 0 {
  231. indexMax = edbData[0].Value
  232. indexMin = edbData[0].Value
  233. for _, indexData := range edbData {
  234. if dataB, ok := indexDataBMap[indexData.DataTime]; ok {
  235. f, _ := strconv.ParseFloat(dataB.Value, 64)
  236. valueB = f
  237. } else {
  238. continue
  239. }
  240. // 总因变量平方和
  241. totalQuadraticSum += math.Pow(indexData.Value-averageValueA, 2)
  242. // 补全残差值
  243. indexData.Value = math.Round((indexData.Value-valueB)*10000) / 10000
  244. // 残差平方和
  245. residualQuadraticSum += math.Pow(indexData.Value, 2)
  246. if indexData.Value > indexMax {
  247. indexMax = indexData.Value
  248. }
  249. if indexData.Value < indexMin {
  250. indexMin = indexData.Value
  251. }
  252. // 获取映射指标之后的数据
  253. if startTime != "" && utils.CompareDate(startTime, indexData.DataTime) {
  254. edbDataResp = append(edbDataResp, indexData)
  255. }
  256. }
  257. }
  258. // 计算R2 公式:R2=1-SSE/SST R2越大,越符合线性 R2 = 1 - 残差平方和/总平方和
  259. R2 = 1 - residualQuadraticSum/totalQuadraticSum
  260. mappingEdb := make([]EdbInfoList, len(mappingEdbList))
  261. copy(mappingEdb, mappingEdbList)
  262. for i, mapping := range mappingEdb {
  263. if mapping.EdbInfoId != edbInfoMappingA.EdbInfoId {
  264. toEdbData := convertEdbDataListToEdbData(edbDataResp)
  265. mappingEdb[i].DataList = toEdbData
  266. mappingEdb[i].EdbName = edbInfoMappingA.EdbName + "映射残差/" + edbInfoMappingB.EdbName
  267. if config.IndexType == 2 {
  268. if config.LeadValue > 0 {
  269. mappingEdb[i].EdbName = edbInfoMappingA.EdbName + "映射残差/" + edbInfoMappingB.EdbName + "(领先" + strconv.Itoa(config.LeadValue) + config.LeadFrequency + ")"
  270. }
  271. }
  272. }
  273. }
  274. return mappingEdb, R2, nil
  275. }
  276. 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) {
  277. // 计算公式:Y=aX+b,Y为映射后的指标,X为自变量指标
  278. // 正序:a=(L2-L1)/(R2-R1) b=L2-R2*a
  279. // 逆序:a=(L2-L1)/(R1-R2) b=L2-R1*a
  280. // L2:左轴下限 R2:右轴上限 L1:左轴上限 R1:右轴下限
  281. var a, b, r float64
  282. // 映射残差 计算a,b
  283. if config.ResidualType == 1 {
  284. if config.IsOrder {
  285. a = (config.LeftIndexMax - config.LeftIndexMin) / (config.RightIndexMin - config.RightIndexMax)
  286. b = config.LeftIndexMax - config.RightIndexMin*a
  287. } else {
  288. a = (config.LeftIndexMax - config.LeftIndexMin) / (config.RightIndexMax - config.RightIndexMin)
  289. b = config.LeftIndexMax - config.RightIndexMax*a
  290. }
  291. }
  292. dataList := edbInfoMappingB.DataList
  293. // 指标B数据补充
  294. // 新建一个切片来保存补充的数据
  295. var replenishDataList []*EdbData
  296. for index := 0; index < len(dataList)-1; index++ {
  297. // 获取当前数据和下一个数据
  298. beforeIndexData := dataList[index]
  299. afterIndexData := dataList[index+1]
  300. // 从最早时间开始,补充时间为自然日
  301. for utils.IsMoreThanOneDay(beforeIndexData.DataTime, afterIndexData.DataTime) {
  302. // 创建补充数据
  303. nextDay := utils.GetNextDay(beforeIndexData.DataTime)
  304. toTime := utils.StringToTime(nextDay)
  305. replenishIndexData := EdbData{
  306. DataTime: nextDay, // 计算下一个自然日
  307. DataTimestamp: toTime.UnixMilli(),
  308. Value: beforeIndexData.Value, // 可以选择使用前一天的值,或者其他逻辑来计算值
  309. }
  310. // 将补充数据加入补充数据列表
  311. replenishDataList = append(replenishDataList, &replenishIndexData)
  312. // 更新 beforeIndexData 为新创建的补充数据
  313. beforeIndexData = &replenishIndexData
  314. }
  315. }
  316. // 将补充数据插入原始数据列表
  317. dataList = append(dataList, replenishDataList...)
  318. // 排序
  319. sort.Sort(ByDataTime(dataList))
  320. // 拟合残差 计算a,b
  321. var coordinateList []utils.Coordinate
  322. var replenishADataList []*EdbDataList
  323. var replenishBDataList []*EdbDataList
  324. if config.ResidualType == 2 {
  325. //
  326. // 因变量指标也转换为日度
  327. for index := 0; index < len(fullADataList)-1; index++ {
  328. // 获取当前数据和下一个数据
  329. beforeIndexData := fullADataList[index]
  330. afterIndexData := fullADataList[index+1]
  331. replenishADataList = append(replenishADataList, beforeIndexData)
  332. // 从最早时间开始,补充时间为自然日
  333. if utils.IsMoreThanOneDay(beforeIndexData.DataTime, afterIndexData.DataTime) {
  334. for {
  335. // 创建补充数据
  336. nextDay := utils.GetNextDay(beforeIndexData.DataTime)
  337. toTime := utils.StringToTime(nextDay)
  338. replenishIndexData := EdbDataList{
  339. DataTime: nextDay, // 计算下一个自然日
  340. DataTimestamp: toTime.UnixMilli(),
  341. Value: beforeIndexData.Value, // 可以选择使用前一天的值,或者其他逻辑来计算值
  342. }
  343. // 将补充数据加入补充数据列表
  344. replenishADataList = append(replenishADataList, &replenishIndexData)
  345. // 更新 beforeIndexData 为新创建的补充数据
  346. beforeIndexData = &replenishIndexData
  347. // 检查是否还需要继续补充数据
  348. if !utils.IsMoreThanOneDay(beforeIndexData.DataTime, afterIndexData.DataTime) {
  349. break
  350. }
  351. }
  352. }
  353. }
  354. replenishADataList = append(replenishADataList, fullADataList[len(fullADataList)-1])
  355. // 自变量指标也转换为日度
  356. for index := 0; index < len(fullBDataList)-1; index++ {
  357. // 获取当前数据和下一个数据
  358. beforeIndexData := fullBDataList[index]
  359. afterIndexData := fullBDataList[index+1]
  360. replenishBDataList = append(replenishBDataList, beforeIndexData)
  361. // 从最早时间开始,补充时间为自然日
  362. if utils.IsMoreThanOneDay(beforeIndexData.DataTime, afterIndexData.DataTime) {
  363. for {
  364. // 创建补充数据
  365. nextDay := utils.GetNextDay(beforeIndexData.DataTime)
  366. toTime := utils.StringToTime(nextDay)
  367. replenishIndexData := EdbDataList{
  368. DataTime: nextDay, // 计算下一个自然日
  369. DataTimestamp: toTime.UnixMilli(),
  370. Value: beforeIndexData.Value, // 可以选择使用前一天的值,或者其他逻辑来计算值
  371. }
  372. // 将补充数据加入补充数据列表
  373. replenishBDataList = append(replenishBDataList, &replenishIndexData)
  374. // 更新 beforeIndexData 为新创建的补充数据
  375. beforeIndexData = &replenishIndexData
  376. // 检查是否还需要继续补充数据
  377. if !utils.IsMoreThanOneDay(beforeIndexData.DataTime, afterIndexData.DataTime) {
  378. break
  379. }
  380. }
  381. }
  382. }
  383. replenishBDataList = append(replenishBDataList, fullBDataList[len(fullBDataList)-1])
  384. // replenishADataList --> map
  385. replenishADataMap := make(map[string]*EdbDataList)
  386. for _, indexData := range replenishADataList {
  387. 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))) {
  388. replenishADataMap[indexData.DataTime] = indexData
  389. }
  390. }
  391. for _, indexData := range replenishBDataList {
  392. if _, ok := replenishADataMap[indexData.DataTime]; ok {
  393. coordinate := utils.Coordinate{
  394. X: indexData.Value,
  395. Y: replenishADataMap[indexData.DataTime].Value,
  396. }
  397. coordinateList = append(coordinateList, coordinate)
  398. }
  399. }
  400. a, b = utils.GetLinearResult(coordinateList)
  401. r = utils.ComputeCorrelation(coordinateList)
  402. }
  403. // 填充映射指标值 使得时间长度一致
  404. dataList = FillDataBList(dataList, edbInfoMappingA)
  405. // 根据指标A的时间key,在B的映射指标中筛选出对应的值
  406. var dataBList []*EdbDataList
  407. var indexMax, indexMin string
  408. if len(dataList) > 0 {
  409. indexMax = dataList[0].Value
  410. indexMin = dataList[0].Value
  411. for _, indexData := range dataList {
  412. if _, ok := indexADataMap[indexData.DataTime]; ok {
  413. indexDataCopy := *indexData
  414. // 计算指标B映射值
  415. f, _ := strconv.ParseFloat(indexData.Value, 64)
  416. indexDataCopy.Value = fmt.Sprintf("%f", math.Round((a*f+b)*10000)/10000)
  417. // 比较最大值
  418. if indexData.Value > indexMax {
  419. indexMax = indexData.Value
  420. }
  421. // 比较最小值
  422. if indexData.Value < indexMin {
  423. indexMin = indexData.Value
  424. }
  425. // 将副本添加到 dataBList
  426. copyValue, _ := strconv.ParseFloat(indexDataCopy.Value, 64)
  427. dataBList = append(dataBList, &EdbDataList{
  428. DataTime: indexDataCopy.DataTime,
  429. DataTimestamp: indexDataCopy.DataTimestamp,
  430. EdbDataId: indexDataCopy.EdbDataId,
  431. EdbInfoId: indexDataCopy.EdbInfoId,
  432. Value: copyValue,
  433. })
  434. }
  435. }
  436. }
  437. mappingEdbList := make([]EdbInfoList, len(originalEdbList))
  438. copy(mappingEdbList, originalEdbList)
  439. for i, mapping := range mappingEdbList {
  440. if mapping.EdbInfoId != edbInfoMappingA.EdbInfoId {
  441. mappingEdbList[i].EdbInfoId = 0
  442. mappingEdbList[i].EdbCode = ""
  443. mappingEdbList[i].EdbName = edbInfoMappingB.EdbName + "映射" + edbInfoMappingA.EdbName
  444. if config.IndexType == 2 {
  445. if config.LeadValue > 0 {
  446. mappingEdbList[i].EdbName = edbInfoMappingB.EdbName + "映射" + edbInfoMappingA.EdbName + "(领先" + strconv.Itoa(config.LeadValue) + config.LeadFrequency + ")"
  447. }
  448. }
  449. edbData := convertEdbDataListToEdbData(dataBList)
  450. mappingEdbList[i].DataList = edbData
  451. }
  452. }
  453. return mappingEdbList, a, b, r, nil
  454. }
  455. // FillDataBList 填充B的数据 使得与A的时间保持一致
  456. func FillDataBList(dataList []*EdbData, edbInfoMappingA *EdbInfoList) []*EdbData {
  457. dataAList := edbInfoMappingA.DataList
  458. for utils.StringToTime(dataList[len(dataList)-1].DataTime).Before(utils.StringToTime(dataAList[len(dataAList)-1].DataTime)) {
  459. // 使用A的时间填充时间差
  460. timeDiff := utils.GetNextDayN(dataList[len(dataList)-1].DataTime, 1)
  461. // 创建新的数据点并填充 前值填充
  462. newDataPoint := &EdbData{
  463. DataTime: timeDiff,
  464. Value: dataList[len(dataList)-1].Value,
  465. DataTimestamp: utils.StringToTime(timeDiff).UnixMilli(),
  466. }
  467. // 将新数据点添加到dataList末尾
  468. dataList = append(dataList, newDataPoint)
  469. }
  470. return dataList
  471. }
  472. func fillOriginalChart(config ResidualAnalysisConfig, req *EdbInfo, mappingList []*EdbInfoList, startDate string, endDate string, edbInfoMappingA *EdbInfoList, edbInfoMappingB *EdbInfoList, originalEdbList []EdbInfoList) ([]EdbInfoList, []*EdbDataList, []*EdbDataList, error) {
  473. var fullADataList, fullBDataList []*EdbDataList
  474. for _, v := range mappingList {
  475. var edbInfoMapping EdbInfoList
  476. edbInfoMapping.EdbName = v.EdbName
  477. // 获取图表中的指标数据
  478. dataList, err := GetEdbDataList(v.Source, v.SubSource, v.EdbInfoId, startDate, endDate)
  479. if err != nil {
  480. return nil, nil, nil, fmt.Errorf("获取指标数据失败,Err:%s", err.Error())
  481. }
  482. data := convertEdbDataListToEdbData(dataList)
  483. // 重新获取指标数据 产品要求需要和计算指标-拟合残差逻辑保持一致
  484. fullDataList, err := GetEdbDataList(v.Source, v.SubSource, v.EdbInfoId, "", "")
  485. if err != nil {
  486. return nil, nil, nil, fmt.Errorf("获取指标数据失败,Err:%s", err.Error())
  487. }
  488. if v.EdbInfoId == edbInfoMappingB.EdbInfoId {
  489. // 领先指标 dataList进行数据处理
  490. if config.IndexType == 1 {
  491. if config.LeadValue < 0 {
  492. return nil, nil, nil, fmt.Errorf("领先值不能小于0")
  493. } else if config.LeadValue > 0 {
  494. edbInfoMapping.EdbName = v.EdbName + "(领先" + strconv.Itoa(config.LeadValue) + config.LeadFrequency + ")"
  495. for _, indexData := range dataList {
  496. switch config.LeadFrequency {
  497. case "天":
  498. indexData.DataTime = utils.GetNextDayN(indexData.DataTime, config.LeadValue)
  499. case "周":
  500. indexData.DataTime = utils.GetNextDayN(indexData.DataTime, config.LeadValue*7)
  501. case "月":
  502. indexData.DataTime = utils.TimeToString(utils.AddDate(utils.StringToTime(indexData.DataTime), 0, config.LeadValue), utils.YearMonthDay)
  503. case "季":
  504. indexData.DataTime = utils.TimeToString(utils.AddDate(utils.StringToTime(indexData.DataTime), 0, config.LeadValue*3), utils.YearMonthDay)
  505. case "年":
  506. indexData.DataTime = utils.TimeToString(utils.AddDate(utils.StringToTime(indexData.DataTime), config.LeadValue, 0), utils.YearMonthDay)
  507. }
  508. indexData.DataTimestamp = utils.StringToTime(indexData.DataTime).UnixMilli()
  509. }
  510. }
  511. }
  512. edbInfoMappingB.DataList = data
  513. fullBDataList = fullDataList
  514. } else {
  515. edbInfoMappingA.DataList = data
  516. fullADataList = fullDataList
  517. }
  518. edbInfoMapping.EdbInfoId = v.EdbInfoId
  519. edbInfoMapping.EdbCode = v.EdbCode
  520. edbInfoMapping.Unit = v.Unit
  521. edbInfoMapping.Frequency = v.Frequency
  522. edbInfoMapping.Source = v.Source
  523. edbInfoMapping.SourceName = v.SourceName
  524. edbInfoMapping.LatestDate = v.LatestDate
  525. edbInfoMapping.LatestValue = v.LatestValue
  526. edbInfoMapping.DataList = data
  527. originalEdbList = append(originalEdbList, edbInfoMapping)
  528. }
  529. return originalEdbList, fullADataList, fullBDataList, nil
  530. }
  531. func convertEdbDataListToEdbData(edbDataLists []*EdbDataList) []*EdbData {
  532. var edbDataList []*EdbData
  533. for _, edbData := range edbDataLists {
  534. data := &EdbData{
  535. DataTime: edbData.DataTime,
  536. DataTimestamp: edbData.DataTimestamp,
  537. EdbDataId: edbData.EdbDataId,
  538. EdbInfoId: edbData.EdbInfoId,
  539. Value: fmt.Sprintf("%f", edbData.Value),
  540. }
  541. edbDataList = append(edbDataList, data)
  542. }
  543. return edbDataList
  544. }
  545. type ByDataTime []*EdbData
  546. func (a ByDataTime) Len() int {
  547. return len(a)
  548. }
  549. func (a ByDataTime) Swap(i, j int) {
  550. a[i], a[j] = a[j], a[i]
  551. }
  552. func (a ByDataTime) Less(i, j int) bool {
  553. t1 := utils.StringToTime(a[i].DataTime)
  554. t2 := utils.StringToTime(a[j].DataTime)
  555. return t1.Before(t2)
  556. }