LoginSignup
3
1

More than 5 years have passed since last update.

有馬記念をきっかけに機械学習を始める

Posted at

pythonを知る

とりあえず馬のマスタデータを集める

# coding: UTF-8

# CSV
import csv

# 時間
from datetime import datetime
import time

# httpリクエスト
from urllib.parse import urlparse
import urllib.request, urllib.error
import requests

# htmlparse
from bs4 import BeautifulSoup

# pandas
import pandas as pd

# data init
data_scheme   = ['name', 'age', 'total_attend', 'bad_attend', 'good_rate']
csv_head      = ["名前", "年齢", "生涯出走回数", "4位以下になった回数", "1位から3位に入る打率"]
target_horses = ["ヤマカツエース", "キタサンブラック", "クイーンズリング", "ブレスジャーニー", "トーセンビクトリー", "サトノクロニクル", "シャケトラ", "レインボーライン", "サクラアンプルール", "シュヴァルグラン", "ルージュバック", "サトノクラウン", "ミッキークイーン", "スワーヴリチャード", "カレンミロティック", "サウンズオブアース"]

# CSV init
csv_lists = []
csv_lists.append(csv_head)

class Scrape:
    def current_time(self):
        # 現在の時刻を年、月、日、時、分、秒で取得します
        time = datetime.now().strftime("%Y/%m/%d %H:%M:%S")
        return time

    def create_search_horse_url(self, horse):
        # アクセスするURL
        search_template = 'https://keiba.yahoo.co.jp/directory/horsesearch/?status=1&fhn=&mhn=&mfhn=&mmhn=&tn=&on=&bn=&minage=&maxage=&hn='
        url_string = search_template + horse
        request_url = urlparse(url_string)
        query = urllib.parse.quote_plus(request_url.query, safe='=&')
        url = '{}://{}{}{}{}{}{}{}{}'.format(
            request_url.scheme, request_url.netloc, request_url.path,
            ';' if request_url.params else '', request_url.params,
            '?' if request_url.query else '', query,
            '#' if request_url.fragment else '', request_url.fragment)
        return url

class Horse:
    def get_attr(self, name):
        element = ''
        if name is 'name':
            element = soup.find("h1", class_="fntB").get_text()
        elif name is 'age':
            element = soup.find(id="dirTitName").find_all("p")[0].get_text()[-3:-2] # 今回は競走馬が1けたのためこれでOK
        elif name is 'total_attend':
            element = soup.find_all(class_="mgnBL")[0].find_all("td")[5].get_text()
        elif name is 'bad_attend':
            element = soup.find_all(class_="mgnBL")[0].find_all("td")[4].get_text()
        else:
            print("Marcos Vechionacci")
        return element

for i in range(len(target_horses)):
    scrape = Scrape()
    horse = Horse()

    # 1カラム目に時間を挿入します
    #csv_list.append(time_)
    url = scrape.create_search_horse_url(target_horses[i])
    res = requests.get(url)
    if res.status_code == 200:
        soup = BeautifulSoup(res.text, 'lxml')
        # aタグの取得
        r_horse_name = horse.get_attr('name')
        if r_horse_name == target_horses[i]:
            r_horse_age = horse.get_attr('age')
            r_horse_total_attend = horse.get_attr('total_attend')
            r_horse_bad_attend = horse.get_attr('bad_attend')
            r_horse_good_rate = 1 - float(int(r_horse_bad_attend)) / int(r_horse_total_attend)

            csv_list = [r_horse_name, r_horse_age, r_horse_total_attend, r_horse_bad_attend, r_horse_good_rate]
            csv_lists.append(csv_list)

df = pd.DataFrame(csv_lists, columns=data_scheme)
# CSV ファイル (employee.csv) として出力
df.to_csv("mst_horse.csv")

結果.csv

,name,age,total_attend,bad_attend,good_rate
0,名前,年齢,生涯出走回数,4位以下になった回数,1位から3位に入る打率
1,ヤマカツエース,5,7,6,0.1428571428571429
2,キタサンブラック,5,13,2,0.8461538461538461
3,クイーンズリング,5,8,6,0.25
4,ブレスジャーニー,3,1,1,0.0
5,トーセンビクトリー,5,3,3,0.0
6,サトノクロニクル,3,1,1,0.0
7,シャケトラ,4,4,4,0.0
8,レインボーライン,4,8,5,0.375
9,サクラアンプルール,6,2,2,0.0
10,シュヴァルグラン,5,7,3,0.5714285714285714
11,ルージュバック,5,9,8,0.11111111111111116
12,サトノクラウン,5,9,6,0.33333333333333337
13,ミッキークイーン,5,9,3,0.6666666666666667
14,スワーヴリチャード,3,2,1,0.5
15,カレンミロティック,9,8,5,0.375
16,サウンズオブアース,6,9,6,0.33333333333333337

ちょっと雑に始めてみて継続的に改修しようかと。

買ってみた

2-13-10 3連単
13-2-10 3連単
9 単勝

を100円ずつ

有馬記念の結果

2-3-10

大外れ。

次にやること

レース結果を元に解析することで有馬記念の反省を行う。

3
1
4

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
1