predict_edb_info_rule.go 65 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780
  1. package models
  2. import (
  3. "encoding/json"
  4. "errors"
  5. "eta_gn/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. }
  1317. // GetChartPredictEdbInfoDataListByRuleAnnualValueInversion 根据 年度值倒推 规则获取预测数据
  1318. // ETA预测规则:年度值倒推:设定年度值,余额=年度值-年初至今累计值(算法参考累计值),进行余额分配,均值法分配时保证每期数值相等(日度/周度:剩余期数=剩余自然日历天数/今年指标最新日期自然日历天数*今年至今指标数据期数;旬度/月度/季度/半年度:剩余期数=全年期数(36\12\4\2)-今年至今自然日历期数),同比法保证每期同比相等(同比增速=余额/同比年份相应日期的余额,预测值等于同比年份同期值*同比增速)
  1319. // 举例:
  1320. // 指标A 日度 最新日期 2023-05-19 年初至今累计值100
  1321. // 设置年度值1000
  1322. // 则余额=1000-100=900
  1323. // 均值法分配:剩余期数=226/139*120=195.11
  1324. // 今年之后的每一期预测值=900/195.11=4.6128
  1325. // 同比法分配:同比增速=900/同比年份5.19的余额
  1326. // 预测值=同比年份5-20的值*(1+同比增速)
  1327. 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) {
  1328. if frequency == "年度" {
  1329. err = errors.New("当前指标频度是年度,不允许配置年度值倒推")
  1330. return
  1331. }
  1332. // 获取配置
  1333. var annualValueInversionConf AnnualValueInversionConf
  1334. err = json.Unmarshal([]byte(configValue), &annualValueInversionConf)
  1335. if err != nil {
  1336. err = errors.New("年度值倒推配置信息异常:" + err.Error())
  1337. return
  1338. }
  1339. allDataList := make([]*EdbInfoSearchData, 0)
  1340. allDataList = append(allDataList, realPredictEdbInfoData...)
  1341. allDataList = append(allDataList, predictEdbInfoData...)
  1342. newPredictEdbInfoData = predictEdbInfoData
  1343. index := len(allDataList)
  1344. // 没有数据,直接返回
  1345. if index <= 0 {
  1346. return
  1347. }
  1348. // 配置的年度值
  1349. yearValueConfig := annualValueInversionConf.Value
  1350. // 最新数据的日期
  1351. currDayTime, err := time.ParseInLocation(utils.FormatDate, allDataList[index-1].DataTime, time.Local)
  1352. if err != nil {
  1353. return
  1354. }
  1355. // 当前年的日期
  1356. lastDayTime := dayList[len(dayList)-1]
  1357. if currDayTime.Year() != lastDayTime.Year() {
  1358. err = errors.New("年度值倒推不支持跨年预测")
  1359. return
  1360. }
  1361. // 均值法
  1362. if annualValueInversionConf.Type == 1 {
  1363. // 当前年的期数
  1364. currYearN := 0
  1365. // 当前已经消耗的额度
  1366. var currYearVal float64
  1367. // 计算当前年的期数以及已经消耗的额度
  1368. {
  1369. if frequency != "周度" {
  1370. for _, v := range allDataList {
  1371. currTime, tmpErr := time.ParseInLocation(utils.FormatDate, v.DataTime, time.Local)
  1372. if tmpErr != nil {
  1373. err = tmpErr
  1374. return
  1375. }
  1376. // 只是计算今年的
  1377. if currTime.Year() != currDayTime.Year() {
  1378. continue
  1379. }
  1380. currYearN++
  1381. currYearVal = currYearVal + v.Value
  1382. }
  1383. } else {
  1384. tmpDataList := make([]*EdbInfoSearchData, 0)
  1385. // 上一期的数据
  1386. var lastData *EdbInfoSearchData
  1387. // 是否第一条数据
  1388. isFirst := true
  1389. for _, v := range allDataList {
  1390. currTime, tmpErr := time.ParseInLocation(utils.FormatDate, v.DataTime, time.Local)
  1391. if tmpErr != nil {
  1392. err = tmpErr
  1393. return
  1394. }
  1395. // 只是计算今年的
  1396. if currTime.Year() != currDayTime.Year() {
  1397. lastData = v
  1398. continue
  1399. }
  1400. if isFirst {
  1401. tmpDataList = append(tmpDataList, lastData)
  1402. }
  1403. isFirst = false
  1404. tmpDataList = append(tmpDataList, v)
  1405. currYearN++
  1406. }
  1407. // 需要插值法处理
  1408. tmpHandleDataMap := make(map[string]float64)
  1409. _, err = HandleDataByLinearRegression(tmpDataList, tmpHandleDataMap)
  1410. if err != nil {
  1411. return
  1412. }
  1413. for tmpDate, val := range tmpHandleDataMap {
  1414. tmpDateTime, tmpErr := time.ParseInLocation(utils.FormatDate, tmpDate, time.Local)
  1415. if tmpErr != nil {
  1416. err = tmpErr
  1417. return
  1418. }
  1419. if tmpDateTime.Year() != currDayTime.Year() {
  1420. continue
  1421. }
  1422. currYearVal = currYearVal + val
  1423. }
  1424. currYearVal = currYearVal / 7
  1425. }
  1426. }
  1427. var averageVal float64
  1428. switch frequency {
  1429. case "半年度":
  1430. averageVal, _ = (decimal.NewFromFloat(yearValueConfig).Sub(decimal.NewFromFloat(currYearVal))).Div(decimal.NewFromInt(int64(2 - currYearN))).Float64()
  1431. case "季度":
  1432. averageVal, _ = (decimal.NewFromFloat(yearValueConfig).Sub(decimal.NewFromFloat(currYearVal))).Div(decimal.NewFromInt(int64(4 - currYearN))).Float64()
  1433. case "月度":
  1434. averageVal, _ = (decimal.NewFromFloat(yearValueConfig).Sub(decimal.NewFromFloat(currYearVal))).Div(decimal.NewFromInt(int64(12 - currYearN))).Float64()
  1435. case "旬度":
  1436. averageVal, _ = (decimal.NewFromFloat(yearValueConfig).Sub(decimal.NewFromFloat(currYearVal))).Div(decimal.NewFromInt(int64(36 - currYearN))).Float64()
  1437. case "周度", "日度":
  1438. //剩余期数=剩余自然日历天数/今年指标最新日期自然日历天数*今年至今指标数据期数
  1439. // 当前年的第一天
  1440. yearFirstDay := time.Date(currDayTime.Year(), 1, 1, 0, 0, 0, 0, time.Local)
  1441. subDay := utils.GetTimeSubDay(yearFirstDay, currDayTime) + 1
  1442. // 当前年的最后一天
  1443. yearLastDay := time.Date(currDayTime.Year(), 12, 31, 0, 0, 0, 0, time.Local)
  1444. subDay2 := utils.GetTimeSubDay(yearFirstDay, yearLastDay) + 1
  1445. // 剩余期数
  1446. surplusN := decimal.NewFromInt(int64(subDay2 - subDay)).Div(decimal.NewFromInt(int64(subDay))).Mul(decimal.NewFromInt(int64(currYearN)))
  1447. // 剩余余额
  1448. balance := decimal.NewFromFloat(annualValueInversionConf.Value).Sub(decimal.NewFromFloat(currYearVal))
  1449. averageVal, _ = balance.Div(surplusN).Round(4).Float64()
  1450. }
  1451. // 保留四位小数
  1452. averageVal, _ = decimal.NewFromFloat(averageVal).Round(4).Float64()
  1453. for k, currentDate := range dayList {
  1454. currentDateStr := currentDate.Format(utils.FormatDate)
  1455. tmpData := &EdbInfoSearchData{
  1456. EdbDataId: edbInfoId + 100000 + index + k,
  1457. //EdbInfoId: edbInfoId,
  1458. DataTime: currentDateStr,
  1459. Value: averageVal,
  1460. //DataTimestamp: currentDate.UnixNano() / 1e6,
  1461. }
  1462. newPredictEdbInfoData = append(newPredictEdbInfoData, tmpData)
  1463. allDataList = append(allDataList, tmpData)
  1464. existMap[currentDateStr] = averageVal
  1465. }
  1466. // 最大最小值
  1467. if averageVal < minValue {
  1468. minValue = averageVal
  1469. }
  1470. if averageVal > maxValue {
  1471. maxValue = averageVal
  1472. }
  1473. return
  1474. }
  1475. // 同比法分配
  1476. // 同比法保证每期同比相等(同比增速=余额/同比年份相应日期的余额,预测值等于同比年份同期值*同比增速);
  1477. // 同比法分配:同比增速=900/同比年份5.19的余额
  1478. // 每年截止到当前日期的累计值
  1479. dateTotalMap := make(map[time.Time]float64)
  1480. // 每年的累计值(计算使用)
  1481. yearTotalMap := make(map[int]float64)
  1482. for _, v := range allDataList {
  1483. currTime, tmpErr := time.ParseInLocation(utils.FormatDate, v.DataTime, time.Local)
  1484. if tmpErr != nil {
  1485. err = tmpErr
  1486. return
  1487. }
  1488. yearVal := yearTotalMap[currTime.Year()]
  1489. yearVal = yearVal + v.Value
  1490. yearTotalMap[currTime.Year()] = yearVal
  1491. dateTotalMap[currTime] = yearVal
  1492. }
  1493. //(同比增速=余额/同比年份相应日期的余额,预测值等于同比年份同期值*同比增速);
  1494. for k, currentDate := range dayList {
  1495. currYearBalance := yearValueConfig - yearTotalMap[currentDate.Year()] // 当年的余额
  1496. // 上一期的日期
  1497. prevDateStr := allDataList[len(allDataList)-1].DataTime
  1498. prevDateTime, tmpErr := time.ParseInLocation(utils.FormatDate, prevDateStr, time.Local)
  1499. if tmpErr != nil {
  1500. err = tmpErr
  1501. return
  1502. }
  1503. //同比年份相应日期
  1504. lastYear := annualValueInversionConf.Year + (currentDate.Year() - currDayTime.Year())
  1505. // 前N年的上一期时间;前N年的当期时间;
  1506. var lastPrevDateTime, lastDateTime time.Time
  1507. switch frequency {
  1508. case "半年度", "季度":
  1509. lastDateTime = time.Date(lastYear, currentDate.Month(), currentDate.Day(), 0, 0, 0, 0, currentDate.Location())
  1510. lastPrevDateTime = time.Date(lastYear, prevDateTime.Month(), prevDateTime.Day(), 0, 0, 0, 0, prevDateTime.Location())
  1511. case "月度":
  1512. lastDateTime = time.Date(lastYear, currentDate.Month()+1, 1, 0, 0, 0, 0, currentDate.Location()).AddDate(0, 0, -1)
  1513. lastPrevDateTime = time.Date(lastYear, prevDateTime.Month()+1, 1, 0, 0, 0, 0, prevDateTime.Location()).AddDate(0, 0, -1)
  1514. case "旬度":
  1515. if prevDateTime.Day() == 10 || prevDateTime.Day() == 20 {
  1516. lastDateTime = time.Date(lastYear, currentDate.Month(), currentDate.Day(), 0, 0, 0, 0, currentDate.Location())
  1517. lastPrevDateTime = time.Date(lastYear, prevDateTime.Month(), prevDateTime.Day(), 0, 0, 0, 0, prevDateTime.Location())
  1518. } else {
  1519. lastDateTime = time.Date(lastYear, currentDate.Month()+1, 1, 0, 0, 0, 0, currentDate.Location()).AddDate(0, 0, -1)
  1520. lastPrevDateTime = time.Date(lastYear, prevDateTime.Month()+1, 1, 0, 0, 0, 0, prevDateTime.Location()).AddDate(0, 0, -1)
  1521. }
  1522. case "周度", "日度":
  1523. lastDateTime = time.Date(lastYear, currentDate.Month(), currentDate.Day(), 0, 0, 0, 0, currentDate.Location())
  1524. lastPrevDateTime = time.Date(lastYear, prevDateTime.Month(), prevDateTime.Day(), 0, 0, 0, 0, prevDateTime.Location())
  1525. }
  1526. // 同比年份相应日期的累计值
  1527. var dateTotal float64
  1528. dateTotal, ok := dateTotalMap[lastPrevDateTime]
  1529. if !ok { //如果没有找到这个日期,那么就往前面找,一直到找到这个累计值,或者找完这一年
  1530. yearFirstDayTime := time.Date(lastPrevDateTime.Year(), 1, 1, 0, 0, 0, 0, lastDateTime.Location())
  1531. for tmpDateTime := lastPrevDateTime.AddDate(0, 0, -1); tmpDateTime.After(yearFirstDayTime) || tmpDateTime.Equal(yearFirstDayTime); tmpDateTime = tmpDateTime.AddDate(0, 0, -1) {
  1532. dateTotal, ok = dateTotalMap[tmpDateTime]
  1533. if ok {
  1534. break
  1535. }
  1536. }
  1537. }
  1538. //同比年份相应的上一期日期的余额
  1539. lastYearDateBalance := yearTotalMap[lastPrevDateTime.Year()] - dateTotal
  1540. if lastYearDateBalance == 0 {
  1541. continue
  1542. }
  1543. // 同比增速=当年余额/同比年份上一期日期的余额
  1544. tbVal := decimal.NewFromFloat(currYearBalance).Div(decimal.NewFromFloat(lastYearDateBalance))
  1545. // 获取同比年份同期值,获取失败的话,就不处理
  1546. if lastDateVal, ok := existMap[lastDateTime.Format(utils.FormatDate)]; ok {
  1547. //预测值 = 同比年份同期值*同比增速
  1548. tmpVal, _ := decimal.NewFromFloat(lastDateVal).Mul(tbVal).Round(4).Float64()
  1549. currentDateStr := currentDate.Format(utils.FormatDate)
  1550. tmpData := &EdbInfoSearchData{
  1551. EdbDataId: edbInfoId + 100000 + index + k,
  1552. //EdbInfoId: edbInfoId,
  1553. DataTime: currentDateStr,
  1554. Value: tmpVal,
  1555. //DataTimestamp: currentDate.UnixNano() / 1e6,
  1556. }
  1557. newPredictEdbInfoData = append(newPredictEdbInfoData, tmpData)
  1558. allDataList = append(allDataList, tmpData)
  1559. existMap[currentDateStr] = tmpVal
  1560. yearVal := yearTotalMap[currentDate.Year()]
  1561. yearVal = yearVal + tmpVal
  1562. yearTotalMap[currentDate.Year()] = yearVal
  1563. dateTotalMap[currentDate] = yearVal
  1564. // 最大最小值
  1565. if tmpVal < minValue {
  1566. minValue = tmpVal
  1567. }
  1568. if tmpVal > maxValue {
  1569. maxValue = tmpVal
  1570. }
  1571. }
  1572. }
  1573. return
  1574. }
  1575. // getYearListBySeasonConf 根据配置获取年份列表
  1576. func getYearListBySeasonConf(configValue string) (yearList []int, seasonConf SeasonConf, err error) {
  1577. tmpErr := json.Unmarshal([]byte(configValue), &seasonConf)
  1578. if tmpErr != nil {
  1579. err = errors.New("年份配置信息异常:" + tmpErr.Error())
  1580. return
  1581. }
  1582. //选择方式,1:连续N年;2:指定年份
  1583. if seasonConf.YearType == 1 {
  1584. if seasonConf.NValue < 1 {
  1585. err = errors.New("连续N年不允许小于1")
  1586. return
  1587. }
  1588. currYear := time.Now().Year()
  1589. for i := 0; i < seasonConf.NValue; i++ {
  1590. yearList = append(yearList, currYear-i-1)
  1591. }
  1592. } else {
  1593. yearList = seasonConf.YearList
  1594. }
  1595. return
  1596. }