私が考えることができる 3 つのオプションは、(1) 転置してデータ ステップ配列を使用する、(2) 2 つのアンパサンド マクロ配列を使用する、(3) ハッシュ オブジェクトを作成する、です。ハッシュはおそらくあなたの最善の策です。これはハッシュの良い紹介です。
リテインを使おうと思ったのですが、売買の際に、売買した価格を含まない最大売値と最小買値を再計算する必要があるように見えるので、うまくいかないと思います。
編集::以下は、ハッシュを使用してこれを機能させる方法です。まず、販売用と購入用の 2 つのデータセットを設定します。次に、次のデータステップで、両方をハッシュ オブジェクトに変換します。何かが売買されるときにハッシュオブジェクトを参照して、需要/供給量を更新し、その価格での新しい最良の価格と数量を見つけます。
data hashset (keep=time2 buyprice2 ntobuy2 sellprice2 ntosell2);
set book2;
buyprice2=buyprice; ntobuy2=ntobuy; sellprice2=sellprice; ntosell2=ntosell; time2=time;
if (buyprice2 ne .) or (sellprice2 ne .) then output;
run;
data bestprices;
retain time buyprice ntobuy sellprice ntosell buy sell bestbuy nbestbuy tbestbuy bestsell nbestsell tbestsell;
set book2 end=setdone;
if _n_ = 1 then do;
*Set up hash hh, which contains the data in the data set hashset, with the key time2;
set hashset;
declare hash hh(dataset:'hashset', ordered:'a');
hh.definekey('time2');
hh.definedata(all:'yes');
hh.definedone();
declare hiter hiter('hh'); *Hash iterator allows iterating through the hash;
end;
*Buy section;
if (buyprice ne . and ((bestbuy=.) or (bestbuy>buyprice))) then do;
bestbuy=buyprice; nbestbuy=ntobuy; tbestbuy=time;
end;
bamper=index(buy, '@');
if bamper>0 then do;
time2=tbestbuy;
num=substr(buy, 1, bamper-1)*1;
if hh.find()=0 then do;
ntobuy2=ntobuy2-num;
hh.replace();
found=0;
rc=hiter.first();
do while(rc=0);
if (ntobuy2>0) and (time2<time) and ((found=0) or (bestbuy>buyprice2)) then do;
found=1;
bestbuy=buyprice2; nbestbuy=ntobuy2; tbestbuy=time2;
end;
rc=hiter.next();
end;
end;
end;
*Sell section;
if (sellprice ne . and ((bestsell=.) or (bestsell<sellprice))) then do;
bestsell=sellprice; nbestsell=ntosell; tbestsell=time;
end;
samper=index(sell, '@');
if samper>0 then do;
time2=tbestsell;
num=substr(sell, 1, samper-1)*1;
if hh.find()=0 then do;
ntosell2=ntosell2-num;
hh.replace();
found=0;
rc=hiter.first();
do while(rc=0);
if (ntosell2>0) and (time2<time) and ((found=0) or (bestsell<sellprice2)) then do;
found=1;
bestsell=sellprice2; nbestsell=ntosell2; tbestsell=time2;
end;
rc=hiter.next();
end;
end;
end;
keep time buyprice ntobuy sellprice ntosell buy sell bestbuy nbestbuy bestsell nbestsell;
if setdone then hh.output(dataset:'hh');
run;
初期データセットを設定するために使用したコードを次に示します。すでにデータセットを持っているので必要ありませんが、参考までに:
data book;
input buyprice sellprice buy $ sell $ ntobuy ntosell ;
datalines;
80 78 na na 10 13
80.5 79.5 na na 12 15
80.4 . na na 11 .
81 . na na 13 .
80.1 78.1 na na 12 11
80.2 77 na na 11 12
82 76 na na 14 11
. . 9@80 na . .
. . 1@80 na . .
. 78.5 na na . 12
. . na 4@79.5 . .
. 79 na na . 14
79.5 79.1 na na 10 13
. . na 11@79.5 . .
79.4 . na na 5 .
run;
data book;
retain time;
set book;
time = _n_;
if buy = 'na' then buy = '';
if sell = 'na' then sell = '';
run;