predict_edb_info_rule.go 66 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819
  1. package data
  2. import (
  3. "encoding/json"
  4. "errors"
  5. "fmt"
  6. "github.com/nosixtools/solarlunar"
  7. "github.com/shopspring/decimal"
  8. "hongze/hongze_chart_lib/models"
  9. "hongze/hongze_chart_lib/models/data_manage"
  10. "hongze/hongze_chart_lib/utils"
  11. "math"
  12. "strings"
  13. "time"
  14. )
  15. // GetChartPredictEdbInfoDataListByRule1 根据规则1获取预测数据
  16. func GetChartPredictEdbInfoDataListByRule1(edbInfoId int, dataValue float64, startDate, endDate time.Time, frequency string, predictEdbInfoData []*models.EdbDataList, existMap map[string]float64) (newPredictEdbInfoData []*models.EdbDataList) {
  17. newPredictEdbInfoData = predictEdbInfoData
  18. //获取后面的预测数据
  19. dayList := getPredictEdbDayList(startDate, endDate, frequency)
  20. predictEdbInfoData = make([]*models.EdbDataList, 0)
  21. for k, v := range dayList {
  22. newPredictEdbInfoData = append(newPredictEdbInfoData, &models.EdbDataList{
  23. EdbDataId: edbInfoId + 10000000000 + k,
  24. EdbInfoId: edbInfoId,
  25. DataTime: v.Format(utils.FormatDate),
  26. Value: dataValue,
  27. DataTimestamp: v.UnixNano() / 1e6,
  28. })
  29. existMap[v.Format(utils.FormatDate)] = dataValue
  30. }
  31. return
  32. }
  33. // GetChartPredictEdbInfoDataListByRuleTb 根据同比值规则获取预测数据
  34. // 2.1 同比: 在未来某一个时间段内,给定一个固定的同比增速a,用去年同期值X乘以同比增速(1+a),得到预测值Y=X(1+a)
  35. // 例: 今年1-3月值,100,100,120。给定同比增速a=0.1,则明年1-3月预测值为: 100*1.1=110,100*1.1=110,120*1.1=132。
  36. func GetChartPredictEdbInfoDataListByRuleTb(edbInfoId int, tbValue float64, startDate, endDate time.Time, frequency string, realPredictEdbInfoData, predictEdbInfoData []*models.EdbDataList, existMap map[string]float64) (newPredictEdbInfoData []*models.EdbDataList, minValue, maxValue float64) {
  37. allDataList := make([]*models.EdbDataList, 0)
  38. allDataList = append(allDataList, realPredictEdbInfoData...)
  39. allDataList = append(allDataList, predictEdbInfoData...)
  40. newPredictEdbInfoData = predictEdbInfoData
  41. index := len(allDataList)
  42. //获取后面的预测数据
  43. dayList := getPredictEdbDayList(startDate, endDate, frequency)
  44. predictEdbInfoData = make([]*models.EdbDataList, 0)
  45. for k, currentDate := range dayList {
  46. tmpData := &models.EdbDataList{
  47. EdbDataId: edbInfoId + 10000000000 + index + k,
  48. EdbInfoId: edbInfoId,
  49. DataTime: currentDate.Format(utils.FormatDate),
  50. //Value: dataValue,
  51. DataTimestamp: currentDate.UnixNano() / 1e6,
  52. }
  53. var val float64
  54. var calculateStatus bool //计算结果
  55. //currentItem := existMap[av]
  56. //上一年的日期
  57. preDate := currentDate.AddDate(-1, 0, 0)
  58. preDateStr := preDate.Format(utils.FormatDate)
  59. if preValue, ok := existMap[preDateStr]; ok { //上一年同期找到
  60. val = TbzDiv(preValue, tbValue)
  61. calculateStatus = true
  62. } else {
  63. switch frequency {
  64. case "月度":
  65. //向上和向下,各找一个月
  66. nextDateDay := preDate
  67. preDateDay := preDate
  68. for i := 0; i <= 35; i++ {
  69. nextDateDayStr := nextDateDay.Format(utils.FormatDate)
  70. if preValue, ok := existMap[nextDateDayStr]; ok { //上一年同期->下一个月找到
  71. val = TbzDiv(preValue, tbValue)
  72. calculateStatus = true
  73. break
  74. } else {
  75. preDateDayStr := preDateDay.Format(utils.FormatDate)
  76. if preValue, ok := existMap[preDateDayStr]; ok { //上一年同期->上一个月找到
  77. val = TbzDiv(preValue, tbValue)
  78. calculateStatus = true
  79. break
  80. }
  81. }
  82. nextDateDay = nextDateDay.AddDate(0, 0, 1)
  83. preDateDay = preDateDay.AddDate(0, 0, -1)
  84. }
  85. case "季度", "年度":
  86. if preValue, ok := existMap[preDateStr]; ok { //上一年同期->下一个月找到
  87. val = TbzDiv(preValue, tbValue)
  88. calculateStatus = true
  89. break
  90. }
  91. default:
  92. nextDateDay := preDate
  93. preDateDay := preDate
  94. for i := 0; i < 35; i++ {
  95. nextDateDayStr := nextDateDay.Format(utils.FormatDate)
  96. if preValue, ok := existMap[nextDateDayStr]; ok { //上一年同期->下一个月找到
  97. val = TbzDiv(preValue, tbValue)
  98. calculateStatus = true
  99. break
  100. } else {
  101. preDateDayStr := preDateDay.Format(utils.FormatDate)
  102. if preValue, ok := existMap[preDateDayStr]; ok { //上一年同期->上一个月找到
  103. val = TbzDiv(preValue, tbValue)
  104. calculateStatus = true
  105. break
  106. } else {
  107. //fmt.Println("pre not find:", preDateStr, "i:", i)
  108. }
  109. }
  110. nextDateDay = nextDateDay.AddDate(0, 0, 1)
  111. preDateDay = preDateDay.AddDate(0, 0, -1)
  112. }
  113. }
  114. }
  115. if calculateStatus {
  116. tmpData.Value = val
  117. newPredictEdbInfoData = append(newPredictEdbInfoData, tmpData)
  118. allDataList = append(allDataList, tmpData)
  119. existMap[tmpData.DataTime] = val
  120. // 最大最小值
  121. if val < minValue {
  122. minValue = val
  123. }
  124. if val > maxValue {
  125. maxValue = val
  126. }
  127. }
  128. }
  129. return
  130. }
  131. // TbzDiv 同比值计算
  132. // @params a float64 去年同期值
  133. // @params b float64 固定同比增速
  134. func TbzDiv(a, b float64) (result float64) {
  135. if b != 0 {
  136. // 去年同期值
  137. af := decimal.NewFromFloat(a)
  138. // 同比增速
  139. bf := decimal.NewFromFloat(b)
  140. // 默认1
  141. cf := decimal.NewFromFloat(1)
  142. // 总增速
  143. val := bf.Add(cf)
  144. // 计算
  145. result, _ = val.Mul(af).RoundCeil(4).Float64()
  146. } else {
  147. result = 0
  148. }
  149. return
  150. }
  151. // GetChartPredictEdbInfoDataListByRuleTc 根据同差值规则获取预测数据
  152. // 2.2 同差: 在未来某一个时间段内,给定一个固定的同比增加值a,用去年同期值X加上同比增加值A,得到预测值Y=X+a
  153. // 例: 今年1-3月值,100,100,120。给定同比增加值a=10,则明年1-3月预测值为: 100+10=110,100+10=110,120+10=130
  154. func GetChartPredictEdbInfoDataListByRuleTc(edbInfoId int, tcValue float64, startDate, endDate time.Time, frequency string, realPredictEdbInfoData, predictEdbInfoData []*models.EdbDataList, existMap map[string]float64) (newPredictEdbInfoData []*models.EdbDataList, minValue, maxValue float64) {
  155. allDataList := make([]*models.EdbDataList, 0)
  156. allDataList = append(allDataList, realPredictEdbInfoData...)
  157. allDataList = append(allDataList, predictEdbInfoData...)
  158. newPredictEdbInfoData = predictEdbInfoData
  159. index := len(allDataList)
  160. //获取后面的预测数据
  161. dayList := getPredictEdbDayList(startDate, endDate, frequency)
  162. predictEdbInfoData = make([]*models.EdbDataList, 0)
  163. for k, currentDate := range dayList {
  164. tmpData := &models.EdbDataList{
  165. EdbDataId: edbInfoId + 10000000000 + index + k,
  166. EdbInfoId: edbInfoId,
  167. DataTime: currentDate.Format(utils.FormatDate),
  168. //Value: dataValue,
  169. DataTimestamp: currentDate.UnixNano() / 1e6,
  170. }
  171. var val float64
  172. var calculateStatus bool //计算结果
  173. //currentItem := existMap[av]
  174. //上一年的日期
  175. preDate := currentDate.AddDate(-1, 0, 0)
  176. preDateStr := preDate.Format(utils.FormatDate)
  177. if preValue, ok := existMap[preDateStr]; ok { //上一年同期找到
  178. val = TczDiv(preValue, tcValue)
  179. calculateStatus = true
  180. } else {
  181. switch frequency {
  182. case "月度":
  183. //向上和向下,各找一个月
  184. nextDateDay := preDate
  185. preDateDay := preDate
  186. for i := 0; i <= 35; i++ {
  187. nextDateDayStr := nextDateDay.Format(utils.FormatDate)
  188. if preValue, ok := existMap[nextDateDayStr]; ok { //上一年同期->下一个月找到
  189. val = TczDiv(preValue, tcValue)
  190. calculateStatus = true
  191. break
  192. } else {
  193. preDateDayStr := preDateDay.Format(utils.FormatDate)
  194. if preValue, ok := existMap[preDateDayStr]; ok { //上一年同期->上一个月找到
  195. val = TczDiv(preValue, tcValue)
  196. calculateStatus = true
  197. break
  198. }
  199. }
  200. nextDateDay = nextDateDay.AddDate(0, 0, 1)
  201. preDateDay = preDateDay.AddDate(0, 0, -1)
  202. }
  203. case "季度", "年度":
  204. if preValue, ok := existMap[preDateStr]; ok { //上一年同期->下一个月找到
  205. val = TczDiv(preValue, tcValue)
  206. calculateStatus = true
  207. break
  208. }
  209. default:
  210. nextDateDay := preDate
  211. preDateDay := preDate
  212. for i := 0; i < 35; i++ {
  213. nextDateDayStr := nextDateDay.Format(utils.FormatDate)
  214. if preValue, ok := existMap[nextDateDayStr]; ok { //上一年同期->下一个月找到
  215. val = TczDiv(preValue, tcValue)
  216. calculateStatus = true
  217. break
  218. } else {
  219. preDateDayStr := preDateDay.Format(utils.FormatDate)
  220. if preValue, ok := existMap[preDateDayStr]; ok { //上一年同期->上一个月找到
  221. val = TczDiv(preValue, tcValue)
  222. calculateStatus = true
  223. break
  224. } else {
  225. //fmt.Println("pre not find:", preDateStr, "i:", i)
  226. }
  227. }
  228. nextDateDay = nextDateDay.AddDate(0, 0, 1)
  229. preDateDay = preDateDay.AddDate(0, 0, -1)
  230. }
  231. }
  232. }
  233. if calculateStatus {
  234. tmpData.Value = val
  235. newPredictEdbInfoData = append(newPredictEdbInfoData, tmpData)
  236. allDataList = append(allDataList, tmpData)
  237. existMap[tmpData.DataTime] = val
  238. // 最大最小值
  239. if val < minValue {
  240. minValue = val
  241. }
  242. if val > maxValue {
  243. maxValue = val
  244. }
  245. }
  246. }
  247. return
  248. }
  249. // TczDiv 环差值计算
  250. // @params a float64 上一期值
  251. // @params b float64 固定的环比增加值
  252. func TczDiv(a, b float64) (result float64) {
  253. if b != 0 {
  254. // 上一期值
  255. af := decimal.NewFromFloat(a)
  256. // 固定的环比增加值
  257. bf := decimal.NewFromFloat(b)
  258. // 计算
  259. result, _ = af.Add(bf).RoundCeil(4).Float64()
  260. } else {
  261. result = 0
  262. }
  263. return
  264. }
  265. // GetChartPredictEdbInfoDataListByRuleHb 根据环比值规则获取预测数据
  266. // 环比:在未来某一个时间段内,给定一个固定的环比增速a,用上一期值X乘以环比增速(1+a),得到预测值Y=X(1+a)
  267. // 例: 最近1期值为100,给定环比增速a=0.2,则未来3期预测值为: 100*1.2=120,120*1.2=144,144*1.2=172.8
  268. func GetChartPredictEdbInfoDataListByRuleHb(edbInfoId int, hbValue float64, startDate, endDate time.Time, frequency string, realPredictEdbInfoData, predictEdbInfoData []*models.EdbDataList, existMap map[string]float64) (newPredictEdbInfoData []*models.EdbDataList, minValue, maxValue float64) {
  269. allDataList := make([]*models.EdbDataList, 0)
  270. allDataList = append(allDataList, realPredictEdbInfoData...)
  271. allDataList = append(allDataList, predictEdbInfoData...)
  272. newPredictEdbInfoData = predictEdbInfoData
  273. index := len(allDataList)
  274. //获取后面的预测数据
  275. dayList := getPredictEdbDayList(startDate, endDate, frequency)
  276. for k, currentDate := range dayList {
  277. tmpK := index + k - 1 //上1期的值
  278. // 环比值计算
  279. val := HbzDiv(allDataList[tmpK].Value, hbValue)
  280. currentDateStr := currentDate.Format(utils.FormatDate)
  281. tmpData := &models.EdbDataList{
  282. EdbDataId: edbInfoId + 10000000000 + index + k,
  283. EdbInfoId: edbInfoId,
  284. DataTime: currentDateStr,
  285. Value: val,
  286. DataTimestamp: currentDate.UnixNano() / 1e6,
  287. }
  288. newPredictEdbInfoData = append(newPredictEdbInfoData, tmpData)
  289. allDataList = append(allDataList, tmpData)
  290. existMap[currentDateStr] = val
  291. // 最大最小值
  292. if val < minValue {
  293. minValue = val
  294. }
  295. if val > maxValue {
  296. maxValue = val
  297. }
  298. }
  299. return
  300. }
  301. // HbzDiv 环比值计算
  302. // @params a float64 上一期值
  303. // @params b float64 固定的环比增速
  304. func HbzDiv(a, b float64) (result float64) {
  305. if b != 0 {
  306. // 上一期值
  307. af := decimal.NewFromFloat(a)
  308. // 固定的环比增速
  309. bf := decimal.NewFromFloat(b)
  310. // 默认1
  311. cf := decimal.NewFromFloat(1)
  312. // 总增速
  313. val := bf.Add(cf)
  314. // 计算
  315. result, _ = val.Mul(af).RoundCeil(4).Float64()
  316. } else {
  317. result = 0
  318. }
  319. return
  320. }
  321. // GetChartPredictEdbInfoDataListByRuleHc 根据环差值规则获取预测数据
  322. // 2.4 环差:在未来某一个时间段内,给定一个固定的环比增加值a,用上一期值X加上环比增加值a,得到预测值Y=X+a
  323. // 例: 最近1期值为100,给定环比增加值a=10,则未来3期预测值为: 100+10=110,110+10=120,120+10=130
  324. func GetChartPredictEdbInfoDataListByRuleHc(edbInfoId int, hcValue float64, startDate, endDate time.Time, frequency string, realPredictEdbInfoData, predictEdbInfoData []*models.EdbDataList, existMap map[string]float64) (newPredictEdbInfoData []*models.EdbDataList, minValue, maxValue float64) {
  325. allDataList := make([]*models.EdbDataList, 0)
  326. allDataList = append(allDataList, realPredictEdbInfoData...)
  327. allDataList = append(allDataList, predictEdbInfoData...)
  328. newPredictEdbInfoData = predictEdbInfoData
  329. index := len(allDataList)
  330. //获取后面的预测数据
  331. dayList := getPredictEdbDayList(startDate, endDate, frequency)
  332. for k, currentDate := range dayList {
  333. tmpK := index + k - 1 //上1期的值
  334. // 环差别值计算
  335. val := HczDiv(allDataList[tmpK].Value, hcValue)
  336. currentDateStr := currentDate.Format(utils.FormatDate)
  337. tmpData := &models.EdbDataList{
  338. EdbDataId: edbInfoId + 10000000000 + index + k,
  339. EdbInfoId: edbInfoId,
  340. DataTime: currentDateStr,
  341. Value: val,
  342. DataTimestamp: currentDate.UnixNano() / 1e6,
  343. }
  344. newPredictEdbInfoData = append(newPredictEdbInfoData, tmpData)
  345. allDataList = append(allDataList, tmpData)
  346. existMap[currentDateStr] = val
  347. // 最大最小值
  348. if val < minValue {
  349. minValue = val
  350. }
  351. if val > maxValue {
  352. maxValue = val
  353. }
  354. }
  355. return
  356. }
  357. // HczDiv 环差值计算
  358. // @params a float64 上一期值
  359. // @params b float64 固定的环比增加值
  360. func HczDiv(a, b float64) (result float64) {
  361. if b != 0 {
  362. // 上一期值
  363. af := decimal.NewFromFloat(a)
  364. // 固定的环比增加值
  365. bf := decimal.NewFromFloat(b)
  366. // 计算
  367. result, _ = af.Add(bf).RoundCeil(4).Float64()
  368. } else {
  369. result = 0
  370. }
  371. return
  372. }
  373. // GetChartPredictEdbInfoDataListByRuleNMoveMeanValue 根据N期移动均值规则获取预测数据
  374. // 2.5 N期移动均值:在未来某一个时间段内,下一期值等于过去N期值得平均值。
  375. // 例:最近3期值(N=3),为95,98,105则未来第1期值为 1/3*(95+98+105)=99.33, 未来第2期值为 1/3*(98+105+99.33)=100.78依次类推。
  376. func GetChartPredictEdbInfoDataListByRuleNMoveMeanValue(edbInfoId int, nValue int, startDate, endDate time.Time, frequency string, realPredictEdbInfoData, predictEdbInfoData []*models.EdbDataList, existMap map[string]float64) (newPredictEdbInfoData []*models.EdbDataList, minValue, maxValue float64) {
  377. allDataList := make([]*models.EdbDataList, 0)
  378. allDataList = append(allDataList, realPredictEdbInfoData...)
  379. allDataList = append(allDataList, predictEdbInfoData...)
  380. newPredictEdbInfoData = predictEdbInfoData
  381. lenAllData := len(allDataList)
  382. if lenAllData < nValue || lenAllData <= 0 {
  383. return
  384. }
  385. if nValue <= 0 {
  386. return
  387. }
  388. // 分母
  389. decimalN := decimal.NewFromInt(int64(nValue))
  390. //获取后面的预测数据
  391. dayList := getPredictEdbDayList(startDate, endDate, frequency)
  392. for k, currentDate := range dayList {
  393. tmpIndex := lenAllData + k - 1 //上1期的值
  394. // 数据集合中的最后一个数据
  395. tmpDecimalVal := decimal.NewFromFloat(allDataList[tmpIndex].Value)
  396. for tmpK := 2; tmpK <= nValue; tmpK++ {
  397. tmpIndex2 := tmpIndex - tmpK //上N期的值
  398. tmpDecimalVal2 := decimal.NewFromFloat(allDataList[tmpIndex2].Value)
  399. tmpDecimalVal = tmpDecimalVal.Add(tmpDecimalVal2)
  400. }
  401. // N期移动均值计算
  402. val, _ := tmpDecimalVal.Div(decimalN).RoundCeil(4).Float64()
  403. currentDateStr := currentDate.Format(utils.FormatDate)
  404. tmpData := &models.EdbDataList{
  405. EdbDataId: edbInfoId + 10000000000 + lenAllData + k,
  406. EdbInfoId: edbInfoId,
  407. DataTime: currentDateStr,
  408. Value: val,
  409. DataTimestamp: currentDate.UnixNano() / 1e6,
  410. }
  411. newPredictEdbInfoData = append(newPredictEdbInfoData, tmpData)
  412. allDataList = append(allDataList, tmpData)
  413. existMap[currentDateStr] = val
  414. // 最大最小值
  415. if val < minValue {
  416. minValue = val
  417. }
  418. if val > maxValue {
  419. maxValue = val
  420. }
  421. }
  422. return
  423. }
  424. // GetChartPredictEdbInfoDataListByRuleNLinearRegression 根据N期移动均值规则获取预测数据
  425. // 2.6N期段线性外推值:给出过去N期值所确定的线性回归方程(Y=aX+b)在未来一段时间内的推算值。回归方程虽然比较复杂,但各种编程语言应该都有现成的模块或函数,应该无需自己编写。
  426. // 例1:过去5期值(N=5)分别为:3,5,7,9,11(每两期值之间的时间间隔相等)。那么按照线性回归方程推算,未来三期的预测值是:13,15,17。
  427. //
  428. // 例2:过去6期值(N=6)分别为:3,3,5,7,9,11(每两期值之间的时间间隔相等)。那么按照线性回归方程推算,未来三期的预测值是:12.33,14.05,15.76。例1和例2的区别在于,多加了一期数据,导致回归方程发生改变,从而预测值不同。
  429. func GetChartPredictEdbInfoDataListByRuleNLinearRegression(edbInfoId int, nValue int, startDate, endDate time.Time, frequency string, realPredictEdbInfoData, predictEdbInfoData []*models.EdbDataList, existMap map[string]float64) (newPredictEdbInfoData []*models.EdbDataList, minValue, maxValue float64) {
  430. //var errMsg string
  431. //defer func() {
  432. // if errMsg != `` {
  433. // go alarm_msg.SendAlarmMsg("更新上海的token失败;ERR:"+err.Error(), 3)
  434. // }
  435. //}()
  436. allDataList := make([]*models.EdbDataList, 0)
  437. allDataList = append(allDataList, realPredictEdbInfoData...)
  438. allDataList = append(allDataList, predictEdbInfoData...)
  439. newPredictEdbInfoData = predictEdbInfoData
  440. lenAllData := len(allDataList)
  441. if lenAllData < nValue || lenAllData <= 0 {
  442. return
  443. }
  444. if nValue <= 1 {
  445. return
  446. }
  447. //获取后面的预测数据
  448. // 获取线性方程公式的a、b的值
  449. coordinateData := make([]Coordinate, 0)
  450. for tmpK := nValue; tmpK > 0; tmpK-- {
  451. tmpIndex2 := lenAllData - tmpK //上N期的值
  452. tmpCoordinate := Coordinate{
  453. X: float64(nValue - tmpK + 1),
  454. Y: allDataList[tmpIndex2].Value,
  455. }
  456. coordinateData = append(coordinateData, tmpCoordinate)
  457. }
  458. a, b := getLinearResult(coordinateData)
  459. //fmt.Println("a:", a, ";======b:", b)
  460. dayList := getPredictEdbDayList(startDate, endDate, frequency)
  461. for k, currentDate := range dayList {
  462. tmpK := nValue + k + 1
  463. aDecimal := decimal.NewFromFloat(a)
  464. xDecimal := decimal.NewFromInt(int64(tmpK))
  465. bDecimal := decimal.NewFromFloat(b)
  466. val, _ := aDecimal.Mul(xDecimal).Add(bDecimal).RoundCeil(4).Float64()
  467. currentDateStr := currentDate.Format(utils.FormatDate)
  468. tmpData := &models.EdbDataList{
  469. EdbDataId: edbInfoId + 10000000000 + lenAllData + k,
  470. EdbInfoId: edbInfoId,
  471. DataTime: currentDateStr,
  472. Value: val,
  473. DataTimestamp: currentDate.UnixNano() / 1e6,
  474. }
  475. newPredictEdbInfoData = append(newPredictEdbInfoData, tmpData)
  476. allDataList = append(allDataList, tmpData)
  477. existMap[currentDateStr] = val
  478. // 最大最小值
  479. if val < minValue {
  480. minValue = val
  481. }
  482. if val > maxValue {
  483. maxValue = val
  484. }
  485. }
  486. return
  487. }
  488. // Series is a container for a series of data
  489. type Series []Coordinate
  490. // Coordinate holds the data in a series
  491. type Coordinate struct {
  492. X, Y float64
  493. }
  494. func getLinearResult(s []Coordinate) (gradient, intercept float64) {
  495. if len(s) <= 1 {
  496. return
  497. }
  498. // Placeholder for the math to be done
  499. var sum [5]float64
  500. // Loop over data keeping index in place
  501. i := 0
  502. for ; i < len(s); i++ {
  503. sum[0] += s[i].X
  504. sum[1] += s[i].Y
  505. sum[2] += s[i].X * s[i].X
  506. sum[3] += s[i].X * s[i].Y
  507. sum[4] += s[i].Y * s[i].Y
  508. }
  509. // Find gradient and intercept
  510. f := float64(i)
  511. gradient = (f*sum[3] - sum[0]*sum[1]) / (f*sum[2] - sum[0]*sum[0])
  512. intercept = (sum[1] / f) - (gradient * sum[0] / f)
  513. //fmt.Println("gradient:", gradient, ";intercept:", intercept)
  514. // Create the new regression series
  515. //for j := 0; j < len(s); j++ {
  516. // regressions = append(regressions, Coordinate{
  517. // X: s[j].X,
  518. // Y: s[j].X*gradient + intercept,
  519. // })
  520. //}
  521. return
  522. }
  523. // GetChartPredictEdbInfoDataListByRuleTrendsHC 根据动态环比增加值的计算规则获取预测数据
  524. //
  525. // 研究员有对预测指标进行动态环差计算的需求,即预测指标使用环差规则进行预测时,环比增加值不是固定值,而是由几个预测指标计算得出的动态变化的值;
  526. // 需求说明:
  527. // 1、增加“动态环差”预测规则;
  528. // 2、环比增加值在弹窗设置;
  529. // 3、动态环差预测举例:
  530. // 指标A实际最新数据为2022-10-27(100);
  531. // 预测指标B预测数据为2022-10-28(240)、2022-10-29(300);
  532. // 预测指标C预测数据为2022-10-28(260)、2022-10-29(310);
  533. // 计算公式为B-C;
  534. // 则指标A至2022-10-29的预测值为2022-10-28(100+(240-260)=80)、2022-10-29(80+(300-310)=90);
  535. // 注:动态环比增加值的计算遵从计算指标的计算规则,即用于计算的指标若有部分指标缺少部分日期数据,则这部分日期数据不做计算,为空;若动态环比增加值某一天为空,则往前追溯最近一期有值的环比增加值作为该天的数值参与计算;
  536. func GetChartPredictEdbInfoDataListByRuleTrendsHC(edbInfoId, configId int, startDate, endDate time.Time, frequency string, realPredictEdbInfoData, predictEdbInfoData []*models.EdbDataList, existMap map[string]float64) (newPredictEdbInfoData []*models.EdbDataList, minValue, maxValue float64) {
  537. allDataList := make([]*models.EdbDataList, 0)
  538. allDataList = append(allDataList, realPredictEdbInfoData...)
  539. allDataList = append(allDataList, predictEdbInfoData...)
  540. newPredictEdbInfoData = predictEdbInfoData
  541. lenAllData := len(allDataList)
  542. if lenAllData <= 0 {
  543. return
  544. }
  545. hcDataMap := make(map[string]float64) //规则计算的环差值map
  546. //已经生成的动态数据
  547. tmpPredictEdbRuleDataList, err := data_manage.GetPredictEdbRuleDataList(edbInfoId, configId, startDate.Format(utils.FormatDate), endDate.Format(utils.FormatDate))
  548. if err != nil {
  549. return
  550. }
  551. for _, v := range tmpPredictEdbRuleDataList {
  552. hcDataMap[v.DataTime] = v.Value
  553. }
  554. dayList := getPredictEdbDayList(startDate, endDate, frequency)
  555. for k, currentDate := range dayList {
  556. // 最近一条数据
  557. tmpLenAllDataList := len(allDataList)
  558. lastValue := allDataList[tmpLenAllDataList-1].Value
  559. // 动态环差值数据
  560. currentDateStr := currentDate.Format(utils.FormatDate)
  561. hcVal, ok := hcDataMap[currentDateStr]
  562. if !ok {
  563. continue
  564. }
  565. lastValueDecimal := decimal.NewFromFloat(lastValue)
  566. hcValDecimal := decimal.NewFromFloat(hcVal)
  567. val, _ := lastValueDecimal.Add(hcValDecimal).RoundCeil(4).Float64()
  568. tmpData := &models.EdbDataList{
  569. EdbDataId: edbInfoId + 10000000000 + lenAllData + k,
  570. EdbInfoId: edbInfoId,
  571. DataTime: currentDateStr,
  572. Value: val,
  573. DataTimestamp: currentDate.UnixNano() / 1e6,
  574. }
  575. newPredictEdbInfoData = append(newPredictEdbInfoData, tmpData)
  576. allDataList = append(allDataList, tmpData)
  577. existMap[currentDateStr] = val
  578. // 最大最小值
  579. if val < minValue {
  580. minValue = val
  581. }
  582. if val > maxValue {
  583. maxValue = val
  584. }
  585. }
  586. return
  587. }
  588. // GetChartPredictEdbInfoDataListByRuleFinalValueHc 根据 给定终值后插值 规则获取预测数据
  589. //
  590. // 项目背景:
  591. // 假设螺纹产量在2023年1月1号的预测值是255万吨,从当下到2023年1月1号,螺纹产量将会线性变化,那么每一期的螺纹产量是多少?
  592. // 算法:从当下(2022/10/28)到2023/1/1号,一共65天,从当前值(305.02)到255,差值-50.02,
  593. // 则每日环差为-50.02/65=-0.7695。因为数据点是周度频率,每周环差为,-0.3849*7=-5.3868。
  594. // 从以上计算过程可看出,“给定终值后差值”的算法,是在“环差”算法的基础上,做的一个改动。即这个”环差值”=【(终值-最新值)/终值与最新值得日期差】*数据频率
  595. // 需求说明:
  596. // 1、增加一个预测规则,名为“给定终值后插值”,给定预测截止日期和预测终值,计算最新数据日期至预测截止日期的时间差T,计算最新数据和预测终值的数据差S,数据频率与指标频度有关,日度=1,周度=7,旬度=10,月度=30,季度=90,年度=365,环差值=S/T*频率,预测数值=前一天数值+环差值;
  597. // 2、最新数据值和日期改动后,需重新计算环差值和预测数值;
  598. func GetChartPredictEdbInfoDataListByRuleFinalValueHc(edbInfoId int, finalValue float64, startDate, endDate time.Time, frequency string, realPredictEdbInfoData, predictEdbInfoData []*models.EdbDataList, existMap map[string]float64) (newPredictEdbInfoData []*models.EdbDataList, minValue, maxValue float64) {
  599. allDataList := make([]*models.EdbDataList, 0)
  600. allDataList = append(allDataList, realPredictEdbInfoData...)
  601. allDataList = append(allDataList, predictEdbInfoData...)
  602. newPredictEdbInfoData = predictEdbInfoData
  603. index := len(allDataList)
  604. //获取后面的预测日期
  605. dayList := getPredictEdbDayList(startDate, endDate, frequency)
  606. lenDay := len(dayList)
  607. if lenDay <= 0 {
  608. return
  609. }
  610. var hcValue float64
  611. lastValueDeciamal := decimal.NewFromFloat(allDataList[index-1].Value) // 实际数据的最后一个值
  612. finalValueDeciamal := decimal.NewFromFloat(finalValue) // 给定的终止数据
  613. dayDecimal := decimal.NewFromInt(int64(lenDay)) // 需要作为分母的期数
  614. hcValue, _ = finalValueDeciamal.Sub(lastValueDeciamal).Div(dayDecimal).Float64() // 计算出来的环差值
  615. //获取后面的预测数据
  616. predictEdbInfoData = make([]*models.EdbDataList, 0)
  617. lastK := lenDay - 1 // 最后的日期
  618. for k, currentDate := range dayList {
  619. tmpK := index + k - 1 //上1期的值
  620. var val float64
  621. // 环差别值计算
  622. if k == lastK { //如果是最后一天,那么就用最终值,否则就计算
  623. val = finalValue
  624. } else {
  625. val = HczDiv(allDataList[tmpK].Value, hcValue)
  626. }
  627. currentDateStr := currentDate.Format(utils.FormatDate)
  628. tmpData := &models.EdbDataList{
  629. EdbDataId: edbInfoId + 10000000000 + index + k,
  630. EdbInfoId: edbInfoId,
  631. DataTime: currentDateStr,
  632. Value: val,
  633. DataTimestamp: currentDate.UnixNano() / 1e6,
  634. }
  635. newPredictEdbInfoData = append(newPredictEdbInfoData, tmpData)
  636. allDataList = append(allDataList, tmpData)
  637. existMap[currentDateStr] = val
  638. // 最大最小值
  639. if val < minValue {
  640. minValue = val
  641. }
  642. if val > maxValue {
  643. maxValue = val
  644. }
  645. }
  646. return
  647. }
  648. // SeasonConf 季节性规则的配置
  649. type SeasonConf struct {
  650. Calendar string `description:"公历、农历"`
  651. YearType int `description:"选择方式,1:连续N年;2:指定年份"`
  652. NValue int `description:"连续N年"`
  653. YearList []int `description:"指定年份列表"`
  654. }
  655. // GetChartPredictEdbInfoDataListByRuleSeason 根据 季节性 规则获取预测数据
  656. //
  657. // ETA预测规则:季节性
  658. // 已知选定指标A最近更新日期: 2022-12-6 200
  659. // 设置预测截止日期2023-01-06
  660. // 1、选择过去N年,N=3
  661. // 则过去N年为2021、2020、2019
  662. // 指标A日期 实际值 指标A日期
  663. // 2019/12/5 150 2019/12/6
  664. // 2020/12/5 180 2020/12/6
  665. // 2021/12/5 210 2021/12/6
  666. // 2019/12/31 200 2020/1/1
  667. // 2020/12/31 210 2021/1/1
  668. // 2021/12/31 250 2022/1/1
  669. //
  670. // 计算12.7预测值,求过去N年环差均值=[(100-150)+(160-180)+(250-210)]/3=-10
  671. // 则12.7预测值=12.6值+过去N年环差均值=200-10=190
  672. // 以此类推...
  673. //
  674. // 计算2023.1.2预测值,求过去N年环差均值=[(300-200)+(220-210)+(260-250)]/3=40
  675. // 则2023.1.2预测值=2023.1.1值+过去N年环差均值
  676. func GetChartPredictEdbInfoDataListByRuleSeason(edbInfoId int, yearsList []int, calendar string, startDate, endDate time.Time, frequency string, realPredictEdbInfoData, predictEdbInfoData []*models.EdbDataList, existMap map[string]float64) (newPredictEdbInfoData []*models.EdbDataList, minValue, maxValue float64, err error) {
  677. allDataList := make([]*models.EdbDataList, 0)
  678. allDataList = append(allDataList, realPredictEdbInfoData...)
  679. allDataList = append(allDataList, predictEdbInfoData...)
  680. newPredictEdbInfoData = predictEdbInfoData
  681. // 插值法数据处理
  682. handleDataMap := make(map[string]float64)
  683. err = HandleDataByLinearRegression(allDataList, handleDataMap)
  684. if err != nil {
  685. return
  686. }
  687. // 获取每个年份的日期数据需要平移的天数
  688. moveDayMap := make(map[int]int, 0) // 每个年份的春节公历
  689. {
  690. if calendar == "公历" {
  691. for _, year := range yearsList {
  692. moveDayMap[year] = 0 //公历就不平移了
  693. }
  694. } else {
  695. currentDay := time.Now()
  696. if currentDay.Month() >= 11 { //如果大于等于11月份,那么用的是下一年的春节
  697. currentDay = currentDay.AddDate(1, 0, 0)
  698. }
  699. currentYear := currentDay.Year()
  700. currentYearCjnl := fmt.Sprintf("%d-01-01", currentYear) //当年的春节农历
  701. currentYearCjgl := solarlunar.LunarToSolar(currentYearCjnl, false) //当年的春节公历
  702. currentYearCjglTime, tmpErr := time.ParseInLocation(utils.FormatDate, currentYearCjgl, time.Local)
  703. if tmpErr != nil {
  704. err = errors.New("当前春节公历日期转换失败:" + tmpErr.Error())
  705. return
  706. }
  707. // 指定的年份
  708. for _, year := range yearsList {
  709. tmpYearCjnl := fmt.Sprintf("%d-01-01", year) //指定年的春节农历
  710. tmpYearCjgl := solarlunar.LunarToSolar(tmpYearCjnl, false) //指定年的春节公历
  711. //moveDayList = append(moveDayList, 0) //公历就不平移了
  712. tmpYearCjglTime, tmpErr := time.ParseInLocation(utils.FormatDate, tmpYearCjgl, time.Local)
  713. if tmpErr != nil {
  714. err = errors.New(fmt.Sprintf("%d公历日期转换失败:%s", year, tmpErr.Error()))
  715. return
  716. }
  717. tmpCurrentYearCjglTime := currentYearCjglTime.AddDate(year-currentYear, 0, 0)
  718. moveDay := utils.GetTimeSubDay(tmpYearCjglTime, tmpCurrentYearCjglTime)
  719. moveDayMap[year] = moveDay //公历平移
  720. }
  721. }
  722. }
  723. index := len(allDataList)
  724. //获取后面的预测日期
  725. dayList := getPredictEdbDayList(startDate, endDate, frequency)
  726. //获取后面的预测数据
  727. predictEdbInfoData = make([]*models.EdbDataList, 0)
  728. for k, currentDate := range dayList {
  729. // 如果遇到闰二月,如2.29,去掉该天数据
  730. if strings.Contains(currentDate.Format(utils.FormatDate), "02-29") {
  731. continue
  732. }
  733. tmpHistoryVal := decimal.NewFromFloat(0) //往期的差值总和
  734. tmpHistoryValNum := 0 // 往期差值计算的数量
  735. tmpLenAllDataList := len(allDataList)
  736. tmpK := tmpLenAllDataList - 1 //上1期数据的下标
  737. lastDayData := allDataList[tmpK] // 上1期的数据
  738. lastDayStr := lastDayData.DataTime
  739. lastDayVal := lastDayData.Value
  740. lastDay, tmpErr := time.ParseInLocation(utils.FormatDate, lastDayStr, time.Local)
  741. if tmpErr != nil {
  742. err = errors.New("获取上期日期转换失败:" + tmpErr.Error())
  743. }
  744. for _, year := range yearsList {
  745. moveDay := moveDayMap[year] //需要移动的天数
  746. var tmpHistoryCurrentVal, tmpHistoryLastVal float64
  747. var isFindHistoryCurrent, isFindHistoryLast bool //是否找到前几年的数据
  748. //前几年当日的日期
  749. tmpHistoryCurrentDate := currentDate.AddDate(year-currentDate.Year(), 0, -moveDay)
  750. for i := 0; i <= 35; i++ { // 前后35天找数据,找到最近的值,先向后面找,再往前面找
  751. tmpDate := tmpHistoryCurrentDate.AddDate(0, 0, i)
  752. if val, ok := handleDataMap[tmpDate.Format(utils.FormatDate)]; ok {
  753. tmpHistoryCurrentVal = val
  754. isFindHistoryCurrent = true
  755. break
  756. } else {
  757. tmpDate := tmpHistoryCurrentDate.AddDate(0, 0, -i)
  758. if val, ok := handleDataMap[tmpDate.Format(utils.FormatDate)]; ok {
  759. tmpHistoryCurrentVal = val
  760. isFindHistoryCurrent = true
  761. break
  762. }
  763. }
  764. }
  765. //前几年上一期的日期
  766. tmpHistoryLastDate := lastDay.AddDate(year-lastDay.Year(), 0, -moveDay)
  767. for i := 0; i <= 35; i++ { // 前后35天找数据,找到最近的值,先向后面找,再往前面找
  768. tmpDate := tmpHistoryLastDate.AddDate(0, 0, i)
  769. if val, ok := handleDataMap[tmpDate.Format(utils.FormatDate)]; ok {
  770. tmpHistoryLastVal = val
  771. isFindHistoryLast = true
  772. break
  773. } else {
  774. tmpDate := tmpHistoryLastDate.AddDate(0, 0, -i)
  775. if val, ok := handleDataMap[tmpDate.Format(utils.FormatDate)]; ok {
  776. tmpHistoryLastVal = val
  777. isFindHistoryLast = true
  778. break
  779. }
  780. }
  781. }
  782. // 如果两个日期对应的数据都找到了,那么计算两期的差值
  783. if isFindHistoryCurrent && isFindHistoryLast {
  784. af := decimal.NewFromFloat(tmpHistoryCurrentVal)
  785. bf := decimal.NewFromFloat(tmpHistoryLastVal)
  786. tmpHistoryVal = tmpHistoryVal.Add(af.Sub(bf))
  787. tmpHistoryValNum++
  788. }
  789. }
  790. //计算的差值与选择的年份数量不一致,那么当前日期不计算
  791. if tmpHistoryValNum != len(yearsList) {
  792. continue
  793. }
  794. lastDayValDec := decimal.NewFromFloat(lastDayVal)
  795. val, _ := tmpHistoryVal.Div(decimal.NewFromInt(int64(tmpHistoryValNum))).Add(lastDayValDec).RoundCeil(4).Float64()
  796. currentDateStr := currentDate.Format(utils.FormatDate)
  797. tmpData := &models.EdbDataList{
  798. EdbDataId: edbInfoId + 10000000000 + index + k,
  799. EdbInfoId: edbInfoId,
  800. DataTime: currentDateStr,
  801. Value: val,
  802. DataTimestamp: currentDate.UnixNano() / 1e6,
  803. }
  804. newPredictEdbInfoData = append(newPredictEdbInfoData, tmpData)
  805. allDataList = append(allDataList, tmpData)
  806. existMap[currentDateStr] = val
  807. // 继续使用插值法补充新预测日期的数据之间的值
  808. err = HandleDataByLinearRegression([]*models.EdbDataList{
  809. lastDayData, tmpData,
  810. }, handleDataMap)
  811. if err != nil {
  812. return
  813. }
  814. // 最大最小值
  815. if val < minValue {
  816. minValue = val
  817. }
  818. if val > maxValue {
  819. maxValue = val
  820. }
  821. }
  822. return
  823. }
  824. // MoveAverageConf 移动平均同比规则的配置
  825. type MoveAverageConf struct {
  826. Year int `description:"指定年份"`
  827. NValue int `description:"N期的数据"`
  828. }
  829. // GetChartPredictEdbInfoDataListByRuleMoveAverageTb 根据 移动平均同比 规则获取预测数据
  830. //
  831. // ETA预测规则:季节性
  832. // 2、选择指定N年,N=3
  833. // 指定N年为2012、2015、2018
  834. // 指标A日期 实际值 指标A日期 实际值
  835. // 2012/12/5 150 2012/12/6 130
  836. // 2015/12/5 180 2015/12/6 150
  837. // 2018/12/5 210 2018/12/6 260
  838. // 2012/12/31 200 2013/1/1 200
  839. // 2015/12/31 210 2016/1/1 250
  840. // 2018/12/31 250 2019/1/1 270
  841. // 计算12.7预测值,求过去N年环差均值=[(130-150)+(150-180)+(290-210)]/3=10
  842. // 则12.7预测值=12.6值+过去N年环差均值=200+10=210
  843. // 以此类推...
  844. // 计算2023.1.2预测值,求过去N年环差均值=[(200-200)+(250-210)+(270-250)]/3=16.67
  845. // 则2023.1.2预测值=2023.1.1值+过去N年环差均值
  846. func GetChartPredictEdbInfoDataListByRuleMoveAverageTb(edbInfoId int, nValue, year int, startDate, endDate time.Time, frequency string, realPredictEdbInfoData, predictEdbInfoData []*models.EdbDataList, existMap map[string]float64) (newPredictEdbInfoData []*models.EdbDataList, minValue, maxValue float64, err error) {
  847. allDataList := make([]*models.EdbDataList, 0)
  848. allDataList = append(allDataList, realPredictEdbInfoData...)
  849. allDataList = append(allDataList, predictEdbInfoData...)
  850. newPredictEdbInfoData = predictEdbInfoData
  851. lenAllData := len(allDataList)
  852. if lenAllData < nValue || lenAllData <= 0 {
  853. return
  854. }
  855. if nValue <= 0 {
  856. return
  857. }
  858. // 分母
  859. decimalN := decimal.NewFromInt(int64(nValue))
  860. //获取后面的预测数据
  861. dayList := getPredictEdbDayList(startDate, endDate, frequency)
  862. if len(dayList) <= 0 {
  863. return
  864. }
  865. // 需要减去的年份
  866. subYear := year - dayList[0].Year()
  867. for k, currentDate := range dayList {
  868. tmpLenAllDataList := len(allDataList)
  869. tmpIndex := tmpLenAllDataList - 1 //上1期数据的下标
  870. averageDateList := make([]string, 0) //计算平均数的日期
  871. // 数据集合中的最后一个数据
  872. tmpDecimalVal := decimal.NewFromFloat(allDataList[tmpIndex].Value)
  873. averageDateList = append(averageDateList, allDataList[tmpIndex].DataTime)
  874. for tmpK := 1; tmpK < nValue; tmpK++ {
  875. tmpIndex2 := tmpIndex - tmpK //上N期的值
  876. tmpDecimalVal2 := decimal.NewFromFloat(allDataList[tmpIndex2].Value)
  877. tmpDecimalVal = tmpDecimalVal.Add(tmpDecimalVal2)
  878. averageDateList = append(averageDateList, allDataList[tmpIndex2].DataTime)
  879. }
  880. // 最近的N期平均值
  881. tmpAverageVal := tmpDecimalVal.Div(decimalN)
  882. var tmpHistoryCurrentVal float64 // 前几年当日的数据值
  883. var isFindHistoryCurrent, isFindHistoryLast bool //是否找到前几年的数据
  884. tmpHistoryDecimalVal := decimal.NewFromFloat(0) //前几年N期数据总值
  885. {
  886. // 前几年N期汇总期数
  887. tmpHistoryValNum := 0
  888. {
  889. //前几年当日的日期
  890. tmpHistoryCurrentDate := currentDate.AddDate(subYear, 0, 0)
  891. for i := 0; i <= 35; i++ { // 前后35天找数据,找到最近的值,先向后面找,再往前面找
  892. tmpDate := tmpHistoryCurrentDate.AddDate(0, 0, i)
  893. if val, ok := existMap[tmpDate.Format(utils.FormatDate)]; ok {
  894. tmpHistoryCurrentVal = val
  895. isFindHistoryCurrent = true
  896. break
  897. } else {
  898. tmpDate := tmpHistoryCurrentDate.AddDate(0, 0, -i)
  899. if val, ok := existMap[tmpDate.Format(utils.FormatDate)]; ok {
  900. tmpHistoryCurrentVal = val
  901. isFindHistoryCurrent = true
  902. break
  903. }
  904. }
  905. }
  906. }
  907. for _, averageDate := range averageDateList {
  908. lastDay, tmpErr := time.ParseInLocation(utils.FormatDate, averageDate, time.Local)
  909. if tmpErr != nil {
  910. err = tmpErr
  911. return
  912. }
  913. //前几年上一期的日期
  914. tmpHistoryLastDate := lastDay.AddDate(subYear, 0, 0)
  915. for i := 0; i <= 35; i++ { // 前后35天找数据,找到最近的值,先向后面找,再往前面找
  916. tmpDate := tmpHistoryLastDate.AddDate(0, 0, i)
  917. if val, ok := existMap[tmpDate.Format(utils.FormatDate)]; ok {
  918. tmpDecimalVal2 := decimal.NewFromFloat(val)
  919. tmpHistoryDecimalVal = tmpHistoryDecimalVal.Add(tmpDecimalVal2)
  920. tmpHistoryValNum++
  921. break
  922. } else {
  923. tmpDate := tmpHistoryLastDate.AddDate(0, 0, -i)
  924. if val, ok := existMap[tmpDate.Format(utils.FormatDate)]; ok {
  925. tmpDecimalVal2 := decimal.NewFromFloat(val)
  926. tmpHistoryDecimalVal = tmpHistoryDecimalVal.Add(tmpDecimalVal2)
  927. tmpHistoryValNum++
  928. break
  929. }
  930. }
  931. }
  932. }
  933. // 汇总期数与配置的N期数量一致
  934. if tmpHistoryValNum == nValue {
  935. isFindHistoryLast = true
  936. }
  937. }
  938. // 如果没有找到前几年的汇总数据,或者没有找到前几年当日的数据,那么退出当前循环,进入下一循环
  939. if !isFindHistoryLast || !isFindHistoryCurrent {
  940. continue
  941. }
  942. // 计算最近N期平均值
  943. tmpHistoryAverageVal := tmpHistoryDecimalVal.Div(decimalN)
  944. // 计算最近N期同比值
  945. tbVal := tmpAverageVal.Div(tmpHistoryAverageVal)
  946. // 预测值结果 = 同比年份同期值(tmpHistoryCurrentVal的值)* 同比值(tbVal的值)
  947. val, _ := decimal.NewFromFloat(tmpHistoryCurrentVal).Mul(tbVal).RoundCeil(4).Float64()
  948. currentDateStr := currentDate.Format(utils.FormatDate)
  949. tmpData := &models.EdbDataList{
  950. EdbDataId: edbInfoId + 10000000000 + lenAllData + k,
  951. EdbInfoId: edbInfoId,
  952. DataTime: currentDateStr,
  953. Value: val,
  954. DataTimestamp: currentDate.UnixNano() / 1e6,
  955. }
  956. newPredictEdbInfoData = append(newPredictEdbInfoData, tmpData)
  957. allDataList = append(allDataList, tmpData)
  958. existMap[currentDateStr] = val
  959. // 最大最小值
  960. if val < minValue {
  961. minValue = val
  962. }
  963. if val > maxValue {
  964. maxValue = val
  965. }
  966. }
  967. return
  968. }
  969. // GetChartPredictEdbInfoDataListByRuleTbzscz 根据 同比增速差值 规则获取预测数据
  970. // 同比增速差值计算方式:
  971. // 1、首先计算出所选指标实际最新日期值的同比增速:(本期数值-同期数值)÷同期数值*100%
  972. // 2、根据预测截止日期的同比增速终值、最新日期值的同比增速、与最新日期距离截止日期的期数,计算出到截止日期为止的每一期的同比增速。(等差规则计算每一期的同比增速,结合去年同期值,计算出每一期的同比预测值)。公差=(末项-首项)÷(n-1),an=a1+(n-1)d,(n为正整数,n大于等于2)
  973. // 3、根据去年同期值和未来每一期的同比增速值,求出同比预测值,同比预测值=同期值*(1+同比增速)
  974. // 同比增速差值:计算最新数据的同比增速((本期数值-同期数值)÷同期数值*100%),结合同比增速终值与期数,计算每一期同比增速,进而求出同比预测值。
  975. //
  976. // 例:如上图所示指标,(1)最新日期值2022-12-31 141175 ,结合同期值,计算同比增速;
  977. // (2)同比增速终值,若为50%, 预测日期为2023-03-31,则根据(1)中的同比增速值与同比增速终值,计算出中间两期的同比增速;
  978. // (3)求出每一期的预测同比值,预测同比值=同期值*(1+同比增速)
  979. func GetChartPredictEdbInfoDataListByRuleTbzscz(edbInfoId int, tbEndValue float64, dayList []time.Time, frequency string, realPredictEdbInfoData, predictEdbInfoData []*models.EdbDataList, existMap map[string]float64) (newPredictEdbInfoData []*models.EdbDataList, minValue, maxValue float64) {
  980. allDataList := make([]*models.EdbDataList, 0)
  981. allDataList = append(allDataList, realPredictEdbInfoData...)
  982. allDataList = append(allDataList, predictEdbInfoData...)
  983. newPredictEdbInfoData = predictEdbInfoData
  984. index := len(allDataList)
  985. // 获取近期数据的同比值
  986. if index <= 0 {
  987. return
  988. }
  989. lastData := allDataList[index-1]
  990. lastDayTime, _ := time.ParseInLocation(utils.FormatDate, lastData.DataTime, time.Local)
  991. var lastTb decimal.Decimal // 计算最新数据与上一期的数据同比值
  992. {
  993. //上一年的日期
  994. preDate := lastDayTime.AddDate(-1, 0, 0)
  995. preDateStr := preDate.Format(utils.FormatDate)
  996. if preValue, ok := existMap[preDateStr]; ok { //上一年同期找到
  997. lastTb = (decimal.NewFromFloat(lastData.Value)).Sub(decimal.NewFromFloat(preValue)).Div(decimal.NewFromFloat(preValue))
  998. } else {
  999. switch frequency {
  1000. case "月度":
  1001. //向上和向下,各找一个月
  1002. nextDateDay := preDate
  1003. preDateDay := preDate
  1004. for i := 0; i <= 35; i++ {
  1005. nextDateDayStr := nextDateDay.Format(utils.FormatDate)
  1006. if preValue, ok := existMap[nextDateDayStr]; ok { //上一年同期->下一个月找到
  1007. lastTb = (decimal.NewFromFloat(lastData.Value)).Sub(decimal.NewFromFloat(preValue)).Div(decimal.NewFromFloat(preValue))
  1008. break
  1009. } else {
  1010. preDateDayStr := preDateDay.Format(utils.FormatDate)
  1011. if preValue, ok := existMap[preDateDayStr]; ok { //上一年同期->上一个月找到
  1012. lastTb = (decimal.NewFromFloat(lastData.Value)).Sub(decimal.NewFromFloat(preValue)).Div(decimal.NewFromFloat(preValue))
  1013. break
  1014. }
  1015. }
  1016. nextDateDay = nextDateDay.AddDate(0, 0, 1)
  1017. preDateDay = preDateDay.AddDate(0, 0, -1)
  1018. }
  1019. case "季度", "年度":
  1020. if preValue, ok := existMap[preDateStr]; ok { //上一年同期->下一个月找到
  1021. lastTb = (decimal.NewFromFloat(lastData.Value)).Sub(decimal.NewFromFloat(preValue)).Div(decimal.NewFromFloat(preValue))
  1022. break
  1023. }
  1024. default:
  1025. nextDateDay := preDate
  1026. preDateDay := preDate
  1027. for i := 0; i < 35; i++ {
  1028. nextDateDayStr := nextDateDay.Format(utils.FormatDate)
  1029. if preValue, ok := existMap[nextDateDayStr]; ok { //上一年同期->下一个月找到
  1030. lastTb = (decimal.NewFromFloat(lastData.Value)).Sub(decimal.NewFromFloat(preValue)).Div(decimal.NewFromFloat(preValue))
  1031. break
  1032. } else {
  1033. preDateDayStr := preDateDay.Format(utils.FormatDate)
  1034. if preValue, ok := existMap[preDateDayStr]; ok { //上一年同期->上一个月找到
  1035. lastTb = (decimal.NewFromFloat(lastData.Value)).Sub(decimal.NewFromFloat(preValue)).Div(decimal.NewFromFloat(preValue))
  1036. break
  1037. } else {
  1038. //fmt.Println("pre not find:", preDateStr, "i:", i)
  1039. }
  1040. }
  1041. nextDateDay = nextDateDay.AddDate(0, 0, 1)
  1042. preDateDay = preDateDay.AddDate(0, 0, -1)
  1043. }
  1044. }
  1045. }
  1046. }
  1047. //获取后面的预测数据
  1048. lenDay := len(dayList)
  1049. tbEndValueDecimal := decimal.NewFromFloat(tbEndValue)
  1050. avgTbVal := tbEndValueDecimal.Sub(lastTb).Div(decimal.NewFromInt(int64(lenDay)))
  1051. predictEdbInfoData = make([]*models.EdbDataList, 0)
  1052. for k, currentDate := range dayList {
  1053. var tbValue decimal.Decimal
  1054. if k == lenDay-1 { // 如果是最后的日期了,那么就用终值去计算
  1055. tbValue = tbEndValueDecimal.Add(decimal.NewFromInt(1))
  1056. } else { // 最近数据的同比值 + (平均增值乘以当前期数)
  1057. tbValue = lastTb.Add(avgTbVal.Mul(decimal.NewFromInt(int64(k + 1)))).Add(decimal.NewFromInt(1))
  1058. }
  1059. tmpData := &models.EdbDataList{
  1060. EdbDataId: edbInfoId + 100000 + index + k,
  1061. EdbInfoId: edbInfoId,
  1062. DataTime: currentDate.Format(utils.FormatDate),
  1063. //Value: dataValue,
  1064. DataTimestamp: currentDate.UnixNano() / 1e6,
  1065. }
  1066. var val float64
  1067. var calculateStatus bool //计算结果
  1068. //currentItem := existMap[av]
  1069. //上一年的日期
  1070. preDate := currentDate.AddDate(-1, 0, 0)
  1071. preDateStr := preDate.Format(utils.FormatDate)
  1072. if preValue, ok := existMap[preDateStr]; ok { //上一年同期找到
  1073. val, _ = decimal.NewFromFloat(preValue).Mul(tbValue).RoundCeil(4).Float64()
  1074. calculateStatus = true
  1075. } else {
  1076. switch frequency {
  1077. case "月度":
  1078. //向上和向下,各找一个月
  1079. nextDateDay := preDate
  1080. preDateDay := preDate
  1081. for i := 0; i <= 35; i++ {
  1082. nextDateDayStr := nextDateDay.Format(utils.FormatDate)
  1083. if preValue, ok := existMap[nextDateDayStr]; ok { //上一年同期->下一个月找到
  1084. val, _ = decimal.NewFromFloat(preValue).Mul(tbValue).RoundCeil(4).Float64()
  1085. calculateStatus = true
  1086. break
  1087. } else {
  1088. preDateDayStr := preDateDay.Format(utils.FormatDate)
  1089. if preValue, ok := existMap[preDateDayStr]; ok { //上一年同期->上一个月找到
  1090. val, _ = decimal.NewFromFloat(preValue).Mul(tbValue).RoundCeil(4).Float64()
  1091. calculateStatus = true
  1092. break
  1093. }
  1094. }
  1095. nextDateDay = nextDateDay.AddDate(0, 0, 1)
  1096. preDateDay = preDateDay.AddDate(0, 0, -1)
  1097. }
  1098. case "季度", "年度":
  1099. if preValue, ok := existMap[preDateStr]; ok { //上一年同期->下一个月找到
  1100. val, _ = decimal.NewFromFloat(preValue).Mul(tbValue).RoundCeil(4).Float64()
  1101. calculateStatus = true
  1102. break
  1103. }
  1104. default:
  1105. nextDateDay := preDate
  1106. preDateDay := preDate
  1107. for i := 0; i < 35; i++ {
  1108. nextDateDayStr := nextDateDay.Format(utils.FormatDate)
  1109. if preValue, ok := existMap[nextDateDayStr]; ok { //上一年同期->下一个月找到
  1110. val, _ = decimal.NewFromFloat(preValue).Mul(tbValue).RoundCeil(4).Float64()
  1111. calculateStatus = true
  1112. break
  1113. } else {
  1114. preDateDayStr := preDateDay.Format(utils.FormatDate)
  1115. if preValue, ok := existMap[preDateDayStr]; ok { //上一年同期->上一个月找到
  1116. val, _ = decimal.NewFromFloat(preValue).Mul(tbValue).RoundCeil(4).Float64()
  1117. calculateStatus = true
  1118. break
  1119. } else {
  1120. //fmt.Println("pre not find:", preDateStr, "i:", i)
  1121. }
  1122. }
  1123. nextDateDay = nextDateDay.AddDate(0, 0, 1)
  1124. preDateDay = preDateDay.AddDate(0, 0, -1)
  1125. }
  1126. }
  1127. }
  1128. if calculateStatus {
  1129. tmpData.Value = val
  1130. newPredictEdbInfoData = append(newPredictEdbInfoData, tmpData)
  1131. allDataList = append(allDataList, tmpData)
  1132. existMap[tmpData.DataTime] = val
  1133. // 最大最小值
  1134. if val < minValue {
  1135. minValue = val
  1136. }
  1137. if val > maxValue {
  1138. maxValue = val
  1139. }
  1140. }
  1141. }
  1142. return
  1143. }
  1144. // RuleLineNhConf 一元线性拟合规则的配置
  1145. type RuleLineNhConf struct {
  1146. StartDate string `description:"开始日期"`
  1147. EndDate string `description:"结束日期"`
  1148. MoveDay int `description:"移动天数"`
  1149. EdbInfoId int `description:"指标id"`
  1150. }
  1151. // GetChartPredictEdbInfoDataListByRuleLineNh 根据 一元线性拟合 的计算规则获取预测数据
  1152. //
  1153. // 选择被预测的指标B(作为自变量,非预测指标),选择指标A(作为因变量,可以是基础指标和预测指标)
  1154. // 2、选择拟合时间段,起始日期至今或指定时间段,选择至今,在计算时截止到指标B的最新日期
  1155. // 3、设定A领先B时间(天),正整数、负整数、0
  1156. // 4、调用拟合残差的数据预处理和算法,给出拟合方程Y=aX+b的系数a,b
  1157. // 5、指标A代入拟合方程得到拟合预测指标B',拟合预测指标使用指标B的频度,在指标B的实际值后面连接拟合预测指标B'对应日期的预测值
  1158. //
  1159. // 注:选择预测截止日期,若所选日期 ≤ 指标A设置领先后的日期序列,则预测指标日期最新日期有值(在指标B'的有值范围内);若所选日期 > 指标A设置领先后的日期序列,则预测指标只到指标A领先后的日期序列(超出指标B'的有值范围,最多到指标B'的最新值);指标A、B更新后,更新预测指标
  1160. func GetChartPredictEdbInfoDataListByRuleLineNh(edbInfoId int, dayList []time.Time, realPredictEdbInfoData, predictEdbInfoData []*models.EdbDataList, newNhccDataMap, existMap map[string]float64) (newPredictEdbInfoData []*models.EdbDataList, minValue, maxValue float64, err error) {
  1161. allDataList := make([]*models.EdbDataList, 0)
  1162. allDataList = append(allDataList, realPredictEdbInfoData...)
  1163. allDataList = append(allDataList, predictEdbInfoData...)
  1164. newPredictEdbInfoData = predictEdbInfoData
  1165. lenAllData := len(allDataList)
  1166. if lenAllData <= 0 {
  1167. return
  1168. }
  1169. for k, currentDate := range dayList {
  1170. // 动态拟合残差值数据
  1171. currentDateStr := currentDate.Format(utils.FormatDate)
  1172. val, ok := newNhccDataMap[currentDateStr]
  1173. if !ok {
  1174. continue
  1175. }
  1176. tmpData := &models.EdbDataList{
  1177. EdbDataId: edbInfoId + 100000 + lenAllData + k,
  1178. EdbInfoId: edbInfoId,
  1179. DataTime: currentDateStr,
  1180. Value: val,
  1181. DataTimestamp: currentDate.UnixNano() / 1e6,
  1182. }
  1183. newPredictEdbInfoData = append(newPredictEdbInfoData, tmpData)
  1184. allDataList = append(allDataList, tmpData)
  1185. existMap[currentDateStr] = val
  1186. // 最大最小值
  1187. if val < minValue {
  1188. minValue = val
  1189. }
  1190. if val > maxValue {
  1191. maxValue = val
  1192. }
  1193. }
  1194. return
  1195. }
  1196. // getCalculateNhccData 获取计算出来的 拟合残差 数据
  1197. func getCalculateNhccData(secondDataList []*models.EdbDataList, ruleConf RuleLineNhConf) (newBDataMap map[string]float64, err error) {
  1198. firstEdbInfoId := ruleConf.EdbInfoId
  1199. moveDay := ruleConf.MoveDay
  1200. startDate, _ := time.ParseInLocation(utils.FormatDate, ruleConf.StartDate, time.Local)
  1201. endDate, _ := time.ParseInLocation(utils.FormatDate, ruleConf.EndDate, time.Local)
  1202. //查询当前指标现有的数据
  1203. edbInfo, err := data_manage.GetEdbInfoById(firstEdbInfoId)
  1204. if err != nil {
  1205. return
  1206. }
  1207. //第一个指标
  1208. aDataList := make([]models.EdbDataList, 0)
  1209. aDataMap := make(map[string]float64)
  1210. {
  1211. //第一个指标的数据列表
  1212. var firstDataList []*models.EdbDataList
  1213. switch edbInfo.EdbInfoType {
  1214. case 0:
  1215. firstDataList, err = models.GetEdbDataList(edbInfo.Source, edbInfo.EdbInfoId, ``, ``)
  1216. case 1:
  1217. _, firstDataList, _, _, err, _ = GetPredictDataListByPredictEdbInfoId(edbInfo.EdbInfoId, ``, ``, false)
  1218. default:
  1219. err = errors.New(fmt.Sprint("获取失败,指标类型异常", edbInfo.EdbInfoType))
  1220. }
  1221. if err != nil {
  1222. return
  1223. }
  1224. aDataList, aDataMap = handleNhccData(firstDataList, moveDay)
  1225. }
  1226. //第二个指标
  1227. bDataList := make([]models.EdbDataList, 0)
  1228. bDataMap := make(map[string]float64)
  1229. {
  1230. bDataList, bDataMap = handleNhccData(secondDataList, 0)
  1231. }
  1232. if len(aDataList) <= 0 {
  1233. err = errors.New("指标A没有数据")
  1234. return
  1235. }
  1236. if len(bDataList) <= 0 {
  1237. err = errors.New("指标B没有数据")
  1238. return
  1239. }
  1240. // 拟合残差计算的结束日期判断
  1241. {
  1242. endAData := aDataList[len(aDataList)-1]
  1243. tmpEndDate, tmpErr := time.ParseInLocation(utils.FormatDate, endAData.DataTime, time.Local)
  1244. if tmpErr != nil {
  1245. err = tmpErr
  1246. return
  1247. }
  1248. // 如果A指标的最新数据日期早于拟合残差的结束日期,那么就用A指标的最新数据日期
  1249. if tmpEndDate.Before(endDate) {
  1250. endDate = tmpEndDate
  1251. }
  1252. endBData := bDataList[len(bDataList)-1]
  1253. tmpEndDate, tmpErr = time.ParseInLocation(utils.FormatDate, endBData.DataTime, time.Local)
  1254. if tmpErr != nil {
  1255. err = tmpErr
  1256. return
  1257. }
  1258. // 如果B指标的最新数据日期早于拟合残差的结束日期,那么就用A指标的最新数据日期
  1259. if tmpEndDate.Before(endDate) {
  1260. endDate = tmpEndDate
  1261. }
  1262. }
  1263. // 计算线性方程公式
  1264. var a, b float64
  1265. {
  1266. coordinateData := make([]utils.Coordinate, 0)
  1267. for i := startDate; i.Before(endDate) || i.Equal(endDate); i = i.AddDate(0, 0, 1) {
  1268. dateStr := i.Format(utils.FormatDate)
  1269. xValue, ok := aDataMap[dateStr]
  1270. if !ok {
  1271. err = errors.New("指标A日期:" + dateStr + "数据异常,导致计算线性方程公式失败")
  1272. return
  1273. }
  1274. yValue, ok := bDataMap[dateStr]
  1275. if !ok {
  1276. err = errors.New("指标B日期:" + dateStr + "数据异常,导致计算线性方程公式失败")
  1277. return
  1278. }
  1279. tmpCoordinate := utils.Coordinate{
  1280. X: xValue,
  1281. Y: yValue,
  1282. }
  1283. coordinateData = append(coordinateData, tmpCoordinate)
  1284. }
  1285. a, b = utils.GetLinearResult(coordinateData)
  1286. }
  1287. if math.IsNaN(a) || math.IsNaN(b) {
  1288. err = errors.New("线性方程公式生成失败")
  1289. return
  1290. }
  1291. //fmt.Println("a:", a, ";======b:", b)
  1292. //计算B’
  1293. newBDataMap = make(map[string]float64)
  1294. {
  1295. //B’=aA+b
  1296. aDecimal := decimal.NewFromFloat(a)
  1297. bDecimal := decimal.NewFromFloat(b)
  1298. for _, aData := range aDataList {
  1299. xDecimal := decimal.NewFromFloat(aData.Value)
  1300. val, _ := aDecimal.Mul(xDecimal).Add(bDecimal).RoundCeil(4).Float64()
  1301. newBDataMap[aData.DataTime] = val
  1302. }
  1303. }
  1304. return
  1305. }
  1306. // handleNhccData 处理拟合残差需要的数据
  1307. func handleNhccData(dataList []*models.EdbDataList, moveDay int) (newDataList []models.EdbDataList, dateDataMap map[string]float64) {
  1308. dateMap := make(map[time.Time]float64)
  1309. var minDate, maxDate time.Time
  1310. dateDataMap = make(map[string]float64)
  1311. for _, v := range dataList {
  1312. currDate, _ := time.ParseInLocation(utils.FormatDate, v.DataTime, time.Local)
  1313. if minDate.IsZero() || currDate.Before(minDate) {
  1314. minDate = currDate
  1315. }
  1316. if maxDate.IsZero() || currDate.After(maxDate) {
  1317. maxDate = currDate
  1318. }
  1319. dateMap[currDate] = v.Value
  1320. }
  1321. // 处理领先、滞后数据
  1322. newDateMap := make(map[time.Time]float64)
  1323. for currDate, value := range dateMap {
  1324. newDate := currDate.AddDate(0, 0, moveDay)
  1325. newDateMap[newDate] = value
  1326. }
  1327. minDate = minDate.AddDate(0, 0, moveDay)
  1328. maxDate = maxDate.AddDate(0, 0, moveDay)
  1329. // 开始平移天数
  1330. dayNum := utils.GetTimeSubDay(minDate, maxDate)
  1331. for i := 0; i <= dayNum; i++ {
  1332. currDate := minDate.AddDate(0, 0, i)
  1333. tmpValue, ok := newDateMap[currDate]
  1334. if !ok {
  1335. // 万一没有数据,那么就过滤当次循环
  1336. if len(newDataList) <= 0 {
  1337. continue
  1338. }
  1339. //找不到数据,那么就用前面的数据吧
  1340. tmpValue = newDataList[len(newDataList)-1].Value
  1341. }
  1342. tmpData := models.EdbDataList{
  1343. //EdbDataId: 0,
  1344. DataTime: currDate.Format(utils.FormatDate),
  1345. Value: tmpValue,
  1346. }
  1347. dateDataMap[tmpData.DataTime] = tmpData.Value
  1348. newDataList = append(newDataList, tmpData)
  1349. }
  1350. return
  1351. }
  1352. // GetChartPredictEdbInfoDataListByRuleNAnnualAverage 根据 N年均值 规则获取预测数据
  1353. // ETA预测规则:N年均值:过去N年同期均值。过去N年可以连续或者不连续,指标数据均用线性插值补全为日度数据后计算;
  1354. func GetChartPredictEdbInfoDataListByRuleNAnnualAverage(edbInfoId int, configValue string, dayList []time.Time, realPredictEdbInfoData, predictEdbInfoData []*models.EdbDataList, existMap map[string]float64) (newPredictEdbInfoData []*models.EdbDataList, minValue, maxValue float64, err error) {
  1355. // 获取配置的年份列表
  1356. yearList, _, err := getYearListBySeasonConf(configValue)
  1357. if err != nil {
  1358. return
  1359. }
  1360. allDataList := make([]*models.EdbDataList, 0)
  1361. allDataList = append(allDataList, realPredictEdbInfoData...)
  1362. allDataList = append(allDataList, predictEdbInfoData...)
  1363. newPredictEdbInfoData = predictEdbInfoData
  1364. // 插值法数据处理
  1365. handleDataMap := make(map[string]float64)
  1366. err = HandleDataByLinearRegression(allDataList, handleDataMap)
  1367. if err != nil {
  1368. return
  1369. }
  1370. index := len(allDataList)
  1371. //获取后面的预测数据
  1372. predictEdbInfoData = make([]*models.EdbDataList, 0)
  1373. for k, currentDate := range dayList {
  1374. // 如果遇到闰二月,如2.29,去掉该天数据
  1375. if strings.Contains(currentDate.Format(utils.FormatDate), "02-29") {
  1376. continue
  1377. }
  1378. tmpK := len(allDataList) - 1 //上1期数据的下标
  1379. lastDayData := allDataList[tmpK] // 上1期的数据
  1380. tmpHistoryVal := decimal.NewFromFloat(0) //往期的差值总和
  1381. tmpHistoryValNum := 0 // 往期差值计算的数量
  1382. for _, year := range yearList {
  1383. //前几年当日的日期
  1384. tmpHistoryCurrentDate := currentDate.AddDate(year-currentDate.Year(), 0, 0)
  1385. if val, ok := handleDataMap[tmpHistoryCurrentDate.Format(utils.FormatDate)]; ok {
  1386. tmpHistoryVal = tmpHistoryVal.Add(decimal.NewFromFloat(val))
  1387. tmpHistoryValNum++
  1388. }
  1389. }
  1390. //计算的差值与选择的年份数量不一致,那么当前日期不计算
  1391. if tmpHistoryValNum != len(yearList) {
  1392. continue
  1393. }
  1394. val, _ := tmpHistoryVal.Div(decimal.NewFromInt(int64(tmpHistoryValNum))).RoundCeil(4).Float64()
  1395. currentDateStr := currentDate.Format(utils.FormatDate)
  1396. tmpData := &models.EdbDataList{
  1397. EdbDataId: edbInfoId + 100000 + index + k,
  1398. EdbInfoId: edbInfoId,
  1399. DataTime: currentDateStr,
  1400. Value: val,
  1401. DataTimestamp: currentDate.UnixNano() / 1e6,
  1402. }
  1403. newPredictEdbInfoData = append(newPredictEdbInfoData, tmpData)
  1404. allDataList = append(allDataList, tmpData)
  1405. existMap[currentDateStr] = val
  1406. // 继续使用插值法补充新预测日期的数据之间的值
  1407. err = HandleDataByLinearRegression([]*models.EdbDataList{
  1408. lastDayData, tmpData,
  1409. }, handleDataMap)
  1410. if err != nil {
  1411. return
  1412. }
  1413. // 最大最小值
  1414. if val < minValue {
  1415. minValue = val
  1416. }
  1417. if val > maxValue {
  1418. maxValue = val
  1419. }
  1420. }
  1421. return
  1422. }
  1423. // AnnualValueInversionConf 年度值倒推规则
  1424. type AnnualValueInversionConf struct {
  1425. Value float64 `description:"年度值"`
  1426. Type int `description:"分配方式,1:均值法;2:同比法"`
  1427. Year int `description:"同比年份"`
  1428. }
  1429. // GetChartPredictEdbInfoDataListByRuleAnnualValueInversion 根据 年度值倒推 规则获取预测数据
  1430. // ETA预测规则:年度值倒推:设定年度值,余额=年度值-年初至今累计值(算法参考累计值),进行余额分配,均值法分配时保证每期数值相等(日度/周度:剩余期数=剩余自然日历天数/今年指标最新日期自然日历天数*今年至今指标数据期数;旬度/月度/季度/半年度:剩余期数=全年期数(36\12\4\2)-今年至今自然日历期数),同比法保证每期同比相等(同比增速=余额/同比年份相应日期的余额,预测值等于同比年份同期值*同比增速)
  1431. // 举例:
  1432. // 指标A 日度 最新日期 2023-05-19 年初至今累计值100
  1433. // 设置年度值1000
  1434. // 则余额=1000-100=900
  1435. // 均值法分配:剩余期数=226/139*120=195.11
  1436. // 今年之后的每一期预测值=900/195.11=4.6128
  1437. // 同比法分配:同比增速=900/同比年份5.19的余额
  1438. // 预测值=同比年份5-20的值*(1+同比增速)
  1439. func GetChartPredictEdbInfoDataListByRuleAnnualValueInversion(edbInfoId int, configValue string, dayList []time.Time, frequency string, realPredictEdbInfoData, predictEdbInfoData []*models.EdbDataList, existMap map[string]float64) (newPredictEdbInfoData []*models.EdbDataList, minValue, maxValue float64, err error) {
  1440. if frequency == "年度" {
  1441. err = errors.New("当前指标频度是年度,不允许配置年度值倒推")
  1442. return
  1443. }
  1444. // 获取配置
  1445. var annualValueInversionConf AnnualValueInversionConf
  1446. err = json.Unmarshal([]byte(configValue), &annualValueInversionConf)
  1447. if err != nil {
  1448. err = errors.New("年度值倒推配置信息异常:" + err.Error())
  1449. return
  1450. }
  1451. allDataList := make([]*models.EdbDataList, 0)
  1452. allDataList = append(allDataList, realPredictEdbInfoData...)
  1453. allDataList = append(allDataList, predictEdbInfoData...)
  1454. newPredictEdbInfoData = predictEdbInfoData
  1455. index := len(allDataList)
  1456. // 配置的年度值
  1457. yearValueConfig := annualValueInversionConf.Value
  1458. // 当前年的日期
  1459. currDayTime := dayList[0]
  1460. lastDayTime := dayList[len(dayList)-1]
  1461. if currDayTime.Year() != lastDayTime.Year() {
  1462. err = errors.New("年度值倒推不支持跨年预测")
  1463. return
  1464. }
  1465. // 均值法
  1466. if annualValueInversionConf.Type == 1 {
  1467. // 当前年的期数
  1468. currYearN := 0
  1469. var currYearVal float64
  1470. for _, v := range allDataList {
  1471. currTime, tmpErr := time.ParseInLocation(utils.FormatDate, v.DataTime, time.Local)
  1472. if tmpErr != nil {
  1473. err = tmpErr
  1474. return
  1475. }
  1476. // 只是计算今年的
  1477. if currTime.Year() != currDayTime.Year() {
  1478. continue
  1479. }
  1480. currYearN++
  1481. currYearVal = currYearVal + v.Value
  1482. }
  1483. var averageVal float64
  1484. switch frequency {
  1485. case "半年度":
  1486. averageVal, _ = (decimal.NewFromFloat(yearValueConfig).Sub(decimal.NewFromFloat(currYearVal))).Div(decimal.NewFromInt(int64(2 - currYearN))).Float64()
  1487. case "季度":
  1488. averageVal, _ = (decimal.NewFromFloat(yearValueConfig).Sub(decimal.NewFromFloat(currYearVal))).Div(decimal.NewFromInt(int64(4 - currYearN))).Float64()
  1489. case "月度":
  1490. averageVal, _ = (decimal.NewFromFloat(yearValueConfig).Sub(decimal.NewFromFloat(currYearVal))).Div(decimal.NewFromInt(int64(12 - currYearN))).Float64()
  1491. case "旬度":
  1492. averageVal, _ = (decimal.NewFromFloat(yearValueConfig).Sub(decimal.NewFromFloat(currYearVal))).Div(decimal.NewFromInt(int64(36 - currYearN))).Float64()
  1493. case "周度", "日度":
  1494. //剩余期数=剩余自然日历天数/今年指标最新日期自然日历天数*今年至今指标数据期数
  1495. // 当前年的第一天
  1496. yearFirstDay := time.Date(currDayTime.Year(), 1, 1, 0, 0, 0, 0, time.Local)
  1497. subDay := utils.GetTimeSubDay(yearFirstDay, currDayTime) + 1
  1498. // 当前年的最后一天
  1499. yearLastDay := time.Date(currDayTime.Year(), 12, 31, 0, 0, 0, 0, time.Local)
  1500. subDay2 := utils.GetTimeSubDay(yearFirstDay, yearLastDay) + 1
  1501. surplusN := decimal.NewFromInt(int64(subDay2 - subDay)).Div(decimal.NewFromInt(int64(subDay))).Mul(decimal.NewFromInt(int64(currYearN)))
  1502. averageVal, _ = (decimal.NewFromFloat(annualValueInversionConf.Value).Sub(decimal.NewFromFloat(currYearVal))).Div(surplusN).Round(4).Float64()
  1503. }
  1504. for k, currentDate := range dayList {
  1505. currentDateStr := currentDate.Format(utils.FormatDate)
  1506. tmpData := &models.EdbDataList{
  1507. EdbDataId: edbInfoId + 100000 + index + k,
  1508. EdbInfoId: edbInfoId,
  1509. DataTime: currentDateStr,
  1510. Value: averageVal,
  1511. DataTimestamp: currentDate.UnixNano() / 1e6,
  1512. }
  1513. newPredictEdbInfoData = append(newPredictEdbInfoData, tmpData)
  1514. allDataList = append(allDataList, tmpData)
  1515. existMap[currentDateStr] = averageVal
  1516. }
  1517. // 最大最小值
  1518. if averageVal < minValue {
  1519. minValue = averageVal
  1520. }
  1521. if averageVal > maxValue {
  1522. maxValue = averageVal
  1523. }
  1524. return
  1525. }
  1526. // 同比法分配
  1527. // 同比法保证每期同比相等(同比增速=余额/同比年份相应日期的余额,预测值等于同比年份同期值*同比增速);
  1528. // 同比法分配:同比增速=900/同比年份5.19的余额
  1529. // 每年截止到当前日期的累计值
  1530. dateTotalMap := make(map[time.Time]float64)
  1531. // 每年的累计值(计算使用)
  1532. yearTotalMap := make(map[int]float64)
  1533. for _, v := range allDataList {
  1534. currTime, tmpErr := time.ParseInLocation(utils.FormatDate, v.DataTime, time.Local)
  1535. if tmpErr != nil {
  1536. err = tmpErr
  1537. return
  1538. }
  1539. yearVal := yearTotalMap[currTime.Year()]
  1540. yearVal = yearVal + v.Value
  1541. yearTotalMap[currTime.Year()] = yearVal
  1542. dateTotalMap[currTime] = yearVal
  1543. }
  1544. //(同比增速=余额/同比年份相应日期的余额,预测值等于同比年份同期值*同比增速);
  1545. for k, currentDate := range dayList {
  1546. currYearBalance := yearValueConfig - yearTotalMap[currentDate.Year()] // 当年的余额
  1547. //同比年份相应日期
  1548. lastYear := annualValueInversionConf.Year + (currentDate.Year() - currDayTime.Year())
  1549. var lastDateTime time.Time
  1550. switch frequency {
  1551. case "半年度", "季度":
  1552. lastDateTime = time.Date(lastYear, currentDate.Month(), currentDate.Day(), 0, 0, 0, 0, currentDate.Location())
  1553. case "月度":
  1554. lastDateTime = time.Date(lastYear, currentDate.Month()+1, 1, 0, 0, 0, 0, currentDate.Location()).AddDate(0, 0, -1)
  1555. case "旬度":
  1556. if currentDate.Day() == 10 || currentDate.Day() == 20 {
  1557. lastDateTime = time.Date(lastYear, currentDate.Month(), currentDate.Day(), 0, 0, 0, 0, currentDate.Location())
  1558. } else {
  1559. lastDateTime = time.Date(lastYear, currentDate.Month()+1, 1, 0, 0, 0, 0, currentDate.Location()).AddDate(0, 0, -1)
  1560. }
  1561. case "周度", "日度":
  1562. lastDateTime = time.Date(lastYear, currentDate.Month(), currentDate.Day(), 0, 0, 0, 0, currentDate.Location())
  1563. }
  1564. // 同比年份相应日期的累计值
  1565. var dateTotal float64
  1566. dateTotal, ok := dateTotalMap[lastDateTime]
  1567. if !ok { //如果没有找到这个日期,那么就往前面找,一直到找到这个累计值,或者找完这一年
  1568. yearFirstDayTime := time.Date(lastDateTime.Year(), 1, 1, 0, 0, 0, 0, lastDateTime.Location())
  1569. for tmpDateTime := lastDateTime.AddDate(0, 0, -1); tmpDateTime.After(yearFirstDayTime) || tmpDateTime.Equal(yearFirstDayTime); tmpDateTime = tmpDateTime.AddDate(0, 0, -1) {
  1570. dateTotal, ok = dateTotalMap[tmpDateTime]
  1571. if ok {
  1572. break
  1573. }
  1574. }
  1575. }
  1576. //同比年份相应日期的余额
  1577. lastYearDateBalance := yearValueConfig - dateTotal
  1578. // 同比增速=余额/同比年份相应日期的余额
  1579. tbVal := decimal.NewFromFloat(currYearBalance).Div(decimal.NewFromFloat(lastYearDateBalance))
  1580. // 获取同比年份同期值,获取失败的话,就不处理
  1581. if lastDateVal, ok := existMap[lastDateTime.Format(utils.FormatDate)]; ok {
  1582. //预测值 = 同比年份同期值*同比增速
  1583. tmpVal, _ := decimal.NewFromFloat(lastDateVal).Mul(tbVal).Round(4).Float64()
  1584. currentDateStr := currentDate.Format(utils.FormatDate)
  1585. tmpData := &models.EdbDataList{
  1586. EdbDataId: edbInfoId + 100000 + index + k,
  1587. EdbInfoId: edbInfoId,
  1588. DataTime: currentDateStr,
  1589. Value: tmpVal,
  1590. DataTimestamp: currentDate.UnixNano() / 1e6,
  1591. }
  1592. newPredictEdbInfoData = append(newPredictEdbInfoData, tmpData)
  1593. allDataList = append(allDataList, tmpData)
  1594. existMap[currentDateStr] = tmpVal
  1595. yearVal := yearTotalMap[currentDate.Year()]
  1596. yearVal = yearVal + tmpVal
  1597. yearTotalMap[currentDate.Year()] = yearVal
  1598. dateTotalMap[currentDate] = yearVal
  1599. // 最大最小值
  1600. if tmpVal < minValue {
  1601. minValue = tmpVal
  1602. }
  1603. if tmpVal > maxValue {
  1604. maxValue = tmpVal
  1605. }
  1606. }
  1607. }
  1608. return
  1609. }
  1610. // getYearListBySeasonConf 根据配置获取年份列表
  1611. func getYearListBySeasonConf(configValue string) (yearList []int, seasonConf SeasonConf, err error) {
  1612. tmpErr := json.Unmarshal([]byte(configValue), &seasonConf)
  1613. if tmpErr != nil {
  1614. err = errors.New("年份配置信息异常:" + tmpErr.Error())
  1615. return
  1616. }
  1617. //选择方式,1:连续N年;2:指定年份
  1618. if seasonConf.YearType == 1 {
  1619. if seasonConf.NValue < 1 {
  1620. err = errors.New("连续N年不允许小于1")
  1621. return
  1622. }
  1623. currYear := time.Now().Year()
  1624. for i := 0; i < seasonConf.NValue; i++ {
  1625. yearList = append(yearList, currYear-i-1)
  1626. }
  1627. } else {
  1628. yearList = seasonConf.YearList
  1629. }
  1630. return
  1631. }