predict_edb_info_rule.go 70 KB

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