predict_edb_info_rule.go 70 KB

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