predict_edb_info_rule.go 69 KB

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