尝试使用BigQuery计算EMA(指数移动平均线)

时间:2014-07-05 21:42:01

标签: google-bigquery

我正在尝试计算股票价格的指数移动平均线(EMA)。我使用公式来计算此网站的EMA:http://www.iexplain.org/ema-how-to-calculate/

我完全不知道计算正确的EMA。查询运行并返回结果,但不返回准确的EMA。非常感谢帮助。您可以看到尝试使用从第4行开始的EMA公式计算EMA。

SELECT current_day.date as current_date, current_day.avg_price as current_date_price,       
prev_day.prev_avg_price as previous_date_price, prev_2_day.prev_avg_price,

(  ( current_day.avg_price * (2 / (22 + 1) ) ) +  ( ( ( prev_day.prev_avg_price * (2 / (22     
+ 1) ) ) +   
( prev_2_day.prev_avg_price * (2 / (22 + 1) ) ) ) * (1 -( 2 / (22 + 1) ) ) ) ) as EMA


FROM
(select DATE(time) as date, ROUND(AVG(price),2) as avg_price FROM ds_5.tb_4978 group by     
date) as    
current_day
JOIN
(select DATE(USEC_TO_TIMESTAMP(time- 86400000000)) as prev_date, ROUND(AVG(price),2) as    
prev_avg_price from ds_5.tb_4978 GROUP BY prev_date) as prev_day
ON current_day.date=prev_day.prev_date

JOIN
(select DATE(USEC_TO_TIMESTAMP(time- (86400000000*2))) as prev_2_date, ROUND(AVG(price),2)     
as    
prev_avg_price from ds_5.tb_4978 GROUP BY prev_2_date) as prev_2_day
ON current_day.date=prev_2_day.prev_2_date

GROUP  BY current_date, current_date_price, previous_date_price,    
prev_2_day.prev_avg_price, EMA

这是来自上述查询的json响应:https://json.datadives.com/01843e08d5127e9d26d03fe0f842e735.json

2 个答案:

答案 0 :(得分:2)

我不认为你前一天需要avg_price。您需要在前一天进行EMA。

enter image description here

我宁愿预先计算EMA;如果不可能,可以查看MapReduce。

答案 1 :(得分:1)

这不是一个完整的答案,但是你可以使用LEAD()函数来获取前一天的时间和价格,而不是做多个连接,而不是自我JOIN来获取当前日期和上一个日期。 。这可以带来更自然的代码和更快的查询。

例如:

SELECT <calculate avg here> FROM (
SELECT DATE(time) as date, ROUND(AVG(price),2) as avg_price, 
  LEAD(time, 1) OVER (ORDER BY time DESC) as prev_day_time,
  LEAD(price, 1) OVER (ORDER BY time DESC) as prev_price,
  LEAD(time, 2) OVER (ORDER BY time DESC) as prev_2_day_time,
  LEAD(price, 2) OVER (ORDER BY time DESC) as prev_2_price,  
FROM [...])

那说只有你有一个有限的移动平均线才有效(即你只是跟踪过去N天的移动平均线。如果你试图无限期地连接移动平均线,那么SQL不会是一个很好的解决方案。