predict_edb_info_rule.go 69 KB

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