predict_edb_info_rule.go 74 KB

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