predict_edb_info_rule.go 67 KB

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