Help us understand the problem. What is going on with this article?

TOPIXの時系列を pickle, csv, Excel形式で保存する

More than 5 years have passed since last update.


TOPIX の時系列を表示するのは前の投稿でやったので、

Yahoo ファイナンスの html を解析するコード

前のと同じ。 ただし、 savedataAsなんとか(filename, data) という関数呼び出しを入れている。

#!/usr/bin/env python
#-*- coding: utf-8 -*-
import pylab
import urllib2
import lxml
import lxml.html
import re

dateFr = {"year": 2000, "month":1, "day":1}
dateTo = {"year": 2013, "month":11, "day": 1}

data = []
for page in range(1, 30):
    print page
    url = ""
    url = url % (dateFr["year"], dateFr["month"], dateFr["day"], dateTo["year"], dateFr["month"], dateFr["day"], page)

    html = urllib2.urlopen(url).read()
    root = lxml.html.fromstring(html)
    table = root.xpath(' //*[contains(concat(" ",normalize-space(@class)," "), " boardFin ")]')[0]

    for tr in table.xpath("descendant::tr"):
        tmp = [td.text for td in tr.xpath("descendant::td")]
        if len(tmp) != 5:
        begin = float(tmp[1].replace(",", ""))
        high  = float(tmp[2].replace(",", ""))
        low   = float(tmp[3].replace(",", ""))
        end   = float(tmp[4].replace(",", ""))
        data.append([low, high, low, high])
savedataAsPickle('topix.pickle', data)
savedataAsCSV('topix.csv', data)
savedataAsExcel('topix.xlsx', data)



python の標準ライブラリにある形式

def savedata(filename, data):
    pickle.dump(data, open(filename, "w"))


Comma Separated Values の略。テキスト形式。

def savedata(filename, data):
    import csv
    csvobj = csv.writer(open(filename, "w"))

Excel 形式

Excel で読める形式に保存

def savedata(filename, data):
    import openpyxl.workbook
    import openpyxl.cell

    wb = openpyxl.workbook.Workbook()
    ws = wb.worksheets[0]
    ws.title = "TOPIX"
    for idat, dat in enumerate(data):
        col = openpyxl.cell.get_column_letter(idat + 1) # from 1, 2, ... to A, B, ...
        for irow, d in enumerate(dat):
            ws.cell('%s%s'%(col, irow + 1)).value = d
ハイラブル株式会社の代表取締役。博士(情報学) カエルの研究をしてました。会話の定量化や分析をしてます。
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away