我可以计算特定结束日期的RSI:
DECLARE @StartingDate smalldatetime
DECLARE @EndingDate smalldatetime
DECLARE @StockID char(15)
DECLARE @DAYS INT
DECLARE @AG FLOAT
DECLARE @AL FLOAT
DECLARE @RS FLOAT
SET @StartingDate = '20180301'
SET @EndingDate = '20180403'
SET @StockID = 'ACE'
SET @DAYS = 14
SET @AG =(
SELECT SUM([px_close]-[px_open])
FROM [dbo].[daily_data]
WHERE [Ticker] = @STOCKID
AND ([Date] BETWEEN @StartingDate AND @EndingDate)
AND ([px_close]-[px_open])>0)/@DAYS
SET @AL =(
SELECT SUM([px_close]-[px_open])
FROM [dbo].[daily_data]
WHERE [Ticker] = @STOCKID
AND ([Date] BETWEEN @StartingDate AND @EndingDate)
AND ([px_close]-[px_open])<0)/@DAYS
SET @RS = @AG/ABS(@AL)
SELECT @StockID AS Ticker, @EndingDate AS Date, 100 - (100/(1+@RS)) RSI
这是我的输出:
Ticker Date RSI
ACE 2018-04-03 48.7307
如何计算多个日期和多个代码的RSI?
答案 0 :(得分:0)
您无需将所有这些设置为变量。您只需将日期和股票代码添加到组中,并避免使用多余的子查询......例如:
SELECT
[Ticker]
,[Date]
,AG = SUM(case when (isnull([px_close],0)-isnull([px_open],0))>0 then (isnull([px_close],0)-isnull([px_open],0)) end) / @days
,AL = SUM(case when (isnull([px_close],0)-isnull([px_open],0))<0 then (isnull([px_close],0)-isnull([px_open],0)) end) / @days
,RS = (SUM(case when (isnull([px_close],0)-isnull([px_open],0))>0 then (isnull([px_close],0)-isnull([px_open],0)) end) / @days) / ABS(SUM(case when (isnull([px_close],0)-isnull([px_open],0))<0 then (isnull([px_close],0)-isnull([px_open],0)) end) / @days)
,RSI = 100 - (100/(1+(SUM(case when (isnull([px_close],0)-isnull([px_open],0))>0 then (isnull([px_close],0)-isnull([px_open],0)) end) / @days) / ABS(SUM( case when (isnull([px_close],0)-isnull([px_open],0))<0 then (isnull([px_close],0)-isnull([px_open],0)) end) / @days)))
FROM
[dbo].[daily_data]
WHERE
[Ticker] = @STOCKID
AND ([Date] BETWEEN @StartingDate AND @EndingDate)
group by
[Ticker],[Date]
从where子句中删除[Ticker] = @STOCKID
以返回所有代码