predict_edb_info_rule.go 67 KB

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