6a8ee920639a0969862de335ade6e190b9c5bd18
[profile/ivi/qtdeclarative.git] / examples / declarative / canvas / stockchart / model.cpp
1 /****************************************************************************
2 **
3 ** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies).
4 ** All rights reserved.
5 ** Contact: http://www.qt-project.org/
6 **
7 ** This file is part of the examples of the Qt Toolkit.
8 **
9 ** $QT_BEGIN_LICENSE:BSD$
10 ** You may use this file under the terms of the BSD license as follows:
11 **
12 ** "Redistribution and use in source and binary forms, with or without
13 ** modification, are permitted provided that the following conditions are
14 ** met:
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
20 **     distribution.
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
24 **     permission.
25 **
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."
37 ** $QT_END_LICENSE$
38 **
39 ****************************************************************************/
40 #include "model.h"
41
42 #include <QtCore/QUrl>
43 #include <QtCore/QDate>
44 #include <QtCore/QList>
45 #include <QtCore/QStringList>
46 #include <QtCore/QDebug>
47
48 #include <QtNetwork/QNetworkAccessManager>
49 #include <QtNetwork/QNetworkReply>
50
51 StockModel::StockModel(QObject *parent)
52     : QAbstractListModel(parent)
53     , _startDate(QDate(1995, 4, 25))
54     , _endDate(QDate::currentDate())
55     , _dataCycle(StockModel::Daily)
56     , _manager(0)
57     , _updating(false)
58 {
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";
68     setRoleNames(roles);
69
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()));
74
75     _manager = new QNetworkAccessManager(this);
76     connect(_manager, SIGNAL(finished(QNetworkReply*)), this, SLOT(update(QNetworkReply*)));
77
78 }
79
80 int StockModel::rowCount(const QModelIndex & parent) const {
81     Q_UNUSED(parent);
82     return _prices.count();
83 }
84
85 StockPrice* StockModel::stockPriceAtIndex(int idx) const
86 {
87     if (idx >=0 && idx < _prices.size()) {
88         return _prices[idx];
89     }
90     return 0;
91 }
92
93
94 void StockModel::requestData()
95 {
96     if (!_updating) {
97         _updating = true;
98         QMetaObject::invokeMethod(this, "doRequest", Qt::QueuedConnection);
99     }
100 }
101
102 void StockModel::doRequest()
103 {
104     /*
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)
110       */
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());
117
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)));
121     }
122 }
123
124 void StockModel::update(QNetworkReply *reply)
125 {
126     _updating = false;
127
128     if (reply) {
129          if (reply->error() == QNetworkReply::NoError) {
130             beginResetModel();
131
132             foreach (StockPrice* p, _prices) {
133                 p->deleteLater();
134             }
135
136             _prices.clear();
137
138             while (!reply->atEnd()) {
139                 QString line = reply->readLine();
140                 QStringList fields = line.split(',');
141
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);
154                 }
155             }
156             qDebug() << "get stock data successfully, total:" << _prices.count() << "records.";
157          } else {
158             qDebug() << "get stock data failed:" << reply->errorString();
159          }
160          reply->deleteLater();
161          endResetModel();
162          emit dataChanged(QModelIndex(), QModelIndex());
163     }
164 }
165
166 QVariant StockModel::data(const QModelIndex & index, int role) const {
167     if (index.row() < 0 || index.row() > _prices.count())
168         return QVariant();
169
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();
187     return QVariant();
188 }
189
190 QString StockModel::stockName() const
191 {
192     return _stockName;
193 }
194 void StockModel::setStockName(const QString& name)
195 {
196     if (_stockName != name) {
197         _stockName = name;
198         emit stockNameChanged();
199     }
200 }
201
202 QDate StockModel::startDate() const
203 {
204     return _startDate;
205 }
206 void StockModel::setStartDate(const QDate& date)
207 {
208     if (_startDate.isValid() && _startDate != date) {
209         _startDate = date;
210         emit startDateChanged();
211     }
212 }
213
214 QDate StockModel::endDate() const
215 {
216     return _endDate;
217 }
218 void StockModel::setEndDate(const QDate& date)
219 {
220     if (_endDate.isValid() && _endDate != date) {
221         _endDate = date;
222         emit endDateChanged();
223     }
224 }
225
226 StockModel::StockDataCycle StockModel::dataCycle() const
227 {
228     return _dataCycle;
229 }
230
231 QString StockModel::dataCycleString() const
232 {
233     switch (_dataCycle) {
234     case StockModel::Daily:
235         return QString('d');
236         break;
237     case StockModel::Weekly:
238         return QString('w');
239     case StockModel::Monthly:
240         return QString('m');
241     case StockModel::Dividend:
242         return QString('v');
243     }
244
245     return QString('d');
246 }
247
248
249 void StockModel::setDataCycle(StockModel::StockDataCycle cycle)
250 {
251     if (_dataCycle != cycle) {
252         _dataCycle = cycle;
253         emit dataCycleChanged();
254     }
255 }