Better output generation

This commit is contained in:
Taha Afzal committed 2020-01-09 11:28:41 -05:00
1 parent 2c3e4b7d4d
commit bb70db70b5
9 files changed
+150 -126

No files matched your search

@@ -16,14 +16,14 @@ namespace bts.history{
}
public BookSeries(IEnumerable<ProcessedBook> pbooks,
bool remove_duplicate_tops=false){
_books = _to_book_entries(pbooks, remove_duplicate_tops);
bool merge_duplicates_tops=false){
_books = _to_book_entries(pbooks, merge_duplicates_tops);
}
static List<BookEntry> _to_book_entries(IEnumerable<ProcessedBook> pbooks,
bool remove_duplicate_tops){
if(remove_duplicate_tops)
pbooks = MarketQueriesHelper.remove_duplicates_tops(pbooks);
bool merge_duplicates_tops){
if(merge_duplicates_tops)
pbooks = MarketQueriesHelper.merge_duplicates_tops(pbooks);
var rv = new List<BookEntry>();
for (int i=0; i<pbooks.Count(); i++){
ProcessedBook pb_i = pbooks.ElementAt(i),
@@ -109,7 +109,8 @@ namespace bts.history{
}
// load books from the books csv
public static IDictionary<string,BookSeries> load_books(string symbol,
DateTime dt){
DateTime dt,
bool top_only){
DateTime t1 = DateTime.Now;
string file_name = String.Format("{0}/{1}", get_data_path(dt),
String.Format("{0}_{1}", symbol,"books.csv"));
@@ -119,8 +120,9 @@ namespace bts.history{
string line;
while ((line = sr.ReadLine()) != null){
if(ln_no++>0){
var pbook = _csv_to_processedbook(line);
if(pbook != null){
var pbook = _csv_to_processedbook(line,true,top_only);
if(pbook != null){
MarketQueriesHelper.fill_exponent(symbol,pbook);
List<ProcessedBook> contract_books = null;
if(!rv.TryGetValue(pbook.Security,out contract_books)){
contract_books = new List<ProcessedBook>();
@@ -130,7 +132,7 @@ namespace bts.history{
Log.assert(contract_books.Count==0,
String.Format("Illegal sparse book {0}",
pbook.BookSeqNum));
else
else
contract_books.Add(pbook);
}
}
@@ -141,8 +143,9 @@ namespace bts.history{
t1 = DateTime.Now;
foreach (var books in rv.Values)
MarketQueriesHelper.validate_book_series(books);
var ret = rv.ToDictionary(kv => kv.Key, kv => new BookSeries(kv.Value));
Console.WriteLine ("{0} secs to load into book ser",
var ret = rv.ToDictionary(kv => kv.Key, kv => new BookSeries(kv.Value,top_only));
//var ret = rv.ToDictionary(kv => kv.Key, kv => new BookSeries(kv.Value,false));
Console.WriteLine ("{0} secs to load into book ser",
(DateTime.Now - t1).TotalSeconds);
return ret;
}
@@ -200,7 +203,8 @@ namespace bts.history{
private static ProcessedBook _csv_to_processedbook(
string csv_row,
bool only_cal_sprs=true){
bool only_cal_sprs,
bool top_only){
uint n_levels = 10;
uint i = 0;
string[] toks = csv_row.Split(',');
@@ -214,7 +218,8 @@ namespace bts.history{
rv.SendingTime = _parse_time_string(toks[i++]);
rv.TransactTime = _parse_time_string(toks[i++]);
rv.MsgSeqNum = UInt32.Parse(toks[i++]);
for (uint n=0; n<n_levels; n++){
uint iter_levels = top_only ? 1 : n_levels;
for (uint n=0; n<iter_levels; n++){
double b = Double.Parse(toks[i++]);
UInt32 bqty = UInt32.Parse(toks[i++]);
if(bqty == 0)
@@ -223,13 +228,17 @@ namespace bts.history{
}
i = sec_idx;
rv.Security = toks[i++];
for (uint n=0; n<n_levels; n++){
for (uint n=0; n<iter_levels; n++){
double a = Double.Parse(toks[i++]);
UInt32 aqty = UInt32.Parse(toks[i++]);
if(aqty == 0)
break;
rv.Book.Asks.Add(MarketQueriesHelper.to_pricesize(a,aqty));
}
if(rv.Book.Bids.Count == 0)
rv.Book.Bids.Add(MarketQueriesHelper.to_pricesize(0,0));
if(rv.Book.Asks.Count == 0)
rv.Book.Asks.Add(MarketQueriesHelper.to_pricesize(0,0));
return rv;
}
@@ -282,6 +291,48 @@ namespace bts.history{
return String.Format("{0}{1}:{2}{3}", '"',time_secs,nsecs,'"');
}
private static string _array_to_string<T> (IEnumerable<T> entries){
string rv = String.Empty;
foreach(var o in entries)
rv += String.Format("{0};",o);
return rv;
}
public static string leg_book_entry_to_csv(BookEntry b){
return string.Format("{0},{1},{2},{3},{4},{5},{6},{7},{8},{9},{10},{11}",
b.PBook.Security,
b.PBook.MsgSeqNum,
b.PBook.BookSeqNum,
MarketQueriesHelper.book_processing_time(b.PBook),
(b.PBook.AbsorbedBooks == null || b.PBook.AbsorbedBooks.Count == 0) ? String.Empty :
String.Format("{0}-{1}",
b.PBook.AbsorbedBooks.First(),
b.PBook.AbsorbedBooks.Last()),
_format_timestamp(b.TimeRange.T1),
_format_timestamp(b.TimeRange.T2),
MarketQueriesHelper.period_ns(b.TimeRange),
MarketQueriesHelper.book_price(b,true,0),
MarketQueriesHelper.book_qty(b,true,0),
MarketQueriesHelper.book_price(b,false,0),
MarketQueriesHelper.book_qty(b,false,0));
}
public static string synthetic_book_entry_to_csv(MarketQueries.SyntheticPrice p){
var b = p.synthetic_book;
var min_max = MarketQueriesHelper.intersection_range_idx(
p.leg_book.Select(lb=>lb.TimeRange).ToArray());
return string.Format("{0},{1},{2},{3},{4},{5},{6},{7},{8}",
b.PBook.Security,
_format_timestamp(b.TimeRange.T1),
_format_timestamp(b.TimeRange.T2),
String.Format("{0}:{1}",min_max.Item1,min_max.Item2),
MarketQueriesHelper.period_ns(b.TimeRange),
MarketQueriesHelper.book_price(b,true,0),
MarketQueriesHelper.book_qty(b,true,0),
MarketQueriesHelper.book_price(b,false,0),
MarketQueriesHelper.book_qty(b,false,0));
}
public static string book_entry_to_csv(BookEntry b){
return string.Format("{0},{1},{2},{3},{4},{5},{6},{7},{8},{9}",
b.PBook.Security,
@@ -299,8 +350,8 @@ namespace bts.history{
public static string synthetic_price_to_csv(MarketQueries.SyntheticPrice p){
string rv = String.Empty;
foreach (var l in p.leg_book)
rv += String.Format("{0},",book_entry_to_csv(l));
rv += book_entry_to_csv(p.synthetic_book);
rv += String.Format("{0},",leg_book_entry_to_csv(l));
rv += synthetic_book_entry_to_csv(p);
return rv;
}
@@ -19,7 +19,7 @@ namespace bts.history{
public SyntheticPrice(IEnumerable<BookEntry> leg_book_a,
BookEntry synthetic_book_a){
leg_book = leg_book_a;
synthetic_book = synthetic_book_a;
synthetic_book = synthetic_book_a;
}
}
public static void get_synthetic_prices(
@@ -51,7 +51,7 @@ namespace bts.history{
top_ask += l.PriceMultiplier * (l.Side == Side.Buy ? a : b);
top_bid_q = Math.Min(top_bid_q, l.Side == Side.Buy ? bq : aq);
top_ask_q = Math.Min(top_ask_q, l.Side == Side.Buy ? aq : bq);
}
}
IntPrice bid_ip = mbts.co2.IntPrice.from_double(top_bid),
ask_ip = mbts.co2.IntPrice.from_double(top_ask);
PriceSizeMessage bid_psm = new PriceSizeMessage();
@@ -84,21 +84,6 @@ namespace bts.history{
#region Alligning Books
// finds all coexisting books in b1_ser and b2_ser
// that exist in tr
public static IEnumerable<Tuple<BookEntry,BookEntry>> find_coexisting_books (
BookSeries bser_1,
BookSeries bser_2,
Timerange tr){
var rv = new List<Tuple<BookEntry,BookEntry>>();
foreach (BookEntry b1_e in bser_1.find_books_in_time_range(tr))
foreach (var b2_e in bser_2.find_books_in_time_range(b1_e.TimeRange))
if(MarketQueriesHelper.intersects(b2_e.TimeRange,tr))
rv.Add(Tuple.Create(b1_e, b2_e));
return rv;
}
public static IEnumerable<IEnumerable<BookEntry>> allign_bookseries(
params BookSeries[] leg_book_serieses){
var rv = new List<IEnumerable<BookEntry>>();
@@ -115,8 +100,9 @@ namespace bts.history{
foreach(var l in curr_vals)
if(l==null)
return false;
var r = MarketQueriesHelper.intersection_range(curr_vals.Select(i=>i.TimeRange).ToArray());
return MarketQueriesHelper.period_ns(r)>0;
// var r = MarketQueriesHelper.intersection_range(curr_vals.Select(i=>i.TimeRange).ToArray());
// return MarketQueriesHelper.period_ns(r)>0;
return true;
};
uint ord = 0;
foreach (var s in leg_book_serieses){
@@ -21,7 +21,7 @@ namespace bts.history{
/////////////////////////////////////////////////////////////////////////
#region time range helpers
private readonly static UInt64 _ref_secs = Convert.ToUInt64(
(new DateTime(DateTime.Now.Year, 1,1) -
(new DateTime(2019, 1,1) -
new DateTime(1970, 1, 1)).TotalSeconds);
public static int compare (Timestamp xt, Timestamp yt){
var rv = xt.Seconds.CompareTo(yt.Seconds);
@@ -47,9 +47,23 @@ namespace bts.history{
public static Timerange intersection_range(params Timerange[] ranges){
Timerange max_t1 = ranges.MaxElement(r => _from_ref_ns(r.T1)),
min_t2 = ranges.MinElement(r => _from_ref_ns(r.T2));
//return new Timerange{max_t1.T1,min_t2.T2);
return new Timerange {T1=max_t1.T1,T2=min_t2.T2};
}
public static Tuple<UInt16,UInt16> intersection_range_idx(
params Timerange[] ranges){
if(ranges.Length == 0)
return null;
UInt16 entry=0, exit=0;
// greatest T1
for (UInt16 i=0; i<ranges.Length; i++)
if(_is_after_or_same(ranges[i].T1, ranges[entry].T1))
entry = i;
// least T2
for (UInt16 i=0; i<ranges.Length; i++)
if(_is_before_or_same(ranges[i].T2, ranges[exit].T2))
exit = i;
return Tuple.Create(entry,exit);
}
public static Timestamp max_timestamp(){
Timestamp ts = new Timestamp();
ts.Seconds = Convert.ToInt64(
@@ -65,18 +79,23 @@ namespace bts.history{
Timestamp y){
return diff_ns(x,y)<=0;
}
private static bool _is_after_or_same (Timestamp x,
Timestamp y){
return !_is_before(x,y);
}
// x-y ns
public static Int64 diff_ns (Timestamp x,
Timestamp y){
return Convert.ToInt64(_from_ref_ns(x))-
Convert.ToInt64(_from_ref_ns(y));
var xns = Convert.ToInt64(_from_ref_ns(x));
var yns = Convert.ToInt64(_from_ref_ns(y));
return xns - yns;
}
private static UInt64 _from_ref_ns (Timestamp ts){
UInt64 secs = Convert.ToUInt64(ts.Seconds),
ns = Convert.ToUInt64(ts.Nanos);
return (secs - _ref_secs)*1000000000 + ns;
}
#endregion
}
#endregion
// temp exponent filling ////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////
@@ -231,31 +250,25 @@ namespace bts.history{
}
#endregion
#region book accessors
public static IEnumerable<ProcessedBook> remove_duplicates(
IEnumerable<ProcessedBook> bser){
List<ProcessedBook> rv = new List<ProcessedBook>();
if (bser.Count()>0)
rv.Add(bser.ElementAt(0));
for(int i=1;i<bser.Count();i++){
var pb_i = bser.ElementAt(i);
if(!compare_books(pb_i.Book, rv.Last().Book))
rv.Add(pb_i);
}
return rv;
}
#region book accessors
// remove entries with same tops and absorbs them
// into the earlier ones
public static IEnumerable<ProcessedBook> remove_duplicates_tops(
public static IEnumerable<ProcessedBook> merge_duplicates_tops(
IEnumerable<ProcessedBook> bser){
List<ProcessedBook> rv = new List<ProcessedBook>();
if (bser.Count()>0)
rv.Add(bser.ElementAt(0));
for(int i=1;i<bser.Count();i++){
var last_v = rv.Last();
var pb = bser.ElementAt(i);
if(!compare_book_tops(rv.Last().Book,pb.Book,false))
rv.Add(pb);
if(!compare_book_tops(last_v.Book,pb.Book,false))
rv.Add(pb);
else{
last_v.Book.Bids[0].Size = Math.Max(last_v.Book.Bids[0].Size,
pb.Book.Bids[0].Size);
last_v.Book.Asks[0].Size = Math.Max(last_v.Book.Asks[0].Size,
pb.Book.Asks[0].Size);
last_v.AbsorbedBooks.Add(pb.BookSeqNum);
}
}
return rv;
}
@@ -330,7 +343,10 @@ namespace bts.history{
var i = vals[level];
return i.Size;
}
public static Int64 book_processing_time (ProcessedBook pb){
return diff_ns(pb.SendingTime,pb.TransactTime);
}
public static void validate_book_series_order (
IEnumerable<ProcessedBook> books){
for(int i=1;i< books.Count();i++){
@@ -35,7 +35,7 @@ namespace bts.history{
string contract = args[3];
UInt32 m1 = UInt32.Parse(args[4]),
m2 = UInt32.Parse(args[5]);
_find_unreactables(symbol,contract,dt);
//_find_unreactables(symbol,contract,dt);
// BookSeries bser = MarketQueriesHelper.get_book_series(symbol,
// contract,
// dt);
@@ -47,33 +47,5 @@ namespace bts.history{
public void analyze(){
}
private static void _analyze_book(){
}
private static void _find_unreactables(string symbol,
string contract,
DateTime dt){
var raw_books = DataIOHelper.get_raw_books(symbol,
contract,
dt);
raw_books = MarketQueriesHelper.remove_duplicates_tops(raw_books);
int i = 0, unreactable_count = 0;
foreach(var pb in raw_books){
i++;
var pb_next = i>=raw_books.Count() ? null :
raw_books.ElementAt(i);
if(pb_next!=null &&
!MarketQueriesHelper.compare_book_tops(pb.Book,
pb_next.Book,
false) &&
MarketQueriesHelper.diff_ns(pb_next.TransactTime,
pb.SendingTime) < 0)
unreactable_count++;
}
Console.Write("{0} out of {1}",unreactable_count,raw_books.Count());
}
}
}
@@ -76,36 +76,36 @@ namespace bts.history{
}
// find coexisting 1 ////////////////////////////////////////////////////
bseries_list.Clear();
add_b(900);
add_b(990);
add_b(1010);
add_b(1015); //3
add_b(1030);
BookSeries bser_2 = new BookSeries (bseries_list);
var coex = MarketQueries.find_coexisting_books(
bser_1,
bser_2,
new Timerange{T1=from_datetime(base_time, 999),
T2=from_datetime(base_time, 1051)});
_compare_seq_no (coex.ElementAt(0),0,1); //1000
_compare_seq_no (coex.ElementAt(1),0,2);
_compare_seq_no (coex.ElementAt(2),0,3);
_compare_seq_no (coex.ElementAt(3),1,3); //1020
_compare_seq_no (coex.ElementAt(4),2,3); //1025
_compare_seq_no (coex.ElementAt(5),2,4); //1025
_compare_seq_no (coex.ElementAt(6),3,4); //1035
_compare_seq_no (coex.ElementAt(7),4,4); //1050
// bseries_list.Clear();
// add_b(900);
// add_b(990);
// add_b(1010);
// add_b(1015); //3
// add_b(1030);
// BookSeries bser_2 = new BookSeries (bseries_list);
// var coex = MarketQueries.find_coexisting_books(
// bser_1,
// bser_2,
// new Timerange{T1=from_datetime(base_time, 999),
// T2=from_datetime(base_time, 1051)});
// _compare_seq_no (coex.ElementAt(0),0,1); //1000
// _compare_seq_no (coex.ElementAt(1),0,2);
// _compare_seq_no (coex.ElementAt(2),0,3);
// _compare_seq_no (coex.ElementAt(3),1,3); //1020
// _compare_seq_no (coex.ElementAt(4),2,3); //1025
// _compare_seq_no (coex.ElementAt(5),2,4); //1025
// _compare_seq_no (coex.ElementAt(6),3,4); //1035
// _compare_seq_no (coex.ElementAt(7),4,4); //1050
MarketQueries.align_bookseries(
l => {
var b1 = l.ElementAt(0);
var b2 = l.ElementAt(1);
var r = MarketQueriesHelper.intersection_type(b1.TimeRange, b2.TimeRange);
Log.assert(r == TimerangeIntersection.INTERSECTION);
},
bser_1,
bser_2);
// MarketQueries.align_bookseries(
// l => {
// var b1 = l.ElementAt(0);
// var b2 = l.ElementAt(1);
// var r = MarketQueriesHelper.intersection_type(b1.TimeRange, b2.TimeRange);
// Log.assert(r == TimerangeIntersection.INTERSECTION);
// },
// bser_1,
// bser_2);
}
public static void test_random_intersection(){
@@ -26,12 +26,9 @@ namespace bts.history{
string symbol = args[1], sspr_arg = String.Empty;
if(args.Count()==3)
sspr_arg = args[2];
DataIOHelper.load_books(symbol,dt);
string path = DataIOHelper.get_algo_path("sniper");
// 2. downloading all market data for symbol, dt
// (reads the book files and downloads them)
Console.WriteLine("Downloading all spread market data");
var spr_book_map = DataIOHelper.get_all_books(symbol,dt);
IDictionary<string,BookSeries> spr_book_map = DataIOHelper.load_books(symbol,dt,true);
Console.WriteLine("Downloaded {0} books",spr_book_map.Count());
// 3. generating circular spreads
Console.WriteLine("Generating circular spreads");
@@ -44,18 +41,19 @@ namespace bts.history{
Console.WriteLine("Generated {0} circular spreads", circ_spreads.Count());
var spread_map = circ_spreads.ToDictionary(
k=>k,
k=>MarketQueriesHelper.parse_synthetic(k));
k=>MarketQueriesHelper.parse_synthetic(k));
StreamWriter tw = new StreamWriter(
String.Format("{0}/{1}_{2}.csv",
path,
DataIOHelper.get_data_path(dt),
symbol,
dt.ToShortDateString().Replace("/","_")));
"sniper"));
// 4. compute the synthetic prices now
foreach (var kv in spread_map)
_evaluate_synthetic(spr_book_map,kv.Value,tw);
tw.Close();
}
public void analyze(){
}
@@ -152,6 +152,7 @@ message ProcessedBook
google.protobuf.Timestamp transact_time = 30;
string security = 40;
co2.BookMessage book = 50;
repeated uint32 absorbed_books = 60;
}
message Timerange{
@@ -101,7 +101,7 @@ void print_msgs(size_t msg_idx, MDIncrementalUpdate const &line,
struct PriceSize {
double price = 0;
int32_t size = 0;
int32_t size = -1;
};
struct Book {