predict_edb_info_rule.go 65 KB

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