wgetで株価データを取得してくるルーチン
コード全体
# -*- coding: shift_jis -*-
import os
from calendar import *targetURL = 'http://www.targetURL/data2006/'
#↑blog記述用ダミーURLですdef wget():
monthList =(1,2,3,4,5,6,7,8)
for i in monthList:
for m in range(1,monthrange(2006,i)[1] + 1):
if weekday(2006,i,m) < 5:
targetFile = targetURL + 'D06%02d%02d.LZH' % (i,m)
os.popen('wget %s' % targetFile)if __name__ == '__main__':
wget()
逐行解説
いずれも標準モジュール。
import os
from calendar import *
東証1、2部+大証+各種新興市場の相場情報を毎日CSVデータにして公開してくださっているサイトのURL(複数あるのでGoogleで探すなどして使用目的に応じたところを選んでください)。利用させて頂くサイトの株価データは、たとえば06年8月20日であれば"D060820.LZH"などの形式で当該ディレクトリの中に格納されている。
targetURL = 'http://www.targetURL/data2006/'
まずは今年の1〜8月のデータを取得する。
1月から8月までを表す配列。
monthList =(1,2,3,4,5,6,7,8)
monthListから1つずつ値を取り出したものをiに代入していく。
for i in monthList:
for m in range(1,monthrange(2006,i)[1] + 1):
さらに、calendarモジュールのmonthrange関数(yyyy年i月の第1日の曜日、日数を返す)を呼び出し、i月の日数をmに代入して行く。
2006年i月m日が土日でない場合(calendarモジュールのweekday関数:0が月曜日、以下土曜日が5、日曜日が6)、その日の株価データのURLを生成してtargetFileに代入し、os.popenでコマンドwgetを起動して、targetFileをローカルのカレントディレクトリにダウンロードしてくる。
if weekday(2006,i,m) < 5:
targetFile = targetURL + 'D06%02d%02d.LZH' % (i,m)
os.popen('wget %s' % targetFile)
(参考)
- os.popenの解説 http://www.python.jp/doc/release/lib/os-newstreams.html
- calendarモジュールの解説 http://www.python.jp/doc/release/lib/module-calendar.html