predict_edb_info_rule.go 63 KB

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