predict_edb_info_rule.go 75 KB

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