我在SAS还是个新手,我想知道如何才能做到以下几点:
假设我有一个包含以下信息的数据库:
Time_during_the day date prices volume_traded
930am sep02 42 300
10am sep02 41 200
..4pm sep02 40 200
930am sep03 40 500
10am sep03 41 100
..4pm sep03 40 350
.....我想要的是取每日总成交量的平均值,并将这个数字除以50 (总是)。假设avg.daily vol./50 = V;,我想要的是记录每隔一段时间的价格/时间/日期。现在,假设是V=500,我首先在我的数据库中记录第一个价格,时间和日期,然后记录相同的信息500成交量交易。有可能在某一天的交易量是300,其中一半将覆盖v=500,其余的150将用于填满下一段时间。
如何在一个数据库中获取此信息?谢谢!
发布于 2012-06-14 02:18:28
假设您的输入数据集名为tick_data,并且同时按date和time_during_the_day排序。下面是我得到的信息:
%LET n = 50;
/* Calculate V - the breakpoint size */
PROC SUMMARY DATA=tick_data;
BY date;
OUTPUT OUT = temp_1
SUM (volume_traded)= volume_traded_agg;
RUN;
DATA temp_2 ;
SET temp_1;
V = volume_traded_agg / &n;
RUN;
/* Merge it into original dataset so that it is available */
DATA temp_3;
MERGE tick_data temp_2;
BY date;
RUN;
/* Final walk through tick data to output at breakpoints */
DATA results
/* Comment out the KEEP to see what is happening under the hood */
(KEEP=date time_during_the_day price volume_traded)
;
SET temp_3;
/* The IF FIRST will not work without the BY below */
BY date;
/* Stateful counters */
RETAIN
volume_cumulative
breakpoint_next
breakpoint_counter
;
/* Reset stateful counters at the beginning of each day */
IF (FIRST.date) THEN DO;
volume_cumulative = 0;
breakpoint_next = V;
breakpoint_counter = 0;
END;
/* Breakpoint test */
volume_cumulative = volume_cumulative + volume_traded;
IF (breakpoint_counter <= &n AND volume_cumulative >= breakpoint_next) THEN DO;
OUTPUT;
breakpoint_next = breakpoint_next + V;
breakpoint_counter = breakpoint_counter + 1;
END;
RUN;未来需要牢记的关键SAS语言特性是同时使用BY、FIRST和RETAIN。这使得可以像这样有状态地遍历数据。条件OUTPUT在这里也是如此。
请注意,无论何时使用BY <var>,都必须根据包含<var>的键对dataset进行排序。在tick_data和所有中间临时表的情况下,它是。
附加:备选V
为了使V等于(平均每日总体积/ n),请将上面的匹配代码块替换为以下代码块:
. . . . . .
/* Calculate V - the breakpoint size */
PROC SUMMARY DATA=tick_data;
BY date;
OUTPUT OUT = temp_1
SUM (volume_traded)= volume_traded_agg;
RUN;
PROC SUMMARY DATA = temp_1
OUTPUT OUT = temp_1a
MEAN (volume_traded_agg) =;
RUN;
DATA temp_2 ;
SET temp_1a;
V = volume_traded_agg / &n;
RUN;
/* Merge it into original dataset so that it is available */
DATA temp_3 . . . . . .
. . . . . . 基本上,您只需插入第二个PROC SUMMARY来取和的平均值。注意,这里没有BY语句,因为我们是在整个集合上求平均值,而不是按任何分组或桶。还要注意在=之后没有名称的MEAN (...) =。这将使输出变量与输入变量具有相同的名称。
https://stackoverflow.com/questions/11011439
复制相似问题