edb_data_calculate_phase_shift.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404
  1. package models
  2. import (
  3. "errors"
  4. "eta/eta_index_lib/utils"
  5. "fmt"
  6. "github.com/beego/beego/v2/client/orm"
  7. "strconv"
  8. "strings"
  9. "time"
  10. )
  11. // AddCalculatePhaseShift 期数移位
  12. func AddCalculatePhaseShift(req *EdbInfoCalculateBatchSaveReq, fromEdbInfo *EdbInfo, edbCode, uniqueCode string, sysUserId int, sysUserRealName string) (edbInfo *EdbInfo, err error) {
  13. o := orm.NewOrm()
  14. to, err := o.Begin()
  15. if err != nil {
  16. return
  17. }
  18. defer func() {
  19. if err != nil {
  20. fmt.Println("AddCalculatePhaseShift,Err:" + err.Error())
  21. _ = to.Rollback()
  22. } else {
  23. _ = to.Commit()
  24. }
  25. }()
  26. // 前端那边让后端处理。。。
  27. if req.Frequency == "日度" && req.MoveFrequency == "" {
  28. return nil, errors.New("日度指标,移动频率不能为空")
  29. }
  30. switch req.Frequency {
  31. case "周度":
  32. req.MoveFrequency = "周"
  33. case "旬度":
  34. req.MoveFrequency = "旬"
  35. case "月度":
  36. req.MoveFrequency = "月"
  37. case "季度":
  38. req.MoveFrequency = "季"
  39. case "半年度":
  40. req.MoveFrequency = "半年"
  41. case "年度":
  42. req.MoveFrequency = "年"
  43. }
  44. if req.EdbInfoId <= 0 {
  45. edbInfo = new(EdbInfo)
  46. edbInfo.Source = utils.DATA_SOURCE_CALCULATE_PHASE_SHIFT
  47. edbInfo.SourceName = "期数移位"
  48. edbInfo.EdbCode = edbCode
  49. edbInfo.EdbName = req.EdbName
  50. edbInfo.EdbNameSource = req.EdbName
  51. edbInfo.Frequency = req.Frequency
  52. edbInfo.Unit = req.Unit
  53. edbInfo.ClassifyId = req.ClassifyId
  54. edbInfo.SysUserId = sysUserId
  55. edbInfo.SysUserRealName = sysUserRealName
  56. edbInfo.CreateTime = time.Now()
  57. edbInfo.ModifyTime = time.Now()
  58. edbInfo.UniqueCode = uniqueCode
  59. edbInfo.CalculateFormula = req.Formula
  60. edbInfo.EdbNameEn = req.EdbName
  61. edbInfo.UnitEn = req.Unit
  62. edbInfo.EdbType = 2
  63. edbInfo.Sort = GetAddEdbMaxSortByClassifyId(req.ClassifyId, utils.EDB_INFO_TYPE)
  64. edbInfo.MoveType = req.MoveType
  65. edbInfo.MoveFrequency = req.MoveFrequency
  66. newEdbInfoId, tmpErr := to.Insert(edbInfo)
  67. if tmpErr != nil {
  68. err = tmpErr
  69. return
  70. }
  71. edbInfo.EdbInfoId = int(newEdbInfoId)
  72. //关联关系
  73. {
  74. calculateMappingItem := new(EdbInfoCalculateMapping)
  75. calculateMappingItem.CreateTime = time.Now()
  76. calculateMappingItem.ModifyTime = time.Now()
  77. calculateMappingItem.Sort = 1
  78. calculateMappingItem.EdbCode = edbCode
  79. calculateMappingItem.EdbInfoId = edbInfo.EdbInfoId
  80. calculateMappingItem.FromEdbInfoId = fromEdbInfo.EdbInfoId
  81. calculateMappingItem.FromEdbCode = fromEdbInfo.EdbCode
  82. calculateMappingItem.FromEdbName = fromEdbInfo.EdbName
  83. calculateMappingItem.FromSource = fromEdbInfo.Source
  84. calculateMappingItem.FromSourceName = fromEdbInfo.SourceName
  85. calculateMappingItem.FromTag = ""
  86. calculateMappingItem.Source = edbInfo.Source
  87. calculateMappingItem.SourceName = edbInfo.SourceName
  88. calculateMappingItem.FromSubSource = edbInfo.SubSource
  89. _, err = to.Insert(calculateMappingItem)
  90. if err != nil {
  91. return
  92. }
  93. }
  94. } else {
  95. edbInfo, err = GetEdbInfoById(req.EdbInfoId)
  96. if err != nil {
  97. return
  98. }
  99. dataTableName := GetEdbDataTableName(utils.DATA_SOURCE_CALCULATE_PHASE_SHIFT, utils.DATA_SUB_SOURCE_EDB)
  100. fmt.Println("dataTableName:" + dataTableName)
  101. deleteSql := ` DELETE FROM %s WHERE edb_info_id=? `
  102. deleteSql = fmt.Sprintf(deleteSql, dataTableName)
  103. _, err = to.Raw(deleteSql, req.EdbInfoId).Exec()
  104. if err != nil {
  105. return
  106. }
  107. }
  108. formulaInt, _ := strconv.Atoi(req.Formula)
  109. //计算数据
  110. err = refreshAllCalculatePhaseShift(to, edbInfo.EdbInfoId, edbInfo.Source, edbInfo.SubSource, formulaInt, edbInfo.MoveType, fromEdbInfo, edbInfo.EdbCode, "", "", edbInfo.MoveFrequency)
  111. return
  112. }
  113. // EditCalculatePhaseShift 修改期数移位
  114. func EditCalculatePhaseShift(edbInfo *EdbInfo, req *EdbInfoCalculateBatchEditReq, fromEdbInfo *EdbInfo) (err error) {
  115. o := orm.NewOrm()
  116. to, err := o.Begin()
  117. if err != nil {
  118. return
  119. }
  120. defer func() {
  121. if err != nil {
  122. fmt.Println("EditCalculatePhaseShift,Err:" + err.Error())
  123. _ = to.Rollback()
  124. } else {
  125. _ = to.Commit()
  126. }
  127. }()
  128. switch req.Frequency {
  129. case "周度":
  130. req.MoveFrequency = "周"
  131. case "旬度":
  132. req.MoveFrequency = "旬"
  133. case "月度":
  134. req.MoveFrequency = "月"
  135. case "季度":
  136. req.MoveFrequency = "季"
  137. case "半年度":
  138. req.MoveFrequency = "半年"
  139. case "年度":
  140. req.MoveFrequency = "年"
  141. }
  142. oldEdbInfo := *edbInfo //旧的指标信息
  143. //修改指标信息
  144. edbInfo.EdbName = req.EdbName
  145. edbInfo.EdbNameSource = req.EdbName
  146. edbInfo.Frequency = req.Frequency
  147. edbInfo.Unit = req.Unit
  148. edbInfo.ClassifyId = req.ClassifyId
  149. edbInfo.MoveType = req.MoveType
  150. edbInfo.MoveFrequency = req.MoveFrequency
  151. edbInfo.CalculateFormula = req.Formula
  152. edbInfo.EdbNameEn = req.EdbNameEn
  153. edbInfo.UnitEn = req.UnitEn
  154. edbInfo.ModifyTime = time.Now()
  155. _, err = to.Update(edbInfo, "EdbName", "EdbNameSource", "Frequency", "Unit", "ClassifyId", "MoveType", "MoveFrequency", "CalculateFormula", "ModifyTime", "EdbNameEn", "UnitEn")
  156. if err != nil {
  157. return
  158. }
  159. //判断计算指标是否被更换
  160. var existCondition string
  161. var existPars []interface{}
  162. existCondition += " AND edb_info_id=? AND from_edb_info_id=? "
  163. existPars = append(existPars, edbInfo.EdbInfoId, req.FromEdbInfoId)
  164. count, err := GetEdbInfoCalculateCountByCondition(existCondition, existPars)
  165. if err != nil {
  166. err = errors.New("判断指标是否改变失败,Err:" + err.Error())
  167. return
  168. }
  169. if count <= 0 || req.MoveType != oldEdbInfo.MoveType || req.MoveFrequency != oldEdbInfo.MoveFrequency || req.Formula != oldEdbInfo.CalculateFormula {
  170. //如果是依赖指标变更,那么需要删除对应的关联指标,并添加新的关系
  171. if count <= 0 {
  172. //删除,计算指标关联的,基础指标的关联关系
  173. sql := ` DELETE FROM edb_info_calculate_mapping WHERE edb_info_id = ? `
  174. _, err = to.Raw(sql, edbInfo.EdbInfoId).Exec()
  175. if err != nil {
  176. err = errors.New("删除计算指标关联关系失败,Err:" + err.Error())
  177. return
  178. }
  179. //关联关系
  180. {
  181. calculateMappingItem := &EdbInfoCalculateMapping{
  182. EdbInfoCalculateMappingId: 0,
  183. EdbInfoId: edbInfo.EdbInfoId,
  184. Source: utils.DATA_SOURCE_CALCULATE_PHASE_SHIFT,
  185. SourceName: "期数移位",
  186. EdbCode: edbInfo.EdbCode,
  187. FromEdbInfoId: fromEdbInfo.EdbInfoId,
  188. FromEdbCode: fromEdbInfo.EdbCode,
  189. FromEdbName: fromEdbInfo.EdbName,
  190. FromSource: fromEdbInfo.Source,
  191. FromSourceName: fromEdbInfo.SourceName,
  192. FromTag: "",
  193. Sort: 1,
  194. CreateTime: time.Now(),
  195. ModifyTime: time.Now(),
  196. FromSubSource: fromEdbInfo.SubSource,
  197. }
  198. _, err = to.Insert(calculateMappingItem)
  199. if err != nil {
  200. return
  201. }
  202. }
  203. }
  204. //清空原有数据
  205. sql := ` DELETE FROM edb_data_calculate_phase_shift WHERE edb_info_id = ? `
  206. _, err = to.Raw(sql, edbInfo.EdbInfoId).Exec()
  207. if err != nil {
  208. return
  209. }
  210. //计算数据
  211. formulaInt, _ := strconv.Atoi(req.Formula)
  212. err = refreshAllCalculatePhaseShift(to, edbInfo.EdbInfoId, edbInfo.Source, edbInfo.SubSource, formulaInt, edbInfo.MoveType, fromEdbInfo, edbInfo.EdbCode, "", "", edbInfo.MoveFrequency)
  213. }
  214. return
  215. }
  216. // RefreshAllCalculatePhaseShift 刷新所有时间移位数据
  217. func RefreshAllCalculatePhaseShift(edbInfoId, source, subSource, formulaInt, moveType int, fromEdbInfo *EdbInfo, edbCode, startDate, endDate, moveFrequency string) (err error) {
  218. o := orm.NewOrm()
  219. to, err := o.Begin()
  220. if err != nil {
  221. return
  222. }
  223. defer func() {
  224. if err != nil {
  225. fmt.Println("RefreshAllCalculatePhaseShift,Err:" + err.Error())
  226. _ = to.Rollback()
  227. } else {
  228. _ = to.Commit()
  229. }
  230. }()
  231. //清空原有数据
  232. sql := ` DELETE FROM edb_data_calculate_phase_shift WHERE edb_info_id = ? `
  233. _, err = to.Raw(sql, edbInfoId).Exec()
  234. if err != nil {
  235. return
  236. }
  237. //计算数据
  238. err = refreshAllCalculatePhaseShift(to, edbInfoId, source, subSource, formulaInt, moveType, fromEdbInfo, edbCode, startDate, endDate, moveFrequency)
  239. return
  240. }
  241. // refreshAllCalculatePhaseShift 刷新所有时间移位数据
  242. func refreshAllCalculatePhaseShift(to orm.TxOrmer, edbInfoId, source, subSource, formulaInt, moveType int, fromEdbInfo *EdbInfo, edbCode, startDate, endDate, moveFrequency string) (err error) {
  243. edbInfoIdStr := strconv.Itoa(edbInfoId)
  244. //计算数据
  245. dataList, err := GetEdbDataListAllByTo(to, fromEdbInfo.Source, fromEdbInfo.SubSource, FindEdbDataListAllCond{
  246. EdbInfoId: fromEdbInfo.EdbInfoId,
  247. StartDataTime: startDate,
  248. StartDataTimeCond: ">=",
  249. }, 0)
  250. if err != nil {
  251. return err
  252. }
  253. var dateArr []string
  254. dataMap := make(map[string]*EdbInfoSearchData)
  255. for _, v := range dataList {
  256. dateArr = append(dateArr, v.DataTime)
  257. dataMap[v.DataTime] = v
  258. }
  259. fmt.Println("source:", source)
  260. //获取指标所有数据
  261. existDataList := make([]*EdbData, 0)
  262. dataTableName := GetEdbDataTableName(source, subSource)
  263. fmt.Println("dataTableName:", dataTableName)
  264. sql := `SELECT * FROM %s WHERE edb_info_id=? `
  265. sql = fmt.Sprintf(sql, dataTableName)
  266. _, err = to.Raw(sql, edbInfoId).QueryRows(&existDataList)
  267. if err != nil {
  268. return err
  269. }
  270. existDataMap := make(map[string]string)
  271. removeDateMap := make(map[string]string)
  272. for _, v := range existDataList {
  273. existDataMap[v.DataTime] = v.Value
  274. removeDateMap[v.DataTime] = ``
  275. }
  276. fmt.Println("existDataMap:", existDataMap)
  277. addSql := ` INSERT INTO edb_data_calculate_phase_shift(edb_info_id,edb_code,data_time,value,create_time,modify_time,data_timestamp) values `
  278. var isAdd bool
  279. resultMap := make(map[string]float64)
  280. dataLen := len(dataList)
  281. var moveNum int
  282. for i := 0; i < dataLen; i++ {
  283. // step_1 如果 领先/滞后 之后时间key存在,将该key为目标key,填充
  284. currentIndex := dataList[i]
  285. // 领先
  286. if moveType != 2 {
  287. periods := dataLen - i + formulaInt - 1
  288. if periods < dataLen {
  289. newIndex := dataList[dataLen-periods-1]
  290. resultMap[newIndex.DataTime] = currentIndex.Value
  291. } else {
  292. moveNum = formulaInt - i
  293. // 新数据须根据频度补充key
  294. currentDate, _ := time.ParseInLocation(utils.FormatDate, dataList[0].DataTime, time.Local)
  295. shiftDay := CalculateIntervalDays(moveFrequency, moveNum, currentDate, resultMap, moveType)
  296. var newDate time.Time
  297. if moveFrequency == "年" {
  298. newDate = currentDate.AddDate(moveNum, 0, 0)
  299. } else {
  300. newDate = currentDate.AddDate(0, 0, shiftDay)
  301. }
  302. format := newDate.Format(utils.FormatDate)
  303. resultMap[format] = currentIndex.Value
  304. }
  305. } else {
  306. // 滞后
  307. periods := dataLen - i - formulaInt
  308. if periods > 0 {
  309. newIndex := dataList[dataLen-periods]
  310. resultMap[newIndex.DataTime] = currentIndex.Value
  311. } else {
  312. moveNum = formulaInt + 1 - (dataLen - i)
  313. // 新数据须根据频度补充key
  314. currentDate, _ := time.ParseInLocation(utils.FormatDate, dataList[dataLen-1].DataTime, time.Local)
  315. shiftDay := CalculateIntervalDays(moveFrequency, moveNum, currentDate, resultMap, moveType)
  316. var newDate time.Time
  317. if moveFrequency == "年" {
  318. newDate = currentDate.AddDate(-moveNum, 0, 0)
  319. } else {
  320. newDate = currentDate.AddDate(0, 0, -shiftDay)
  321. }
  322. format := newDate.Format(utils.FormatDate)
  323. resultMap[format] = currentIndex.Value
  324. }
  325. }
  326. }
  327. for key, value := range resultMap {
  328. currentDate, _ := time.ParseInLocation(utils.FormatDate, key, time.Local)
  329. timestamp := currentDate.UnixNano() / 1e6
  330. timestampStr := fmt.Sprintf("%d", timestamp)
  331. addSql += GetAddSql(edbInfoIdStr, edbCode, key, timestampStr, fmt.Sprintf("%f", value))
  332. isAdd = true
  333. }
  334. if isAdd {
  335. addSql = strings.TrimRight(addSql, ",")
  336. _, err = to.Raw(addSql).Exec()
  337. if err != nil {
  338. return
  339. }
  340. }
  341. return
  342. }
  343. func CalculateIntervalDays(moveFrequency string, formulaInt int, baseDate time.Time, resultMap map[string]float64, moveType int) int {
  344. var shiftDay int
  345. switch moveFrequency {
  346. case "自然日":
  347. shiftDay = formulaInt
  348. case "交易日":
  349. shiftDay = utils.CalculateTradingDays(baseDate, formulaInt, resultMap, moveType)
  350. case "周":
  351. shiftDay = formulaInt * 7
  352. case "旬":
  353. shiftDay = utils.CalculateDekadTime(baseDate, formulaInt, moveType)
  354. case "月":
  355. shiftDay = utils.CalculateEndOfMonth(baseDate, formulaInt, moveType)
  356. case "季":
  357. shiftDay = utils.CalculateEndOfQuarter(baseDate, formulaInt, moveType)
  358. case "半年":
  359. shiftDay = utils.CalculateEndOfHalfYear(baseDate, formulaInt, moveType)
  360. case "年":
  361. shiftDay = utils.CalculateEndOfYear(baseDate, formulaInt, moveType)
  362. default:
  363. shiftDay = formulaInt
  364. }
  365. return shiftDay
  366. }