predict_edb_info_rule.go 67 KB

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