/
Main.scala
1999 lines (1776 loc) · 37.6 KB
/
Main.scala
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import org.openqa.selenium.firefox.FirefoxDriver
import org.openqa.selenium.htmlunit.HtmlUnitDriver
import org.openqa.selenium.By
import org.openqa.selenium.WebElement
import org.apache.commons.io.FileUtils
import java.lang.Thread
import java.text.SimpleDateFormat
import util.Try
import java.util.Date
import java.util.Calendar
import scala.xml.parsing.NoBindingFactoryAdapter
import org.xml.sax.InputSource
import nu.validator.htmlparser.sax.HtmlParser
import nu.validator.htmlparser.common.XmlViolationPolicy
import org.apache.commons.io.FileUtils
import org.apache.commons.io.FilenameUtils
import java.io.File
import java.io.StringReader
import scalikejdbc._, SQLInterpolation._
object RaceScraper {
val mail = "enter your email address"
val password = "enter your password"
def scrape() = {
val driver = new HtmlUnitDriver(false)
//login
driver.get("https://account.netkeiba.com/?pid=login")
driver.findElement(By.name("login_id")).sendKeys(mail)
driver.findElement(By.name("pswd")).sendKeys(password+"\n")
val re = """/race/(\d+)/""".r
val nums =
io.Source.fromFile("race_url.txt").getLines.toList.
map{ s => val re(x) = re.findFirstIn(s).get; x }
val urls = nums.map(s => "http://db.netkeiba.com/race/" + s)
val folder = new File("html")
if (!folder.exists()) folder.mkdir()
var i = 0
nums.zip(urls).map{ case (num, url) =>
i += 1
println(""+i+":downloading "+url)
val file = new File(folder, num + ".html")
if (!file.exists()) {
driver.get(url)
//↓ここあんまり短くしないでね!
Thread.sleep(5000)
val html = driver.getPageSource()
FileUtils.writeStringToFile(file, html)
}
}
}
}
object RowExtractor {
def str2raceInfo(race_info: Array[String]): RaceInfo = {
val DateRe(d) = race_info(8)
RaceInfo(race_info(0),
race_info(1),
race_info(2).toInt,
race_info(3),
race_info(4),
race_info(5),
race_info(6).toInt,
Try(race_info(7).toInt).toOption,
Util.date2sqliteStr(d),
race_info(9),
race_info(10))
}
def str2raceResult(race_id: Int, race_result: Array[String]): RaceResult = {
RaceResult(race_id,
race_result(0),
race_result(1).toInt,
race_result(2).toInt,
race_result(3).split("horse/")(1).takeWhile(_ != '/'),
race_result(4),
race_result(5).toInt,
race_result(6).toDouble,
race_result(7).split("jockey/")(1).takeWhile(_ != '/'),
race_result(8),
race_result(9),
Try(race_result(10).toInt).toOption,
race_result(11),
Try(race_result(12).toDouble).toOption,
Try(race_result(13).toDouble).toOption,
Try(race_result(14).toInt).toOption,
race_result(15),
{ val remark = race_result(18)
if (remark.isEmpty) None else Some(remark) },
race_result(19),
race_result(20).split("trainer/")(1).takeWhile(_ != '/'),
race_result(21).split("owner/")(1).takeWhile(_ != '/'),
Try(race_result(22).toDouble).toOption
)
}
private def parseHtml(html: String) = {
val hp = new HtmlParser
val saxer = new NoBindingFactoryAdapter
hp.setContentHandler(saxer)
hp.parse(new InputSource(new StringReader(html)))
saxer.rootElem
}
def extract()(implicit s: DBSession) = {
val files = new File("html").listFiles().reverse
val entityId = """<a href="/\w+/(\d+)/"[^>]*>[^<]*</a>"""
val oikiriIconLink =
"""<a href="/\?pid=horse_training&id=\d+&rid=\d+"><img src="/style/netkeiba.ja/image/ico_oikiri.gif" border="0" height="13" width="13"/></a>"""
val commentIconLink =
"""<a href="/\?pid=horse_comment&id=\d+&rid=\d+"><img src="/style/netkeiba.ja/image/ico_comment.gif" border="0" height="13" width="13"/></a>"""
def clean(s: String) = {
s.replaceAll("<span>|</span>|<span/>", "").
replaceAll(",", "").
replaceAll(entityId, "$1").
replaceAll(oikiriIconLink, "").
replaceAll(commentIconLink, "")
}
val usefulFiles =
files.
//タイム指数が表示される2006年以降のデータだけ使う
filter(file => FilenameUtils.getBaseName(file.getName).take(4) >= "2006").
//以下のデータは壊れているので除外する。恐らくnetkeiba.comの不具合。
filter(file => FilenameUtils.getBaseName(file.getName) != "200808020398").
filter(file => FilenameUtils.getBaseName(file.getName) != "200808020399").
toArray.
reverse
var i = 0
while (i < usefulFiles.size) {
val file = usefulFiles(i)
i += 1
val lines = io.Source.fromFile(file).getLines.toList
val rdLines = {
lines.
dropWhile(!_.contains("<dl class=\"racedata fc\">")).
takeWhile(!_.contains("</dl>"))
}
val rdHtml = rdLines.mkString + "</dl>"
val (condition, name) = {
val elem = parseHtml(rdHtml)
val condition = elem.\\("span").text
val name = elem.\\("h1").text
(condition, name)
}
val round = file.getName.replace(".html", "").takeRight(2)
def extractDateInfo(lines: Seq[String]) = {
lines.
toList.
dropWhile(!_.contains("<p class=\"smalltxt\">")).
tail.head.replaceAll("<[^>]+>","")
}
val dateInfo = extractDateInfo(lines).trim
val fieldScore = Try{
val rt2Lines = {
lines.
dropWhile(!_.contains("class=\"result_table_02\"")).
takeWhile(!_.contains("</table>"))
}
val rt2Html = rt2Lines.mkString + "</table>"
val text = parseHtml(rt2Html).\\("td").head.text
text.filter(_ != '?').replaceAll("\\(\\s*\\)", "").trim.toInt.toString
}.getOrElse("")
val rt1Lines = {
lines.
dropWhile(s => !s.contains("race_table_01")).
takeWhile(s => !s.contains("/table"))
}
val rt1Html = rt1Lines.mkString.drop(17) + "</table>"
val conditions = {
condition.
split("/").
map(_.replace("天候 :", "").
replace("発走 : ", ""))
}
val raceInfoStr =
(Array(name) ++
(conditions.head.
replaceAll(" ", "").
replaceAll("([^\\d]+)(\\d+)m","$1,$2") +: conditions.tail) ++
Array(round.split(" ").head, fieldScore) ++
{ val di = dateInfo.split(" ")
di.take(2) :+ di.drop(2).mkString(" ") }).
map(_.filter(_ != '?').replaceAll("(^\\h*)|(\\h*$)","")).
mkString(",").split(",")
val raceInfo = str2raceInfo(raceInfoStr)
RaceInfoDao.insert(raceInfo)
val lastRowId = RaceInfoDao.lastRowId()
val payoffLines = {
lines.
dropWhile(!_.contains("<dl class=\"pay_block\">")).
takeWhile(!_.contains("</dl>"))
}
val payoffHtml =
payoffLines.mkString + "</dl>"
val payoffs = {
parseHtml(payoffHtml).\\("tr").map{ tr =>
val ticketType = tr.\\("th").text.trim
tr.\\("td").map(_.toString.replaceAll("</?td[^>]*>","").split("<br/>").map(_.trim.replaceAll(",",""))).transpose.
map((ticketType, _))
}.flatten.
map { case (ticketStr, list) =>
Payoff(
race_id = lastRowId,
ticket_type = Util.str2ticketType(ticketStr),
horse_number = list(0),
payoff = list(1).toDouble,
popularity = list(2).toInt
)
}
}
payoffs.foreach(PayoffDao.insert)
Try{
parseHtml(rt1Html).\\("tr").tail
}.foreach{ xs =>
xs.map(_.\\("td").map(_.child.mkString).map(clean)).
foreach{ line =>
val row =
line.map(_.replaceAll(" ", "").
replaceAll("<diary_snap_cut></diary_snap_cut>", "").
replaceAll("(牝|牡|セ)(\\d{1,2})", "$1,$2").
replaceAll("\\[(西|地|東|外)\\]", "$1,")).
map(_.filter(_ != '?').trim).
mkString(",").split(",")
val raceResult = str2raceResult(lastRowId, row)
RaceResultDao.insert(raceResult)
}
}
}
}
}
object RaceListScraper {
def extractRaceList(baseUrl: String) = {
"/race/list/\\d+/".r.findAllIn(io.Source.fromURL(baseUrl, "EUC-JP").mkString).toList.
map("http://db.netkeiba.com" + _).
distinct
}
def extractPrevMonth(baseList: String) = {
"/\\?pid=[^\"]+".r.findFirstIn(
io.Source.fromURL(baseList, "EUC-JP").
getLines.filter(_.contains("race_calendar_rev_02.gif")).toList.head).
map("http://db.netkeiba.com" + _).
get
}
def extractRace(listUrl: String) = {
"/race/\\d+/".r.findAllIn(io.Source.fromURL(listUrl, "EUC-JP").mkString).toList.
map("http://db.netkeiba.com" + _).
distinct
}
def scrape(period: Int) = {
var baseUrl = "http://db.netkeiba.com/?pid=race_top"
var i = 0
while (i < period) {
Thread.sleep(1000)
val raceListPages =
extractRaceList(baseUrl)
val racePages =
raceListPages.map{url =>
Thread.sleep(1000)
extractRace(url)
}.flatten
racePages.foreach{ url =>
FileUtils.writeStringToFile(new File("race_url.txt"), url + "\n", true)
}
baseUrl = extractPrevMonth(baseUrl)
println(i + ": collecting URLs from " + baseUrl)
i += 1
}
}
}
case class RaceInfo(
race_name: String,
surface: String,
distance: Int,
weather: String,
surface_state: String,
race_start: String,
race_number: Int,
surface_score: Option[Int],
date: String,
place_detail: String,
race_class: String
)
object RaceInfoDao {
def createTable()(implicit s: DBSession) = {
sql"""
create table if not exists race_info (
id integer primary key autoincrement,
race_name text not null,
surface text not null,
distance integer not null,
weather text not null,
surface_state text not null,
race_start text not null,
race_number integer not null,
surface_score integer,
date text not null,
place_detail text not null,
race_class text not null
);""".execute.apply
sql"""
create index
date_idx
on
race_info (date);
""".execute.apply
sql"""
create index
id_date_idx
on
race_info (id, date);
""".execute.apply
}
def insert(ri: RaceInfo)(implicit s: DBSession) = {
sql"""
insert or replace into race_info (
race_name,
surface,
distance,
weather,
surface_state,
race_start,
race_number,
surface_score,
date,
place_detail,
race_class
) values (
${ri.race_name},
${ri.surface},
${ri.distance},
${ri.weather},
${ri.surface_state},
${ri.race_start},
${ri.race_number},
${ri.surface_score},
${ri.date},
${ri.place_detail},
${ri.race_class}
);
""".update.apply()
}
def lastRowId()(implicit s: DBSession): Int = {
sql"""
select last_insert_rowid() as last_rowid
""".map(_.int("last_rowid")).single.apply().get
}
def getById(id: Int)(implicit s: DBSession): RaceInfo = {
sql"""select * from race_info where id = ${id}""".
map{ x =>
RaceInfo(
race_name = x.string("race_name"),
surface = x.string("surface"),
distance = x.int("distance"),
weather = x.string("weather"),
surface_state = x.string("surface_state"),
race_start = x.string("race_start"),
race_number = x.int("race_number"),
surface_score = x.intOpt("surface_score"),
date = x.string("date"),
place_detail = x.string("place_detail"),
race_class = x.string("race_class")
)
}.single.apply().get
}
}
case class RaceResult(
race_id: Int,
order_of_finish: String,
frame_number: Int,
horse_number: Int,
horse_id: String,
sex: String,
age: Int,
basis_weight: Double,
jockey_id: String,
finishing_time: String,
length: String,
speed_figure: Option[Int],
pass: String,
last_phase: Option[Double],
odds: Option[Double],
popularity: Option[Int],
horse_weight: String,
remark: Option[String],
stable: String,
trainer_id: String,
owner_id: String,
earning_money: Option[Double]
)
object DateRe {
val dateRe =
"(\\d\\d\\d\\d)年(\\d\\d?)月(\\d\\d?)日".r
def unapply(s: String) = {
s match {
case dateRe(y, m, d) =>
val cal = Calendar.getInstance
cal.set(y.toInt, m.toInt - 1, d.toInt)
Some(new Date(cal.getTimeInMillis))
case _ =>
None
}
}
}
object RaceResultDao {
def createTable()(implicit s: DBSession) = {
sql"""
create table if not exists race_result (
race_id integer not null,
order_of_finish text not null,
frame_number integer not null,
horse_number integer not null,
horse_id text not null,
sex text not null,
age integer not null,
basis_weight real not null,
jockey_id text not null,
finishing_time text not null,
length text not null,
speed_figure integer,
pass text not null,
last_phase real,
odds real,
popularity integer,
horse_weight text not null,
remark text,
stable text not null,
trainer_id text not null,
owner_id text not null,
earning_money real,
primary key (race_id, horse_number),
foreign key (race_id) references race_info (id)
);""".execute.apply
sql"""
create index
race_id_idx
on
race_result (race_id);
""".execute.apply
sql"""
create index
race_id_horse_id_idx
on
race_result (race_id, horse_id);
""".execute.apply
sql"""
create index
race_id_jockey_id_idx
on
race_result (race_id, jockey_id);
""".execute.apply
sql"""
create index
race_id_trainer_id_idx
on
race_result (race_id, trainer_id);
""".execute.apply
sql"""
create index
race_id_owner_id_idx
on
race_result (race_id, owner_id);
""".execute.apply
}
def insert(rr: RaceResult)(implicit s: DBSession) = {
sql"""
insert or replace into race_result (
race_id,
order_of_finish,
frame_number,
horse_number,
horse_id,
sex,
age,
basis_weight,
jockey_id,
finishing_time,
length,
speed_figure,
pass,
last_phase,
odds,
popularity,
horse_weight,
remark,
stable,
trainer_id,
owner_id,
earning_money
) values (
${rr.race_id},
${rr.order_of_finish},
${rr.frame_number},
${rr.horse_number},
${rr.horse_id},
${rr.sex},
${rr.age},
${rr.basis_weight},
${rr.jockey_id},
${rr.finishing_time},
${rr.length},
${rr.speed_figure},
${rr.pass},
${rr.last_phase},
${rr.odds},
${rr.popularity},
${rr.horse_weight},
${rr.remark},
${rr.stable},
${rr.trainer_id},
${rr.owner_id},
${rr.earning_money}
)
""".update.apply()
}
}
case class Payoff(
race_id: Int,
ticket_type: Int,
horse_number: String,
payoff: Double,
popularity: Int
)
object PayoffDao {
def createTable()(implicit s: DBSession) = {
sql"""
create table if not exists payoff (
race_id integer not null,
ticket_type integer not null check(ticket_type between 0 and 7),
horse_number text not null,
payoff real not null check(payoff >= 0),
popularity integer not null check(popularity >= 0),
primary key (race_id, ticket_type, horse_number),
foreign key (race_id) references race_info (id)
)
""".execute.apply
}
def insert(dto: Payoff)(implicit s: DBSession) = {
sql"""
insert or replace into payoff (
race_id,
ticket_type,
horse_number,
payoff,
popularity
) values (
${dto.race_id},
${dto.ticket_type},
${dto.horse_number},
${dto.payoff},
${dto.popularity}
)
""".update.apply()
}
}
object FeatureGenerator {
def iterator()(implicit s: DBSession): Iterator[FeatureGenerator] = {
val race_infos = {
sql"select race_id, horse_number from race_result".
map(rs => (rs.int("race_id"), rs.int("horse_number"))).
list.
apply
}
var count = 0
val totalCount = race_infos.size.toDouble
race_infos.
toIterator.
map{ case (race_id, horse_number) =>
count += 1
if (count % 1000 == 0)
println("処理中 ... %7.3f%完了".format(100.0 * count / totalCount))
new FeatureGenerator(race_id, horse_number)
}
}
}
class FeatureGenerator(
val race_id: Int,
val horse_number: Int
)(implicit s: DBSession) {
assert(horse_number > 0)
val RaceInfo(
race_name,
rawSurface,
distance,
rawWeather,
surface_state,
race_start,
race_number,
surface_score,
date,
place_detail,
race_class
) = RaceInfoDao.getById(race_id)
val grade = Util.str2cls(race_class)
val surfaceScore = surface_score
val order_of_finish =
sql"""
select
order_of_finish
from
race_result
where
race_id = ${race_id}
and
horse_number = ${horse_number}""".
map(_.string("order_of_finish")).
single.
apply().
get
val horse_id =
sql"""
select
horse_id
from
race_result
where
race_id = ${race_id}
and
horse_number = ${horse_number}""".
map(_.string("horse_id")).
single.
apply().
get
val jockey_id =
sql"""
select
jockey_id
from
race_result
where
race_id = ${race_id}
and
horse_number = ${horse_number}""".
map(_.string("jockey_id")).
single.
apply().
get
val trainer_id =
sql"""
select
trainer_id
from
race_result
where
race_id = ${race_id}
and
horse_number = ${horse_number}""".
map(_.string("trainer_id")).
single.
apply().
get
val owner_id =
sql"""
select
owner_id
from
race_result
where
race_id = ${race_id}
and
horse_number = ${horse_number}""".
map(_.string("owner_id")).
single.
apply().
get
//Speed rating for the previous race in which the horse ran
val preSRa = {
sql"""
select
speed_figure
from
race_result
inner join
race_info
on
race_result.race_id = race_info.id
where
horse_id = ${horse_id}
and
race_info.date < ${date}
and
speed_figure is not null
order by date desc
limit 1
""".map(_.int("speed_figure")).
single.
apply()
}
//The average of a horse’s speed rating in its last 4 races; value of zero when there is no past run
val avgsr4 = {
val srs =
sql"""
select
speed_figure
from
race_result
inner join
race_info
on
race_result.race_id = race_info.id
where
horse_id = ${horse_id}
and
race_info.date < ${date}
and
speed_figure is not null
order by date desc
limit 4
""".map(_.double("speed_figure")).
list.
apply()
if (srs.isEmpty)
None
else
Some(srs.sum / srs.size)
}
val avgWin4 = {
val wins =
sql"""
select
(order_of_finish = '1' or order_of_finish = '2' or order_of_finish = '3') as is_win
from
race_result
inner join
race_info
on
race_result.race_id = race_info.id
where
horse_id = ${horse_id}
and
race_info.date < ${date}
and
speed_figure is not null
order by date desc
limit 4
""".map(_.double("is_win")).
list.
apply()
if (wins.isEmpty)
None
else
Some(wins.sum / wins.size)
}
//The average speed rating of the past runs of each horse at this distance; value of zero when no previous run
val disavesr = {
val srs =
sql"""
select
speed_figure
from
race_result
inner join
race_info
on
race_result.race_id = race_info.id
where
horse_id = ${horse_id}
and
race_info.date < ${date}
and
distance = ${distance}
and
speed_figure is not null
order by date desc
limit 100
""".map(_.double("speed_figure")).
list.
apply()
if (srs.isEmpty)
None
else
Some(srs.sum / srs.size)
}
val disRoc = {
val distances =
sql"""
select
distance
from
race_result
inner join
race_info
on race_result.race_id = race_info.id
where
horse_id = ${horse_id}
and
race_info.date < ${date}
order by date desc
limit 100
""".map(_.double("distance")).
list.
apply()
if (distances.isEmpty)
None
else {
val mean = distances.sum.toDouble / distances.size
Some((distance - mean) / mean)
}
}
//Total prize money earnings (finishing first, second or third) to date/Number of races entered
val eps = {
val earning_money =
sql"""
select
earning_money
from
race_result
inner join
race_info
on
race_result.race_id = race_info.id
where
horse_id = ${horse_id}
and
race_info.date < ${date}
order by date desc
limit 100
""".map(_.doubleOpt("earning_money")).
list.
apply()
if (earning_money.isEmpty)
None
else
Some(earning_money.flatten.sum / earning_money.size)
}
//Weight carried by the horse in current race
val weight = {
sql"""
select
basis_weight
from
race_result
where
race_id = ${race_id}
and
horse_number = ${horse_number}
""".map(_.double("basis_weight")).
single.
apply.
get
}
val hweight = {
Try{
sql"""
select
horse_weight
from
race_result
where
race_id = ${race_id}
and
horse_number = ${horse_number}
""".map(_.string("horse_weight")).
single.
apply.
get.
replaceAll("""\([^\)]+\)""", "").
toInt
}.toOption
}
val dhweight = {
Try{
sql"""
select
horse_weight
from
race_result
where
race_id = ${race_id}
and
horse_number = ${horse_number}
""".map(_.string("horse_weight")).
single.
apply.
get.
replaceAll(""".*\(([^\)]+)\).*""", "$1").
toInt
}.toOption
}
//The percentage of the races won by the horse in its career
val winRun = {
val wins =
sql"""
select
(order_of_finish = '1') as is_win