predict_edb_info_rule.go 68 KB

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