1 /****************************************************************************
3 ** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies).
4 ** All rights reserved.
5 ** Contact: http://www.qt-project.org/
7 ** This file is part of the examples of the Qt Toolkit.
9 ** $QT_BEGIN_LICENSE:BSD$
10 ** You may use this file under the terms of the BSD license as follows:
12 ** "Redistribution and use in source and binary forms, with or without
13 ** modification, are permitted provided that the following conditions are
15 ** * Redistributions of source code must retain the above copyright
16 ** notice, this list of conditions and the following disclaimer.
17 ** * Redistributions in binary form must reproduce the above copyright
18 ** notice, this list of conditions and the following disclaimer in
19 ** the documentation and/or other materials provided with the
21 ** * Neither the name of Nokia Corporation and its Subsidiary(-ies) nor
22 ** the names of its contributors may be used to endorse or promote
23 ** products derived from this software without specific prior written
26 ** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
27 ** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
28 ** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
29 ** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
30 ** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
31 ** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
32 ** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
33 ** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
34 ** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
35 ** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
36 ** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
39 ****************************************************************************/
42 #include <QtCore/QUrl>
43 #include <QtCore/QDate>
44 #include <QtCore/QList>
45 #include <QtCore/QStringList>
46 #include <QtCore/QDebug>
48 #include <QtNetwork/QNetworkAccessManager>
49 #include <QtNetwork/QNetworkReply>
51 StockModel::StockModel(QObject *parent)
52 : QAbstractListModel(parent)
53 , _startDate(QDate(1995, 4, 25))
54 , _endDate(QDate::currentDate())
55 , _dataCycle(StockModel::Daily)
59 QHash<int, QByteArray> roles;
60 roles[StockModel::DateRole] = "date";
61 roles[StockModel::SectionRole] = "year";
62 roles[StockModel::OpenPriceRole] = "openPrice";
63 roles[StockModel::ClosePriceRole] = "closePrice";
64 roles[StockModel::HighPriceRole] = "highPrice";
65 roles[StockModel::LowPriceRole] = "lowPrice";
66 roles[StockModel::VolumeRole] = "volume";
67 roles[StockModel::AdjustedPriceRole] = "adjustedPrice";
70 connect(this, SIGNAL(stockNameChanged()), SLOT(requestData()));
71 connect(this, SIGNAL(startDateChanged()), SLOT(requestData()));
72 connect(this, SIGNAL(endDateChanged()), SLOT(requestData()));
73 connect(this, SIGNAL(dataCycleChanged()), SLOT(requestData()));
75 _manager = new QNetworkAccessManager(this);
76 connect(_manager, SIGNAL(finished(QNetworkReply*)), this, SLOT(update(QNetworkReply*)));
80 int StockModel::rowCount(const QModelIndex & parent) const {
82 return _prices.count();
85 StockPrice* StockModel::stockPriceAtIndex(int idx) const
87 if (idx >=0 && idx < _prices.size()) {
94 void StockModel::requestData()
98 QMetaObject::invokeMethod(this, "doRequest", Qt::QueuedConnection);
102 void StockModel::doRequest()
105 Fetch stock data from yahoo finance:
106 url: http://ichart.finance.yahoo.com/table.csv?s=NOK&a=5&b=11&c=2010&d=7&e=23&f=2010&g=d&ignore=.csv
107 s:stock name/id, a:start day, b:start month, c:start year default: 25 April 1995, oldest c= 1962
108 d:end day, e:end month, f:end year, default:today (data only available 3 days before today)
109 g:data cycle(d daily, w weekly, m monthly, v Dividend)
111 if (_manager && !_stockName.isEmpty() && _endDate > _startDate) {
112 QString query("http://ichart.finance.yahoo.com/table.csv?s=%1&a=%2&b=%3&c=%4&d=%5&e=%6&f=%7&g=%8&ignore=.csv");
113 query = query.arg(_stockName)
114 .arg(_startDate.day()).arg(_startDate.month()).arg(_startDate.year())
115 .arg(_endDate.day()).arg(_endDate.month()).arg(_endDate.year())
116 .arg(dataCycleString());
118 qDebug() << "request stock data:" << query;
119 QNetworkReply* reply = _manager->get(QNetworkRequest(QUrl(query)));
120 connect(reply, SIGNAL(downloadProgress(qint64,qint64)), SIGNAL(downloadProgress(qint64,qint64)));
124 void StockModel::update(QNetworkReply *reply)
129 if (reply->error() == QNetworkReply::NoError) {
132 foreach (StockPrice* p, _prices) {
138 while (!reply->atEnd()) {
139 QString line = reply->readLine();
140 QStringList fields = line.split(',');
142 //data format:Date,Open,High,Low,Close,Volume,Adjusted close price
143 //example: 2011-06-24,6.03,6.04,5.88,5.88,20465200,5.88
144 if (fields.size() == 7) {
145 StockPrice* price = new StockPrice(this);
146 price->setDate(QDate::fromString(fields[0], Qt::ISODate));
147 price->setOpenPrice(fields[1].toFloat());
148 price->setHighPrice(fields[2].toFloat());
149 price->setLowPrice(fields[3].toFloat());
150 price->setClosePrice(fields[4].toFloat());
151 price->setVolume(fields[5].toInt());
152 price->setAdjustedPrice(fields[6].toFloat());
153 _prices.prepend(price);
156 qDebug() << "get stock data successfully, total:" << _prices.count() << "records.";
158 qDebug() << "get stock data failed:" << reply->errorString();
160 reply->deleteLater();
162 emit dataChanged(QModelIndex(), QModelIndex());
166 QVariant StockModel::data(const QModelIndex & index, int role) const {
167 if (index.row() < 0 || index.row() > _prices.count())
170 const StockPrice* price = _prices[index.row()];
171 if (role == StockModel::DateRole)
172 return price->date();
173 else if (role == StockModel::OpenPriceRole)
174 return price->openPrice();
175 else if (role == StockModel::ClosePriceRole)
176 return price->closePrice();
177 else if (role == StockModel::HighPriceRole)
178 return price->highPrice();
179 else if (role == StockModel::LowPriceRole)
180 return price->lowPrice();
181 else if (role == StockModel::AdjustedPriceRole)
182 return price->adjustedPrice();
183 else if (role == StockModel::VolumeRole)
184 return price->volume();
185 else if (role == StockModel::SectionRole)
186 return price->date().year();
190 QString StockModel::stockName() const
194 void StockModel::setStockName(const QString& name)
196 if (_stockName != name) {
198 emit stockNameChanged();
202 QDate StockModel::startDate() const
206 void StockModel::setStartDate(const QDate& date)
208 if (_startDate.isValid() && _startDate != date) {
210 emit startDateChanged();
214 QDate StockModel::endDate() const
218 void StockModel::setEndDate(const QDate& date)
220 if (_endDate.isValid() && _endDate != date) {
222 emit endDateChanged();
226 StockModel::StockDataCycle StockModel::dataCycle() const
231 QString StockModel::dataCycleString() const
233 switch (_dataCycle) {
234 case StockModel::Daily:
237 case StockModel::Weekly:
239 case StockModel::Monthly:
241 case StockModel::Dividend:
249 void StockModel::setDataCycle(StockModel::StockDataCycle cycle)
251 if (_dataCycle != cycle) {
253 emit dataCycleChanged();