predict_edb_info_rule.go 69 KB

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