predict_edb_data_calculate_nh.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378
  1. package models
  2. import (
  3. "errors"
  4. "eta/eta_index_lib/utils"
  5. "fmt"
  6. "github.com/beego/beego/v2/client/orm"
  7. "github.com/shopspring/decimal"
  8. "strconv"
  9. "strings"
  10. "time"
  11. )
  12. // SavePredictCalculateNh 预测年化值
  13. func SavePredictCalculateNh(reqEdbInfoId, classifyId int, edbName, frequency, unit, formula string, fromEdbInfo *EdbInfo, edbCode, uniqueCode string, sysUserId int, sysUserRealName string) (edbInfo *EdbInfo, latestDateStr string, latestValue float64, err error, errMsg string) {
  14. o := orm.NewOrm()
  15. to, err := o.Begin()
  16. if err != nil {
  17. return
  18. }
  19. defer func() {
  20. if err != nil {
  21. fmt.Println("SavePredictCalculateNh,Err:" + err.Error())
  22. _ = to.Rollback()
  23. } else {
  24. _ = to.Commit()
  25. }
  26. }()
  27. fmt.Println("reqEdbInfoId:", reqEdbInfoId)
  28. if reqEdbInfoId <= 0 {
  29. edbInfo = &EdbInfo{
  30. //EdbInfoId: 0,
  31. EdbInfoType: 1,
  32. SourceName: utils.DATA_SOURCE_NAME_PREDICT_CALCULATE_NH,
  33. Source: utils.DATA_SOURCE_PREDICT_CALCULATE_NH,
  34. EdbCode: edbCode,
  35. EdbName: edbName,
  36. EdbNameSource: edbName,
  37. Frequency: frequency,
  38. Unit: unit,
  39. //StartDate: "",
  40. //EndDate: "",
  41. ClassifyId: classifyId,
  42. SysUserId: sysUserId,
  43. SysUserRealName: sysUserRealName,
  44. UniqueCode: uniqueCode,
  45. CreateTime: time.Now(),
  46. ModifyTime: time.Now(),
  47. MinValue: 0,
  48. MaxValue: 0,
  49. CalculateFormula: formula,
  50. EdbType: 2,
  51. Sort: 0,
  52. MoveType: 0,
  53. MoveFrequency: "",
  54. NoUpdate: 0,
  55. ServerUrl: "",
  56. EdbNameEn: "",
  57. UnitEn: "",
  58. LatestDate: "",
  59. LatestValue: 0,
  60. ChartImage: "",
  61. }
  62. newEdbInfoId, tmpErr := to.Insert(edbInfo)
  63. if tmpErr != nil {
  64. err = tmpErr
  65. return
  66. }
  67. edbInfo.EdbInfoId = int(newEdbInfoId)
  68. // 添加关联关系
  69. {
  70. calculateMappingItem := &EdbInfoCalculateMapping{
  71. EdbInfoCalculateMappingId: 0,
  72. EdbInfoId: edbInfo.EdbInfoId,
  73. Source: edbInfo.Source,
  74. SourceName: edbInfo.SourceName,
  75. EdbCode: edbCode,
  76. FromEdbInfoId: fromEdbInfo.EdbInfoId,
  77. FromEdbCode: fromEdbInfo.EdbCode,
  78. FromEdbName: fromEdbInfo.EdbName,
  79. FromSource: fromEdbInfo.Source,
  80. FromSourceName: fromEdbInfo.SourceName,
  81. FromTag: "",
  82. Sort: 1,
  83. CreateTime: time.Now(),
  84. ModifyTime: time.Now(),
  85. }
  86. _, err = to.Insert(calculateMappingItem)
  87. if err != nil {
  88. return
  89. }
  90. }
  91. } else {
  92. edbInfo, err = GetEdbInfoById(reqEdbInfoId)
  93. if err != nil {
  94. if err.Error() == utils.ErrNoRow() {
  95. errMsg = `获取指标信息失败`
  96. }
  97. return
  98. }
  99. if edbInfo.EdbInfoType != 1 {
  100. errMsg = `该指标不是预测指标`
  101. err = errors.New(errMsg)
  102. return
  103. }
  104. latestDateStr = edbInfo.LatestDate
  105. latestValue = edbInfo.LatestValue
  106. //修改指标信息
  107. edbInfo.EdbName = edbName
  108. edbInfo.EdbNameSource = edbName
  109. edbInfo.Frequency = frequency
  110. edbInfo.Unit = unit
  111. edbInfo.ClassifyId = classifyId
  112. edbInfo.CalculateFormula = formula
  113. edbInfo.ModifyTime = time.Now()
  114. _, err = to.Update(edbInfo, "EdbName", "EdbNameSource", "Frequency", "Unit", "ClassifyId", "CalculateFormula", "ModifyTime")
  115. if err != nil {
  116. return
  117. }
  118. //判断计算指标是否被更换
  119. var existCondition string
  120. var existPars []interface{}
  121. existCondition += " AND edb_info_id=? AND from_edb_info_id=? "
  122. existPars = append(existPars, edbInfo.EdbInfoId, fromEdbInfo.EdbInfoId)
  123. count, tmpErr := GetEdbInfoCalculateCountByCondition(existCondition, existPars)
  124. if tmpErr != nil {
  125. err = errors.New("判断指标是否改变失败,Err:" + tmpErr.Error())
  126. return
  127. }
  128. if count > 0 { // 指标未被替换,无需重新计算
  129. return
  130. }
  131. //删除,计算指标关联的,基础指标的关联关系
  132. sql := ` DELETE FROM edb_info_calculate_mapping WHERE edb_info_id = ? `
  133. _, err = to.Raw(sql, edbInfo.EdbInfoId).Exec()
  134. if err != nil {
  135. err = errors.New("删除计算指标关联关系失败,Err:" + err.Error())
  136. return
  137. }
  138. //清空原有已经入库的数据
  139. tableName := GetEdbDataTableName(edbInfo.Source, edbInfo.SubSource)
  140. sql = ` DELETE FROM ` + tableName + ` WHERE edb_info_id = ? `
  141. _, err = to.Raw(sql, edbInfo.EdbInfoId).Exec()
  142. if err != nil {
  143. return
  144. }
  145. //关联关系
  146. {
  147. calculateMappingItem := &EdbInfoCalculateMapping{
  148. EdbInfoCalculateMappingId: 0,
  149. EdbInfoId: edbInfo.EdbInfoId,
  150. Source: edbInfo.Source,
  151. SourceName: edbInfo.SourceName,
  152. EdbCode: edbCode,
  153. FromEdbInfoId: fromEdbInfo.EdbInfoId,
  154. FromEdbCode: fromEdbInfo.EdbCode,
  155. FromEdbName: fromEdbInfo.EdbName,
  156. FromSource: fromEdbInfo.Source,
  157. FromSourceName: fromEdbInfo.SourceName,
  158. FromTag: "",
  159. Sort: 1,
  160. CreateTime: time.Now(),
  161. ModifyTime: time.Now(),
  162. }
  163. _, err = to.Insert(calculateMappingItem)
  164. if err != nil {
  165. return
  166. }
  167. }
  168. }
  169. // 计算数据
  170. latestDateStr, latestValue, err = refreshAllPredictCalculateNh(to, edbInfo.EdbInfoId, edbInfo.Source, edbInfo.SubSource, fromEdbInfo, edbCode)
  171. return
  172. }
  173. // RefreshAllPredictCalculateNh 刷新全部预测年化值数据
  174. func RefreshAllPredictCalculateNh(edbInfoId, source, subSource int, fromEdbInfo *EdbInfo, edbCode, edbFrequency, formula string) (latestDateStr string, latestValue float64, err error) {
  175. o := orm.NewOrm()
  176. to, err := o.Begin()
  177. if err != nil {
  178. return
  179. }
  180. defer func() {
  181. if err != nil {
  182. fmt.Println("RefreshAllCalculateNh,Err:" + err.Error())
  183. _ = to.Rollback()
  184. } else {
  185. _ = to.Commit()
  186. }
  187. }()
  188. // 计算数据
  189. latestDateStr, latestValue, err = refreshAllPredictCalculateNh(to, edbInfoId, source, subSource, fromEdbInfo, edbCode)
  190. return
  191. }
  192. // refreshAllPredictCalculateNh 刷新预测年化数据
  193. func refreshAllPredictCalculateNh(to orm.TxOrmer, edbInfoId, source, subSource int, fromEdbInfo *EdbInfo, edbCode string) (latestDateStr string, latestValue float64, err error) {
  194. edbInfoIdStr := strconv.Itoa(edbInfoId)
  195. tableName := GetEdbDataTableName(utils.DATA_SOURCE_PREDICT_CALCULATE_NH, subSource)
  196. //获取年化指标所有数据
  197. existDataList, err := GetAllEdbDataListByTo(to, edbInfoId, source, subSource)
  198. if err != nil {
  199. return
  200. }
  201. //计算指标的map
  202. existDataMap := make(map[string]*EdbData, 0)
  203. removeDateMap := make(map[string]string)
  204. for _, v := range existDataList {
  205. existDataMap[v.DataTime] = v
  206. removeDateMap[v.DataTime] = ``
  207. }
  208. //获取源指标数据
  209. fmt.Println("EdbInfoId:", fromEdbInfo.EdbInfoId)
  210. fromDataList, err := GetPredictEdbDataListAll(fromEdbInfo, 1)
  211. if err != nil {
  212. return
  213. }
  214. // 插值法数据处理
  215. handleDataMap := make(map[string]float64)
  216. _, err = HandleDataByLinearRegression(fromDataList, handleDataMap)
  217. if err != nil {
  218. return
  219. }
  220. var dateArr []string
  221. dataMap := make(map[string]*EdbInfoSearchData)
  222. fromDataMap := make(map[string]float64)
  223. //来源指指标数据
  224. for _, v := range fromDataList {
  225. dateArr = append(dateArr, v.DataTime)
  226. dataMap[v.DataTime] = v
  227. fromDataMap[v.DataTime] = v.Value
  228. }
  229. lenFromDataList := len(fromDataList)
  230. // 如果来源指标没有数据,那么就直接返回得了
  231. if lenFromDataList <= 0 {
  232. sql := fmt.Sprintf(` DELETE FROM %s WHERE edb_info_id = ? `, tableName)
  233. _, err = to.Raw(sql, edbInfoId).Exec()
  234. if err != nil {
  235. err = fmt.Errorf("删除年化指标数据失败,Err:" + err.Error())
  236. return
  237. }
  238. return
  239. }
  240. fmt.Println("source:", source)
  241. // 真实数据的最后日期
  242. latestDateStr = fromEdbInfo.LatestDate
  243. // 每年的最后一天的数据值
  244. yearLastValMap := make(map[int]float64)
  245. startDataTime, _ := time.ParseInLocation(utils.FormatDate, fromDataList[0].DataTime, time.Local)
  246. endDataTime, _ := time.ParseInLocation(utils.FormatDate, fromDataList[lenFromDataList-1].DataTime, time.Local)
  247. for i := startDataTime.Year(); i <= endDataTime.Year(); i++ {
  248. tmpDateStr := fmt.Sprintf("%d-12-31", i)
  249. if tmpVal, ok := handleDataMap[tmpDateStr]; ok {
  250. yearLastValMap[i] = tmpVal
  251. }
  252. }
  253. addSql := ` INSERT INTO ` + tableName + ` (edb_info_id,edb_code,data_time,value,create_time,modify_time,data_timestamp) values `
  254. var isAdd bool
  255. //来源指指标数据
  256. for _, v := range fromDataList {
  257. currDateStr := v.DataTime
  258. currDate, _ := time.ParseInLocation(utils.FormatDate, currDateStr, time.Local)
  259. perValMap := make(map[time.Time]float64)
  260. //前3年当日的数据
  261. for i := 1; i <= 3; i++ {
  262. tmpDateTime := currDate.AddDate(-i, 0, 0)
  263. if tmpVal, ok := handleDataMap[tmpDateTime.Format(utils.FormatDate)]; ok {
  264. perValMap[tmpDateTime] = tmpVal
  265. }
  266. }
  267. lenPerValMap := len(perValMap)
  268. // 如果数据少于2年,那么就不参与计算,结束当前循环,进入下一个循环
  269. if lenPerValMap < 2 {
  270. continue
  271. }
  272. // N年 当前值占全年比重 的值列表
  273. divValList := make([]decimal.Decimal, 0)
  274. for tmpDateTime, tmpVal := range perValMap {
  275. yearLastVal, ok2 := yearLastValMap[tmpDateTime.Year()]
  276. // 如果当年最后一天没有数据
  277. if !ok2 {
  278. continue
  279. }
  280. // 当前值占全年比重
  281. divVal := decimal.NewFromFloat(tmpVal).Div(decimal.NewFromFloat(yearLastVal))
  282. divValList = append(divValList, divVal)
  283. }
  284. lenDivValList := len(divValList)
  285. // 如果 N年 当前值占全年比重 的值 小于 2个,那么就不参与计算,结束当前循环,进入下一个循环
  286. if lenDivValList < 2 {
  287. continue
  288. }
  289. divValSum := decimal.NewFromFloat(0)
  290. for _, divVal := range divValList {
  291. divValSum = divValSum.Add(divVal)
  292. }
  293. // 当前计算出来的结果
  294. currVal, _ := decimal.NewFromFloat(v.Value).Div(divValSum.Div(decimal.NewFromInt(int64(lenDivValList)))).Round(4).Float64()
  295. // 给实际日期数据的值赋值
  296. if fromEdbInfo.LatestDate == currDateStr {
  297. latestValue = currVal
  298. }
  299. // 判断年化指标是否存在数据
  300. if existData, ok := existDataMap[currDateStr]; ok {
  301. // 处理年化数据的值
  302. existValStr := existData.Value
  303. existValDeci, tmpErr := decimal.NewFromString(existValStr)
  304. if tmpErr != nil {
  305. err = tmpErr
  306. return
  307. }
  308. existVal, _ := existValDeci.Round(4).Float64()
  309. // 判断年化数据的值 与 当前计算出来的结果, 如果两个数据结果不相等的话,那么就修改咯
  310. if existVal != currVal {
  311. err = ModifyEdbDataById(source, subSource, existData.EdbDataId, fmt.Sprint(currVal))
  312. if err != nil {
  313. return
  314. }
  315. }
  316. } else {
  317. // 直接入库
  318. timestamp := currDate.UnixNano() / 1e6
  319. timestampStr := fmt.Sprintf("%d", timestamp)
  320. addSql += GetAddSql(edbInfoIdStr, edbCode, currDateStr, timestampStr, fmt.Sprint(currVal))
  321. isAdd = true
  322. }
  323. delete(removeDateMap, currDateStr)
  324. }
  325. if isAdd {
  326. addSql = strings.TrimRight(addSql, ",")
  327. _, err = to.Raw(addSql).Exec()
  328. }
  329. // 移除不存在的日期数据
  330. if len(removeDateMap) > 0 {
  331. removeDateList := make([]string, 0) //需要移除的日期
  332. for k := range removeDateMap {
  333. removeDateList = append(removeDateList, k)
  334. }
  335. removeDateStr := strings.Join(removeDateList, `","`)
  336. removeDateStr = `"` + removeDateStr + `"`
  337. sql := fmt.Sprintf(` DELETE FROM %s WHERE edb_info_id = ? and data_time in (%s) `, tableName, removeDateStr)
  338. _, err = to.Raw(sql, edbInfoId).Exec()
  339. if err != nil {
  340. err = fmt.Errorf("删除年化指标数据失败,Err:" + err.Error())
  341. return
  342. }
  343. }
  344. return
  345. }