Compare commits

..

34 Commits

Author SHA1 Message Date
Sam c31c1f5f06 add map 2024-09-04 18:49:40 +01:00
Sam 8788de1717 delete cv 2024-09-04 15:52:57 +01:00
Sam d0d8ef627d fix 2024-09-03 22:24:32 +01:00
Sam 194dc81fab remove link to cv 2024-09-02 14:56:20 +01:00
Sam 9be14e9e95 remove draft article 2024-08-28 21:44:51 +01:00
Sam 5f70642630 minor cv change 2024-08-28 20:57:00 +01:00
Sam e9e9b59054 update cv 2024-08-28 19:07:46 +01:00
Sam 7c53d31090 typo 2024-08-28 18:29:34 +01:00
Sam 6474149be3 update CV 2024-08-28 18:27:57 +01:00
Sam 5600889bb6 move todays date inside route functions 2024-08-27 15:37:27 +01:00
Sam d851b03572 chance lisence 2024-08-22 10:45:55 +01:00
Sam 9c38b67927 chance lisence 2024-08-22 10:39:36 +01:00
Sam 7574996863 fix data-downloads link and update cv 2024-08-22 10:26:09 +01:00
Sam 5840cad951 make construction notice bold 2024-08-20 19:42:58 +01:00
Sam 4977ce1adf changed homepage to remove license info 2024-08-20 19:41:13 +01:00
Sam 51eba0166f update cv 2024-08-20 17:03:36 +01:00
Sam a3d8cc4302 Update cv 2024-08-20 10:17:41 +01:00
Sam b14e2503ce attribution to singapore dl page 2024-08-15 20:31:09 +01:00
Sam 08e1ada18a tweaks and license stuff 2024-08-15 20:28:16 +01:00
Sam 7fa469cb8e fix get remote address in app logging 2024-08-15 15:22:11 +01:00
Sam 12fc1490f0 fix url issue 2024-08-15 15:14:43 +01:00
Sam 0357f61342 revert api url in config 2024-08-15 15:01:36 +01:00
Sam 349101a236 more tweaks 2024-08-15 15:00:44 +01:00
Sam 3f3f27d4c8 Major refactor of charts 2024-08-14 19:48:58 +01:00
Sam a0796dacc5 Change api endpoints to use apiURL 2024-08-14 17:59:38 +01:00
Sam 4cf874ca77 Merge branch 'master' of git.bitlab21.com:sam/baseddata.io 2024-08-14 11:48:09 +01:00
Sam 6ec45a5dd6 Modify content 2024-08-14 11:47:45 +01:00
Sam e277e13aec add data dir to gitignore 2024-08-14 11:46:17 +01:00
Sam e1bdecb23f Use default content list for tags creation 2024-08-13 20:35:00 +01:00
Sam b8c5b01243 Fixes incorrect url in site title 2024-08-13 20:31:51 +01:00
Sam 42a32637bb Modifications 2024-08-13 20:14:17 +01:00
Sam bc41fb2367 Fix incorrect url in data-downloads shortcode 2024-08-13 20:01:36 +01:00
Sam 94b59f8aa9 Add requirements.txt 2024-08-13 19:48:52 +01:00
Sam 9292b0df03 Rename service file 2024-08-13 19:43:41 +01:00
40 changed files with 931 additions and 170 deletions

2
.gitignore vendored
View File

@ -2,4 +2,6 @@
*.old
.hugo_build.lock
*.json
/data
backend/api_logs.txt
*__pycache__*

428
LICENSE.md Normal file
View File

@ -0,0 +1,428 @@
Attribution-ShareAlike 4.0 International
=======================================================================
Creative Commons Corporation ("Creative Commons") is not a law firm and
does not provide legal services or legal advice. Distribution of
Creative Commons public licenses does not create a lawyer-client or
other relationship. Creative Commons makes its licenses and related
information available on an "as-is" basis. Creative Commons gives no
warranties regarding its licenses, any material licensed under their
terms and conditions, or any related information. Creative Commons
disclaims all liability for damages resulting from their use to the
fullest extent possible.
Using Creative Commons Public Licenses
Creative Commons public licenses provide a standard set of terms and
conditions that creators and other rights holders may use to share
original works of authorship and other material subject to copyright
and certain other rights specified in the public license below. The
following considerations are for informational purposes only, are not
exhaustive, and do not form part of our licenses.
Considerations for licensors: Our public licenses are
intended for use by those authorized to give the public
permission to use material in ways otherwise restricted by
copyright and certain other rights. Our licenses are
irrevocable. Licensors should read and understand the terms
and conditions of the license they choose before applying it.
Licensors should also secure all rights necessary before
applying our licenses so that the public can reuse the
material as expected. Licensors should clearly mark any
material not subject to the license. This includes other CC-
licensed material, or material used under an exception or
limitation to copyright. More considerations for licensors:
wiki.creativecommons.org/Considerations_for_licensors
Considerations for the public: By using one of our public
licenses, a licensor grants the public permission to use the
licensed material under specified terms and conditions. If
the licensor's permission is not necessary for any reason--for
example, because of any applicable exception or limitation to
copyright--then that use is not regulated by the license. Our
licenses grant only permissions under copyright and certain
other rights that a licensor has authority to grant. Use of
the licensed material may still be restricted for other
reasons, including because others have copyright or other
rights in the material. A licensor may make special requests,
such as asking that all changes be marked or described.
Although not required by our licenses, you are encouraged to
respect those requests where reasonable. More considerations
for the public:
wiki.creativecommons.org/Considerations_for_licensees
=======================================================================
Creative Commons Attribution-ShareAlike 4.0 International Public
License
By exercising the Licensed Rights (defined below), You accept and agree
to be bound by the terms and conditions of this Creative Commons
Attribution-ShareAlike 4.0 International Public License ("Public
License"). To the extent this Public License may be interpreted as a
contract, You are granted the Licensed Rights in consideration of Your
acceptance of these terms and conditions, and the Licensor grants You
such rights in consideration of benefits the Licensor receives from
making the Licensed Material available under these terms and
conditions.
Section 1 -- Definitions.
a. Adapted Material means material subject to Copyright and Similar
Rights that is derived from or based upon the Licensed Material
and in which the Licensed Material is translated, altered,
arranged, transformed, or otherwise modified in a manner requiring
permission under the Copyright and Similar Rights held by the
Licensor. For purposes of this Public License, where the Licensed
Material is a musical work, performance, or sound recording,
Adapted Material is always produced where the Licensed Material is
synched in timed relation with a moving image.
b. Adapter's License means the license You apply to Your Copyright
and Similar Rights in Your contributions to Adapted Material in
accordance with the terms and conditions of this Public License.
c. BY-SA Compatible License means a license listed at
creativecommons.org/compatiblelicenses, approved by Creative
Commons as essentially the equivalent of this Public License.
d. Copyright and Similar Rights means copyright and/or similar rights
closely related to copyright including, without limitation,
performance, broadcast, sound recording, and Sui Generis Database
Rights, without regard to how the rights are labeled or
categorized. For purposes of this Public License, the rights
specified in Section 2(b)(1)-(2) are not Copyright and Similar
Rights.
e. Effective Technological Measures means those measures that, in the
absence of proper authority, may not be circumvented under laws
fulfilling obligations under Article 11 of the WIPO Copyright
Treaty adopted on December 20, 1996, and/or similar international
agreements.
f. Exceptions and Limitations means fair use, fair dealing, and/or
any other exception or limitation to Copyright and Similar Rights
that applies to Your use of the Licensed Material.
g. License Elements means the license attributes listed in the name
of a Creative Commons Public License. The License Elements of this
Public License are Attribution and ShareAlike.
h. Licensed Material means the artistic or literary work, database,
or other material to which the Licensor applied this Public
License.
i. Licensed Rights means the rights granted to You subject to the
terms and conditions of this Public License, which are limited to
all Copyright and Similar Rights that apply to Your use of the
Licensed Material and that the Licensor has authority to license.
j. Licensor means the individual(s) or entity(ies) granting rights
under this Public License.
k. Share means to provide material to the public by any means or
process that requires permission under the Licensed Rights, such
as reproduction, public display, public performance, distribution,
dissemination, communication, or importation, and to make material
available to the public including in ways that members of the
public may access the material from a place and at a time
individually chosen by them.
l. Sui Generis Database Rights means rights other than copyright
resulting from Directive 96/9/EC of the European Parliament and of
the Council of 11 March 1996 on the legal protection of databases,
as amended and/or succeeded, as well as other essentially
equivalent rights anywhere in the world.
m. You means the individual or entity exercising the Licensed Rights
under this Public License. Your has a corresponding meaning.
Section 2 -- Scope.
a. License grant.
1. Subject to the terms and conditions of this Public License,
the Licensor hereby grants You a worldwide, royalty-free,
non-sublicensable, non-exclusive, irrevocable license to
exercise the Licensed Rights in the Licensed Material to:
a. reproduce and Share the Licensed Material, in whole or
in part; and
b. produce, reproduce, and Share Adapted Material.
2. Exceptions and Limitations. For the avoidance of doubt, where
Exceptions and Limitations apply to Your use, this Public
License does not apply, and You do not need to comply with
its terms and conditions.
3. Term. The term of this Public License is specified in Section
6(a).
4. Media and formats; technical modifications allowed. The
Licensor authorizes You to exercise the Licensed Rights in
all media and formats whether now known or hereafter created,
and to make technical modifications necessary to do so. The
Licensor waives and/or agrees not to assert any right or
authority to forbid You from making technical modifications
necessary to exercise the Licensed Rights, including
technical modifications necessary to circumvent Effective
Technological Measures. For purposes of this Public License,
simply making modifications authorized by this Section 2(a)
(4) never produces Adapted Material.
5. Downstream recipients.
a. Offer from the Licensor -- Licensed Material. Every
recipient of the Licensed Material automatically
receives an offer from the Licensor to exercise the
Licensed Rights under the terms and conditions of this
Public License.
b. Additional offer from the Licensor -- Adapted Material.
Every recipient of Adapted Material from You
automatically receives an offer from the Licensor to
exercise the Licensed Rights in the Adapted Material
under the conditions of the Adapter's License You apply.
c. No downstream restrictions. You may not offer or impose
any additional or different terms or conditions on, or
apply any Effective Technological Measures to, the
Licensed Material if doing so restricts exercise of the
Licensed Rights by any recipient of the Licensed
Material.
6. No endorsement. Nothing in this Public License constitutes or
may be construed as permission to assert or imply that You
are, or that Your use of the Licensed Material is, connected
with, or sponsored, endorsed, or granted official status by,
the Licensor or others designated to receive attribution as
provided in Section 3(a)(1)(A)(i).
b. Other rights.
1. Moral rights, such as the right of integrity, are not
licensed under this Public License, nor are publicity,
privacy, and/or other similar personality rights; however, to
the extent possible, the Licensor waives and/or agrees not to
assert any such rights held by the Licensor to the limited
extent necessary to allow You to exercise the Licensed
Rights, but not otherwise.
2. Patent and trademark rights are not licensed under this
Public License.
3. To the extent possible, the Licensor waives any right to
collect royalties from You for the exercise of the Licensed
Rights, whether directly or through a collecting society
under any voluntary or waivable statutory or compulsory
licensing scheme. In all other cases the Licensor expressly
reserves any right to collect such royalties.
Section 3 -- License Conditions.
Your exercise of the Licensed Rights is expressly made subject to the
following conditions.
a. Attribution.
1. If You Share the Licensed Material (including in modified
form), You must:
a. retain the following if it is supplied by the Licensor
with the Licensed Material:
i. identification of the creator(s) of the Licensed
Material and any others designated to receive
attribution, in any reasonable manner requested by
the Licensor (including by pseudonym if
designated);
ii. a copyright notice;
iii. a notice that refers to this Public License;
iv. a notice that refers to the disclaimer of
warranties;
v. a URI or hyperlink to the Licensed Material to the
extent reasonably practicable;
b. indicate if You modified the Licensed Material and
retain an indication of any previous modifications; and
c. indicate the Licensed Material is licensed under this
Public License, and include the text of, or the URI or
hyperlink to, this Public License.
2. You may satisfy the conditions in Section 3(a)(1) in any
reasonable manner based on the medium, means, and context in
which You Share the Licensed Material. For example, it may be
reasonable to satisfy the conditions by providing a URI or
hyperlink to a resource that includes the required
information.
3. If requested by the Licensor, You must remove any of the
information required by Section 3(a)(1)(A) to the extent
reasonably practicable.
b. ShareAlike.
In addition to the conditions in Section 3(a), if You Share
Adapted Material You produce, the following conditions also apply.
1. The Adapter's License You apply must be a Creative Commons
license with the same License Elements, this version or
later, or a BY-SA Compatible License.
2. You must include the text of, or the URI or hyperlink to, the
Adapter's License You apply. You may satisfy this condition
in any reasonable manner based on the medium, means, and
context in which You Share Adapted Material.
3. You may not offer or impose any additional or different terms
or conditions on, or apply any Effective Technological
Measures to, Adapted Material that restrict exercise of the
rights granted under the Adapter's License You apply.
Section 4 -- Sui Generis Database Rights.
Where the Licensed Rights include Sui Generis Database Rights that
apply to Your use of the Licensed Material:
a. for the avoidance of doubt, Section 2(a)(1) grants You the right
to extract, reuse, reproduce, and Share all or a substantial
portion of the contents of the database;
b. if You include all or a substantial portion of the database
contents in a database in which You have Sui Generis Database
Rights, then the database in which You have Sui Generis Database
Rights (but not its individual contents) is Adapted Material,
including for purposes of Section 3(b); and
c. You must comply with the conditions in Section 3(a) if You Share
all or a substantial portion of the contents of the database.
For the avoidance of doubt, this Section 4 supplements and does not
replace Your obligations under this Public License where the Licensed
Rights include other Copyright and Similar Rights.
Section 5 -- Disclaimer of Warranties and Limitation of Liability.
a. UNLESS OTHERWISE SEPARATELY UNDERTAKEN BY THE LICENSOR, TO THE
EXTENT POSSIBLE, THE LICENSOR OFFERS THE LICENSED MATERIAL AS-IS
AND AS-AVAILABLE, AND MAKES NO REPRESENTATIONS OR WARRANTIES OF
ANY KIND CONCERNING THE LICENSED MATERIAL, WHETHER EXPRESS,
IMPLIED, STATUTORY, OR OTHER. THIS INCLUDES, WITHOUT LIMITATION,
WARRANTIES OF TITLE, MERCHANTABILITY, FITNESS FOR A PARTICULAR
PURPOSE, NON-INFRINGEMENT, ABSENCE OF LATENT OR OTHER DEFECTS,
ACCURACY, OR THE PRESENCE OR ABSENCE OF ERRORS, WHETHER OR NOT
KNOWN OR DISCOVERABLE. WHERE DISCLAIMERS OF WARRANTIES ARE NOT
ALLOWED IN FULL OR IN PART, THIS DISCLAIMER MAY NOT APPLY TO YOU.
b. TO THE EXTENT POSSIBLE, IN NO EVENT WILL THE LICENSOR BE LIABLE
TO YOU ON ANY LEGAL THEORY (INCLUDING, WITHOUT LIMITATION,
NEGLIGENCE) OR OTHERWISE FOR ANY DIRECT, SPECIAL, INDIRECT,
INCIDENTAL, CONSEQUENTIAL, PUNITIVE, EXEMPLARY, OR OTHER LOSSES,
COSTS, EXPENSES, OR DAMAGES ARISING OUT OF THIS PUBLIC LICENSE OR
USE OF THE LICENSED MATERIAL, EVEN IF THE LICENSOR HAS BEEN
ADVISED OF THE POSSIBILITY OF SUCH LOSSES, COSTS, EXPENSES, OR
DAMAGES. WHERE A LIMITATION OF LIABILITY IS NOT ALLOWED IN FULL OR
IN PART, THIS LIMITATION MAY NOT APPLY TO YOU.
c. The disclaimer of warranties and limitation of liability provided
above shall be interpreted in a manner that, to the extent
possible, most closely approximates an absolute disclaimer and
waiver of all liability.
Section 6 -- Term and Termination.
a. This Public License applies for the term of the Copyright and
Similar Rights licensed here. However, if You fail to comply with
this Public License, then Your rights under this Public License
terminate automatically.
b. Where Your right to use the Licensed Material has terminated under
Section 6(a), it reinstates:
1. automatically as of the date the violation is cured, provided
it is cured within 30 days of Your discovery of the
violation; or
2. upon express reinstatement by the Licensor.
For the avoidance of doubt, this Section 6(b) does not affect any
right the Licensor may have to seek remedies for Your violations
of this Public License.
c. For the avoidance of doubt, the Licensor may also offer the
Licensed Material under separate terms or conditions or stop
distributing the Licensed Material at any time; however, doing so
will not terminate this Public License.
d. Sections 1, 5, 6, 7, and 8 survive termination of this Public
License.
Section 7 -- Other Terms and Conditions.
a. The Licensor shall not be bound by any additional or different
terms or conditions communicated by You unless expressly agreed.
b. Any arrangements, understandings, or agreements regarding the
Licensed Material not stated herein are separate from and
independent of the terms and conditions of this Public License.
Section 8 -- Interpretation.
a. For the avoidance of doubt, this Public License does not, and
shall not be interpreted to, reduce, limit, restrict, or impose
conditions on any use of the Licensed Material that could lawfully
be made without permission under this Public License.
b. To the extent possible, if any provision of this Public License is
deemed unenforceable, it shall be automatically reformed to the
minimum extent necessary to make it enforceable. If the provision
cannot be reformed, it shall be severed from this Public License
without affecting the enforceability of the remaining terms and
conditions.
c. No term or condition of this Public License will be waived and no
failure to comply consented to unless expressly agreed to by the
Licensor.
d. Nothing in this Public License constitutes or may be interpreted
as a limitation upon, or waiver of, any privileges and immunities
that apply to the Licensor or You, including from the legal
processes of any jurisdiction or authority.
=======================================================================
Creative Commons is not a party to its public
licenses. Notwithstanding, Creative Commons may elect to apply one of
its public licenses to material it publishes and in those instances
will be considered the “Licensor.” The text of the Creative Commons
public licenses is dedicated to the public domain under the CC0 Public
Domain Dedication. Except for the limited purpose of indicating that
material is shared under a Creative Commons public license or as
otherwise permitted by the Creative Commons policies published at
creativecommons.org/policies, Creative Commons does not authorize the
use of the trademark "Creative Commons" or any other trademark or logo
of Creative Commons without its prior written consent including,
without limitation, in connection with any unauthorized modifications
to any of its public licenses or any other arrangements,
understandings, or agreements concerning use of licensed material. For
the avoidance of doubt, this paragraph does not form part of the
public licenses.
Creative Commons may be contacted at creativecommons.org.

View File

@ -1,63 +1,172 @@
from flask import Flask, jsonify, request, json, Response, send_from_directory, abort
from flask import Flask, g, jsonify, request, json, Response, send_from_directory, abort
from flask_cors import CORS
import orjson, os
import datetime
import time
app = Flask(__name__)
CORS(app)
FILES_DIRECTORY = '../data/'
FILES_DIRECTORY = "../data/"
@app.route('/bitcoin_business_growth_by_country', methods=['GET'])
@app.before_request
def start_timer():
g.start = time.time()
@app.after_request
def log(response):
now = time.time()
duration = round(now - g.start, 4)
dt = datetime.datetime.fromtimestamp(now).strftime("%Y-%m-%d %H:%M:%S")
log_entry = {
"timestamp": dt,
"duration": duration,
"method": request.method,
"url": request.url,
"status": response.status_code,
"remote_addr": request.access_route[-1],
"user_agent": request.user_agent.string,
}
log_line = ",".join(f"{key}={value}" for key, value in log_entry.items())
with open("api_logs.txt", "a") as f:
f.write(log_line + "\n")
return response
@app.route("/bitcoin_business_growth_by_country", methods=["GET"])
def business_growth():
today = datetime.datetime.today()
# Parse args from request
latest_date = request.args.get('latest_date')
country_names = request.args.get('countries') # change this line
cumulative_period_type = request.args.get('cumulative_period_type')
latest_date = request.args.get("latest_date")
country_names = request.args.get("countries") # change this line
cumulative_period_type = request.args.get("cumulative_period_type")
# Open json locally
with open('../data/final__bitcoin_business_growth_by_country.json', 'rb') as f:
with open("../data/final__bitcoin_business_growth_by_country.json", "rb") as f:
data = orjson.loads(f.read())
# Filter based on args
if latest_date:
latest_date_bool = latest_date == 'true'
filtered_data = [item for item in data if item['latest_date'] == latest_date_bool]
latest_date_bool = latest_date == "true"
filtered_data = [
item for item in data if item["latest_date"] == latest_date_bool
]
else:
filtered_data = data
if country_names:
countries = [name.strip() for name in country_names.split(",")]
filtered_data = [item for item in filtered_data if item['country_name'] in countries]
filtered_data = [
item for item in filtered_data if item["country_name"] in countries
]
if cumulative_period_type:
filtered_data = [item for item in filtered_data if item['cumulative_period_type'] == cumulative_period_type]
if cumulative_period_type == "1 day":
delta = today - datetime.timedelta(days=2)
filtered_data = [
item
for item in filtered_data
if item["cumulative_period_type"] == cumulative_period_type
and delta <= datetime.datetime.strptime(item["date"], "%Y-%m-%d")
]
elif cumulative_period_type == "7 day":
delta = today - datetime.timedelta(days=8)
filtered_data = [
item
for item in filtered_data
if item["cumulative_period_type"] == cumulative_period_type
and delta <= datetime.datetime.strptime(item["date"], "%Y-%m-%d")
]
elif cumulative_period_type == "28 day":
delta = today - datetime.timedelta(days=29)
filtered_data = [
item
for item in filtered_data
if item["cumulative_period_type"] == cumulative_period_type
and delta <= datetime.datetime.strptime(item["date"], "%Y-%m-%d")
]
elif cumulative_period_type == "365 day":
delta = today - datetime.timedelta(days=366)
filtered_data = [
item
for item in filtered_data
if item["cumulative_period_type"] == cumulative_period_type
and delta <= datetime.datetime.strptime(item["date"], "%Y-%m-%d")
]
# Sort by date
sorted_data = sorted(filtered_data, key=lambda x: x['date'], reverse=True)
sorted_data = sorted(filtered_data, key=lambda x: x["date"], reverse=False)
# Return json
return Response(json.dumps(sorted_data), mimetype='application/json')
return Response(json.dumps(sorted_data), mimetype="application/json")
@app.route('/get_json/<filename>', methods=['GET'])
@app.route("/get_json/<filename>", methods=["GET"])
def get_json(filename):
period = request.args.get("period")
today = datetime.datetime.today()
file_path = os.path.join(FILES_DIRECTORY, filename)
if not os.path.isfile(file_path):
abort(404)
with open(file_path, 'r') as file:
data = json.load(file)
with open(file_path, "r") as f:
data = orjson.loads(f.read())
return jsonify(data)
if period == "last 7 days":
delta = today - datetime.timedelta(days=7)
filtered_data = [
item
for item in data
if delta <= datetime.datetime.strptime(item["date"], "%Y-%m-%d") <= today
]
sorted_data = sorted(filtered_data, key=lambda x: x["date"])
elif period == "last 28 days":
delta = today - datetime.timedelta(days=28)
filtered_data = [
item
for item in data
if delta <= datetime.datetime.strptime(item["date"], "%Y-%m-%d") <= today
]
sorted_data = sorted(filtered_data, key=lambda x: x["date"])
elif period == "last 365 days":
delta = today - datetime.timedelta(days=365)
filtered_data = [
item
for item in data
if delta <= datetime.datetime.strptime(item["date"], "%Y-%m-%d") <= today
]
sorted_data = sorted(filtered_data, key=lambda x: x["date"])
elif period == "last 2 years":
delta = today - datetime.timedelta(days=730)
filtered_data = [
item
for item in data
if delta <= datetime.datetime.strptime(item["date"], "%Y-%m-%d") <= today
]
sorted_data = sorted(filtered_data, key=lambda x: x["date"])
else:
sorted_data = sorted(data, key=lambda x: x["date"])
@app.route('/download/<filename>', methods=['GET'])
return jsonify(sorted_data)
@app.route("/download/<filename>", methods=["GET"])
def download_file(filename):
try:
return send_from_directory(FILES_DIRECTORY, filename, as_attachment=True)
except FileNotFoundError:
abort(404)
if __name__ == '__main__':
app.run(debug=True)
if __name__ == '__main__':
if __name__ == "__main__":
app.run()

5
backend/requirements.txt Normal file
View File

@ -0,0 +1,5 @@
flask
flask_cors
orjson
gunicorn

View File

@ -4,11 +4,11 @@ toc: False
# Grounded Insights from Open Data
This site is currently under construction. The direction I intend for this site to take is as a place to publish analytical insights derived from open data. I have a page called [Data Lab](/data-lab) where I publish interactive analytical dashboards, a blog to publish tutorials and thoughts on various related topics, and a [data downloads](/data-download) page for data access.
**This site is currently under construction**.
I'm interested in a broad set of topics such as Linux, analytics and data engineering, GIS and bitcoin. So expect to see content related to these topics published on this site.
I intend for this to be a place to publish my personal work to share with others. I have a page called [Data Lab](/data-lab) where I publish interactive analytical dashboards based on open data, a blog to publish tutorials and thoughts I have on various topics, and a [data downloads](/data-downloads) page for data access.
I strongly believe in the philosophy of [Free Software](https://www.gnu.org/philosophy/free-sw.html) and [Open Data](https://en.wikipedia.org/wiki/Open_data). Therefore, all material on this site is released into the public domain unless otherwise specified. For more information, see [here](/license).
I'm interested in a broad set of topics such as Linux, analytics and data engineering, Geographic Information Systems (GIS) and bitcoin. So expect to see content related to these topics published on this site.
### Explore Based Data

View File

@ -9,16 +9,13 @@ toc: false
My name is Sam Chance, and this is my personal site.
I'm an independent Analytics Engineer with a passion for working with data. I built this website as a place to publish my personal work.
I'm a professional Analytics Engineer with a passion for working with data. I built this website as a place to publish my personal work.
If you wish to work with me, then please email me on *contact@sjplab.com*.
More about my professional life [here](/cv).
### Shortcuts to some of my work:
- [Based Data Lab](/data-lab) A selection of charts and metrics obtained from public data
- [Data Lab](/data-lab) A selection of charts and metrics obtained from public data
- [Map Printing Service](https://semitamaps.com) A free map printing service based on Openstreetmaps
@ -28,7 +25,7 @@ More about my professional life [here](/cv).
### Software I use:
- [**Neovim**](https://neovim.io/) for text editing (my neovim config is part of my [nixos](https://git.bitlab21.com/sam/nixos) configuration)
- [**Neovim**](https://neovim.io/) for text editing (my neovim config is part of my [nixos](https://git.bitlab21.com/sam/nixos/src/branch/master/home/common/core/nixvim) configuration)
- I use **Linux** on all my machines

View File

@ -51,7 +51,7 @@ Next we can run the following command to download the rasters. This will take so
aws s3 cp s3://raster/SRTM_GL1/ . --recursive --endpoint-url https://opentopography.s3.sdsc.edu --no-sign-request
{{</ highlight >}}
If you'd prefer to download specific rasters or rasters for a region instead, you can checkout this [website](https://dwtkns.com/srtm30m/).
If you'd prefer to download specific rasters or rasters for a region instead of downloading them all, you can select regions for download from the OpenTopography [website](https://portal.opentopography.org/raster?opentopoID=OTSRTM.082015.4326.1) using the interactive map.
## Using raster2pgsql to import raster tiles into PostGIS
Now we have the data downloaded on our system, we can import it into our database.
@ -98,9 +98,9 @@ So we have just over 12 million 128x128 tiles in the database.
## Raster Clipping
Now we have global SRTM data loaded in our local database, we can extract any of the tiles for further analysis and access this using any application.
Now we have global SRTM data loaded in our local database, we can extract the tiles we want for further analysis.
Here I'll demonstrate using the following PostGIS commands: `st_clip`, `st_intersects` and `st_union` to create a digital elevation table for singapore and access this from from within QGIS.
Here we'll create a digital elevation raster for Singapore to demonstrate using the following PostGIS commands: `st_clip`, `st_intersects` and `st_union`, then import this into QGIS to style and visualise the results.
I already have countries vector data in my Postgres database that I extracted from OpenStreetMaps. You can download a pg_dump of this [here](/data/countries.sql) to insert into your database. Alternatively, I have a post [here](/blogs/import-osm-countries-data) that explains the process to do this manually.
@ -224,3 +224,6 @@ This DEM raster of Singapore is available for download from the downloads page [
#### Citations
NASA Shuttle Radar Topography Mission (SRTM)(2013). Shuttle Radar Topography Mission (SRTM) Global. Distributed by OpenTopography. https://doi.org/10.5069/G9445JDF. Accessed: 2024-08-06
#### Attribution and License
© [OpenStreetMap](https://www.openstreetmap.org/copyright)

View File

@ -1,28 +0,0 @@
# Sam Chance
## Analytics Engineer
Analytics Engineer with over 4 years experience in designing and implementing data models, pipelines, and analytics solutions. Proficient in SQL, data warehousing, dbt and building dashboards for company metrics.
## Skills
- SQL
- Python
- Scripting/Programming
- Data Warehousing
- Data Modelling
- DBT
- Data and Statistical Analysis
- System Administration
## Work Experience
### Growth Analyst
What3Words - May 2020 to Feb 2022
### Analytics Engineer
What3Words - Feb 2022 to Apr 2024
## Education
### MSc Marine Biology
Bangor University - 2017 to 2018
### BSc Marine Biology & Zoology
Bangor University - 2008 to 2011

View File

@ -11,7 +11,10 @@ tags: ["QGIS", "SRTM", "DEM", "Raster", "download"]
{{< figure src="/pics/blog/batch-import-postgis-rasters/singapore-final.webp" width="300">}}
Download the Digital Elevation Model featured in [this](/blog/batch-import-postgis-rasters/) blog.
{{< download-data src="http://localhost:5000/download/singapore-srtm-dem.tif" name="singapore-srtm-dem.tif" >}}
{{< download-data src="/singapore-srtm-dem.tif" name="singapore-srtm-dem.tif" >}} (9.6MB)
#### Citations
NASA Shuttle Radar Topography Mission (SRTM)(2013). Shuttle Radar Topography Mission (SRTM) Global. Distributed by OpenTopography. https://doi.org/10.5069/G9445JDF. Accessed: 2024-08-06
#### Attribution and License
© [OpenStreetMap](https://www.openstreetmap.org/copyright)

View File

@ -10,7 +10,5 @@ tags: ["Bitcoin", "Stats"]
---
This chart shows historical median daily feerate percentiles for the Bitcoin
protocol. The data represents a daily aggregation of all blocks. This data was
extracted from the blockchain using the `bitcoin-cli getblockstats` command.
protocol.
{{< chart src="/js/feerate-percentile.js" >}}

View File

@ -8,13 +8,19 @@ summary: "This analysis uses OpenStreetMaps data to chart the yearly growth of b
tags: ["Bitcoin", "Stats", "OpenStreetMaps"]
---
The table below illustrates growth of businesses worldwide that accept bitcoin as payment for products or services. The accompanying chart displays the yearly cumulative number of bitcoin-accepting businesses for the countries selected in the table. The data is sourced from OpenStreetMaps and is updated approximately every 2 hours.
The table below illustrates growth of businesses worldwide that accept bitcoin as payment for products or services. The accompanying chart displays the cumulative number of bitcoin-accepting businesses for the countries selected in the table. The data is sourced from OpenStreetMaps and is updated approximately every 2 hours.
You can select the growth period of interest from the drop-down, which updates the values in the table. The table shows the ***Previous*** value, which was the number of businesses *n* days ago specified in the drop-down. The ***Current*** value is the number of businesses as of the latest update. The table also shows the ***Absolute Difference***, and the ***Percent Difference*** between this period.
The chart always reflects the countries selected in the table. There is a zoom feature on the chart to focus in on a period of interest.
The chart always reflects the countries selected in the table.
<br/>
Select growth period: {{< dropdown-filter id=cumulative_period_type select="365 day,28 day,7 day,1 day" >}}
{{< chart src="/js/bitcoin-business-growth-chart.js" >}}
{{< table src="/js/bitcoin-business-growth-table.js" >}}
#### Attribution and License
Data obtained from © [OpenStreetMap](https://www.openstreetmap.org/copyright)
Licensed under the [ODbl](https://opendatacommons.org/licenses/odbl/)

View File

@ -8,6 +8,6 @@ summary: "Timeseries chart showing the Bitcoin network hashrate and difficulty."
tags: ["Bitcoin", "Stats", "Hashrate"]
---
The estimated hashrate and difficulty of the Bitcoin network, accompanied by the 28-day moving average.
This chart shows the estimated hashrate and difficulty of the Bitcoin network, accompanied by the 28-day moving average. This information is extracted from a bitcoin node using the `bitcoin-cli getnetworkhashps` command.
{{< chart src="/js/hashrate.js" >}}

View File

@ -9,6 +9,6 @@ draft: false
tags: ["Bitcoin", "Stats"]
---
Total daily aggregated miner income denominated in USD for that day.
The following chart shows daily miner revenue in USD for the period selected in the dropdown. This information is based on the sum of bitcoin mined each day (i.e. the block-subsidy) plus the transaction fees. Price data is obtained from [CoinGecko](https://www.coingecko.com/).
{{< chart src="/js/miner-rewards.js" >}}

View File

@ -8,7 +8,7 @@ summary: "Daily bitcoin price. Data is obtained from CoinGecko using their publi
tags: ["Bitcoin", "Stats"]
---
Daily bitcoin price. Data is obtained from CoinGecko using their
Daily bitcoin price. Data is obtained from [CoinGecko](https://www.coingecko.com/) using their
public API.
{{< bitcoin-price >}}

View File

@ -0,0 +1,11 @@
---
title: "Global Protected Mangroves"
date: 2024-09-04T16:00:57+01:00
author:
name: "Sam Chance"
header_image: "/pics/charts/price.webp"
summary: "Daily bitcoin price. Data is obtained from CoinGecko using their public API."
tags: ["Bitcoin", "Stats"]
---
{{< map >}}

View File

@ -1,3 +1,21 @@
# License
All work on this site is licensed using [unlicense](https://unlicense.org/). This effectively means all of the content hosted on https://baseddata.io and in the baseddata repository at https://git.bitlab21.com/sam/bitlab21.com is in the public domain. You can use this material as you wish. Attribution is appreciated, but not required.
Where possible, all original work on this site that has been created and published by me is licensed using [CC BY-SA 4.0](https://creativecommons.org/licenses/by-sa/4.0/).
You are free to:
- Share — copy and redistribute the material in any medium or format for any purpose, even commercially.
- Adapt — remix, transform, and build upon the material for any purpose, even commercially.
The licensor cannot revoke these freedoms as long as you follow the license terms.
Under the following terms:
- Attribution — You must give appropriate credit , provide a link to the license, and indicate if changes were made . You may do so in any reasonable manner, but not in any way that suggests the licensor endorses you or your use.
- ShareAlike — If you remix, transform, or build upon the material, you must distribute your contributions under the same license as the original.
- No additional restrictions — You may not apply legal terms or technological measures that legally restrict others from doing anything the license permits.
Notices:
You do not have to comply with the license for elements of the material in the public domain or where your use is permitted by an applicable exception or limitation .
No warranties are given. The license may not give you all of the permissions necessary for your intended use. For example, other rights such as publicity, privacy, or moral rights may limit how you use the material.

View File

@ -1,6 +1,9 @@
baseURL = 'https://baseddate.io/'
baseURL = 'https://baseddata.io'
languageCode = 'en-gb'
title = 'baseddata.io'
title = 'Based Data'
[params]
apiURL = 'http://localhost:5000'
[markup.highlight]
pygmentsUseClasses = false

View File

@ -1,7 +1,7 @@
<script src="https://cdn.jsdelivr.net/npm/echarts@5.5.1/dist/echarts.min.js"></script>
<section class="chart-container">
<div id="chart-modifiers"></div>
<div id="chart">
<canvas id="{{ .id }}"></canvas>
<script src="{{ .src }}"></script>
</div>
</section>

View File

@ -1,8 +1,9 @@
<footer>
<div id="footer">
<p>
baseddata.io by Sam Chance.
<a href="/license">Uncopywrited.</a>
baseddata.io by Sam Chance. | Built with
<a href="https://gohugo.io/">Hugo</a>
| <a href="/license">License</a>
</p>
</div>
</footer>

View File

@ -1,7 +1,7 @@
<header>
<nav class="navbar" role="navigation">
<div class="navbar__left">
<a href="/"><strong>Based Data</strong></a>
<a href="/"><strong>BASED DATA</strong></a>
</div>
<div class="navbar__right">
<div class="navbar-links">{{ partial "navbarlinks.html" . }}</div>

34
layouts/partials/map.html Normal file
View File

@ -0,0 +1,34 @@
<script src="https://labs.geomatico.es/maplibre-cog-protocol/dist/index.js"></script>
<script src="https://unpkg.com/maplibre-gl/dist/maplibre-gl.js"></script>
<link
rel="stylesheet"
href="https://unpkg.com/maplibre-gl/dist/maplibre-gl.css"
/>
<section class="map-container">
<div id="map" style="height: 400px"></div>
<script>
let map = new maplibregl.Map({
container: "map",
style: "https://tiles.semitamaps.com/styles/maptiler-basic/style.json",
center: [117.9588, 5.81513],
zoom: 11,
});
maplibregl.addProtocol("cog", MaplibreCOGProtocol.cogProtocol);
map.on("load", () => {
map.addSource("imageSource", {
type: "raster",
url: "cog://http://localhost:5000/download/10072.tif",
tileSize: 256,
minzoom: 0,
});
map.addLayer({
id: "imageLayer",
source: "imageSource",
type: "raster",
});
});
</script>
</section>

View File

@ -4,7 +4,7 @@
<p id="price"></p>
<script>
fetch("https://api.baseddata.io/get_json/final__price.json")
fetch(`${"{{ .Site.Params.apiURL }}"}/get_json/final__price.json`)
.then((response) => response.json())
.then((data) => {
var lastElement = data[data.length - 1];

View File

@ -1,2 +1,5 @@
{{ $id := .Get "src" | md5 }}
{{ partial "chart.html" (dict "src" (.Get "src") "id" $id) }}
<script>
const apiURL = "{{ .Site.Params.apiURL }}";
</script>
{{ $id := .Get "src" | md5 }} {{ partial "chart.html" (dict "src" (.Get "src")
"id" $id) }}

View File

@ -5,7 +5,12 @@
<script>
async function downloadFile(url, name) {
try {
const response = await fetch(url);
downloadUrl = `${"{{ .Site.Params.apiURL }}"}/download${url}`
console.log("Downloading from url:",downloadUrl)
const response = await fetch(downloadUrl);
if (!response.ok) {
throw new Error('Network response was not ok');
}
const blob = await response.blob();
const link = document.createElement('a');
link.href = URL.createObjectURL(blob);
@ -13,6 +18,7 @@
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
URL.revokeObjectURL(link.href); // Clean up the object URL
} catch (error) {
console.error('Error downloading the file:', error);
}

View File

@ -1,7 +0,0 @@
<select id={{ .Get "id" }} class="dropdownFilter">
{{ with .Get "select" }}
{{ range $index, $element := split . "," }}
<option value="{{ $element }}">{{ $element }}</option>
{{ end }}
</select>
{{ end }}

View File

@ -0,0 +1 @@
{{ partial "map.html" }}

View File

@ -1,2 +1,2 @@
{{ $id := .Get "src" | md5 }}
{{ partial "table.html" (dict "src" (.Get "src") "id" $id) }}
{{ $id := .Get "src" | md5 }} {{ partial "table.html" (dict "src" (.Get "src")
"id" $id) }}

View File

@ -6,24 +6,39 @@
</div>
<div class="article-card-container">
{{ range.Pages }}
<a class="article-card" href="{{ .RelPermalink }}">
<div class="article-card">
<div class="article-card-info">
<div class="article-card-thumb">
<a href="{{ .RelPermalink }}">
<img
class="article-card-thumbnail"
src="{{ .Params.header_image }}"
/>
</a>
</div>
<div class="article-card-summary">
{{ template "partials/get-tags.html" . }}
<a href="{{ .RelPermalink }}">
<h3><strong>{{ .Title | safeHTML }}</strong></h3>
<p>{{ .Summary | safeHTML }}</p>
</a>
<p>
{{ .Summary | safeHTML }}
<i class="reading-time"
>({{ .ReadingTime }} minute{{ if (ne .ReadingTime 1) }}s{{ end
}})</i
>
</p>
<br />
<div class="article-card-author-row">
{{ with .Params.author }}
<strong><p class="author-name">{{ .name }}</p></strong>
{{ end }}
<time>{{ .Date.Format "January 2, 2006" }}</time>
</div>
</div>
</div>
</a>
</div>
{{ end }}
</div>
</div>

View File

@ -9,10 +9,22 @@ pkgs.mkShell
python312Packages.pandas
python312Packages.orjson
hugo
tmux
];
shellHook = ''
${pkgs.cowsay}/bin/cowsay "Welcome to the bitlab development environment!" | ${pkgs.lolcat}/bin/lolcat
${pkgs.cowsay}/bin/cowsay "Welcome to the baseddata.io development environment!" | ${pkgs.lolcat}/bin/lolcat
get_session=$(tmux list-session | grep "baseddata")
if [ -z "$get_session" ];
then
tmux new-session -d -s baseddata
tmux split-window -h
tmux send-keys -t 0 "hugo server" C-m
tmux send-keys -t 1 "cd backend && python app.py" C-m
echo "Baseddata running in dev tmux shell"
fi
'';
}

View File

@ -16,4 +16,9 @@
margin-top: 20px;
display: flex;
justify-content: center;
flex-direction: column;
}
#chart-modifiers {
display: flex;
}

View File

@ -52,6 +52,7 @@
.navbar__left a {
text-decoration: none !important;
font-weight: 540;
color: var(--text-color) !important;
font-size: 22px;
}

View File

@ -133,7 +133,10 @@ footer {
color: var(--text-color);
padding: 20px;
height: 10vh;
display: flex;
justify-content: space-between;
border-top: var(--border-width) var(--border-style) var(--border-color);
}
#footer {
display: flex;
justify-content: center;
}

View File

@ -1,9 +1,14 @@
let chartData = [];
let myChart;
async function fetchDataForChart(str) {
let periodIndex = 3;
const periods = ["1 day", "7 day", "28 day", "365 day"];
async function fetchDataForChart(str, period) {
try {
const apiEndpoint = `https://api.baseddata.io/bitcoin_business_growth_by_country?cumulative_period_type=365 day&countries=${str}`;
const apiEndpoint = `${apiURL}/bitcoin_business_growth_by_country?cumulative_period_type=${period}&countries=${str}`;
console.log("Fetching from " + apiEndpoint);
const response = await fetch(apiEndpoint);
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
@ -38,10 +43,11 @@ function updateChart() {
axisTick: axisTick,
axisLabel: axisLabel,
axisLine: axisLine,
type: "time",
type: "category",
},
yAxis: {
axisTick: axisTick,
scale: true,
splitLine: {
show: false,
},
@ -69,18 +75,21 @@ function handleCheckboxChange(event) {
if (event.target.type === "checkbox") {
const boxChecked = event.target.checked;
const boxId = event.target.id;
let selectedPeriod = getPeriodFromDropdown();
// Remove unchecked boxes
if (boxChecked === false) {
delete chartData[boxId];
updateChart();
// Add checked boxes
} else {
fetchDataForChart(boxId);
fetchDataForChart(boxId, selectedPeriod);
}
}
}
document.addEventListener("reloadTable", () => {
document.addEventListener("DOMContentLoaded", function () {
periodDropdown(periods, periodIndex);
document.addEventListener("reloadTable", () => {
myChart = echarts.init(document.getElementById("chart"));
jsonTableCheckedBoxes = document.querySelectorAll(
'#jsonTableContainer input[type="checkbox"]:checked',
@ -89,10 +98,12 @@ document.addEventListener("reloadTable", () => {
(checkbox) => checkbox.id,
);
const str = checkedBoxes.join(",");
let selectedPeriod = getPeriodFromDropdown();
chartData = [];
fetchDataForChart(str);
fetchDataForChart(str, selectedPeriod);
jsonTable = document.getElementById("jsonTableContainer");
jsonTable.removeEventListener("change", handleCheckboxChange);
jsonTable.addEventListener("change", handleCheckboxChange);
});
});

View File

@ -1,12 +1,9 @@
async function fetchDataForTable() {
try {
const dropdown = document.querySelector(".dropdownFilter");
let selectedIndex = dropdown.selectedIndex;
let selectedValue = dropdown.options[selectedIndex].value;
const apiEndpoint =
"https://api.baseddata.io/bitcoin_business_growth_by_country?latest_date=true";
selectedPeriod = getPeriodFromDropdown();
const apiEndpoint = `${apiURL}/bitcoin_business_growth_by_country?latest_date=true`;
const response = await fetch(
apiEndpoint + `&cumulative_period_type=${selectedValue}`,
apiEndpoint + `&cumulative_period_type=${selectedPeriod}`,
);
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
@ -89,10 +86,10 @@ function createTable(data) {
);
}
window.onload = () => {
const dropdown = document.querySelector(".dropdownFilter");
document.addEventListener("DOMContentLoaded", function () {
const dropdown = document.getElementById("select-period-dropdown");
fetchDataForTable();
dropdown.addEventListener("change", () => {
fetchDataForTable();
});
};
});

View File

@ -1,9 +1,18 @@
let dataArr = [];
const myChart = echarts.init(document.getElementById("chart"));
const filename = "final__price.json";
async function fetchDataForChart() {
const periods = [
"all time",
"last 7 days",
"last 28 days",
"last 365 days",
"last 2 years",
];
async function fetchDataForChart(selectedValue) {
try {
const apiEndpoint = "https://api.baseddata.io/get_json/final__price.json";
const apiEndpoint = `${apiURL}/get_json/${filename}?period=${selectedValue}`;
const response = await fetch(apiEndpoint);
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
@ -27,7 +36,7 @@ function initEchart(dataArr) {
axisLine: axisLine,
},
grid: grid,
dataZoom: dataZoom(),
dataZoom: dataZoom(0),
yAxis: [
{
type: "value",
@ -62,4 +71,14 @@ function initEchart(dataArr) {
myChart.setOption(option);
}
fetchDataForChart();
document.addEventListener("DOMContentLoaded", function () {
let periodIndex = 2;
periodDropdown(periods, periodIndex);
fetchDataForChart(periods[periodIndex]);
const selectElement = document.getElementById("select-period-dropdown");
selectElement.addEventListener("change", function (event) {
const selectedValue = event.target.value;
fetchDataForChart(selectedValue);
});
});

View File

@ -31,7 +31,7 @@ const toolboxParams = {
dataZoom: {
yAxisIndex: "none",
},
restore: {},
dataView: {},
saveAsImage: {
pixelRatio: 2,
},
@ -73,13 +73,10 @@ const yaxisTextStyle2 = {
color: textColor,
};
function dataZoom(start = 90, end = 100, bottom = 15, height = 15) {
function dataZoom() {
const dataZoom = [
{
start: start,
end: end,
bottom: bottom,
height: height,
type: "inside",
},
];
@ -106,6 +103,35 @@ function nFormatter(value, digits) {
: "0";
}
function periodDropdown(periods, defaultIndex = 0) {
const modifiers = document.getElementById("chart-modifiers");
const dropdownContainer = document.createElement("div");
const dropdown = document.createElement("select");
const textNode = document.createTextNode("Select period: ");
dropdownContainer.id = "dropdown-container";
dropdown.id = "select-period-dropdown";
dropdownContainer.appendChild(textNode);
dropdownContainer.appendChild(dropdown);
modifiers.appendChild(dropdownContainer);
periods.forEach((period, index) => {
const option = document.createElement("option");
if (index === defaultIndex) {
option.selected = true;
}
option.value = period;
option.textContent = period;
dropdown.appendChild(option);
});
}
function getPeriodFromDropdown() {
let dropdown = document.getElementById("select-period-dropdown");
let selectedIndex = dropdown.selectedIndex;
return dropdown.options[selectedIndex].value;
}
window.addEventListener("resize", function () {
if (myChart != null && myChart != undefined) {
myChart.resize();

View File

@ -1,10 +1,18 @@
let dataArr = [];
const myChart = echarts.init(document.getElementById("chart"));
const filename = "final__feerate_percentiles.json";
async function fetchDataForChart() {
const periods = [
"all time",
"last 7 days",
"last 28 days",
"last 365 days",
"last 2 years",
];
async function fetchDataForChart(selectedValue) {
try {
const apiEndpoint =
"https://api.baseddata.io/get_json/final__feerate_percentiles.json";
const apiEndpoint = `${apiURL}/get_json/${filename}?period=${selectedValue}`;
const response = await fetch(apiEndpoint);
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
@ -39,7 +47,7 @@ function initEchart(dataArr) {
axisLine: axisLine,
},
grid: grid,
dataZoom: dataZoom((start = 98)),
dataZoom: dataZoom(0),
series: [
{
type: "line",
@ -105,4 +113,15 @@ function initEchart(dataArr) {
myChart.setOption(option);
}
fetchDataForChart();
document.addEventListener("DOMContentLoaded", function () {
let periodIndex = 2;
periodDropdown(periods, periodIndex);
fetchDataForChart(periods[periodIndex]);
const selectElement = document.getElementById("select-period-dropdown");
selectElement.addEventListener("change", function (event) {
const selectedValue = event.target.value;
fetchDataForChart(selectedValue);
});
});

View File

@ -1,10 +1,17 @@
let dataArr = [];
const myChart = echarts.init(document.getElementById("chart"));
const filename = "final__hashrate.json";
const periods = [
"all time",
"last 7 days",
"last 28 days",
"last 365 days",
"last 2 years",
];
async function fetchDataForChart() {
async function fetchDataForChart(selectedValue) {
try {
const apiEndpoint =
"https://api.baseddata.io/get_json/final__hashrate.json";
const apiEndpoint = `${apiURL}/get_json/${filename}?period=${selectedValue}`;
const response = await fetch(apiEndpoint);
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
@ -33,7 +40,7 @@ function initEchart(dataArr) {
axisLine: axisLine,
},
grid: grid,
dataZoom: dataZoom(),
dataZoom: dataZoom(0),
yAxis: [
{
type: "value",
@ -106,4 +113,15 @@ function initEchart(dataArr) {
myChart.setOption(option);
}
fetchDataForChart();
document.addEventListener("DOMContentLoaded", function () {
let periodIndex = 2;
periodDropdown(periods, periodIndex);
fetchDataForChart(periods[periodIndex]);
const selectElement = document.getElementById("select-period-dropdown");
selectElement.addEventListener("change", function (event) {
const selectedValue = event.target.value;
fetchDataForChart(selectedValue);
});
});

View File

@ -1,10 +1,17 @@
let dataArr = [];
const myChart = echarts.init(document.getElementById("chart"));
const filename = "final__miner_rewards.json";
const periods = [
"all time",
"last 7 days",
"last 28 days",
"last 365 days",
"last 2 years",
];
async function fetchDataForChart() {
async function fetchDataForChart(selectedValue) {
try {
const apiEndpoint =
"https://api.baseddata.io/get_json/final__miner_rewards.json";
const apiEndpoint = `${apiURL}/get_json/${filename}?period=${selectedValue}`;
const response = await fetch(apiEndpoint);
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
@ -17,9 +24,37 @@ async function fetchDataForChart() {
}
function initEchart(dataArr) {
console.log(dataArr);
const option = {
backgroundColor: backgroundColor,
tooltip: tooltip,
tooltip: {
...tooltip,
formatter: function (params) {
let colors = ["#ee6666", "#000000", "#b0da9d", "#8699d5"];
let colorSpan = (color) =>
'<span style="display:inline-block;margin-right:1px;border-radius:5px;width:9px;height:9px;background-color:' +
color +
'"></span>';
let tooltip = "<p>" + params[0].axisValue + "</p>";
params.reverse().forEach((item, index) => {
let color = colors[index % colors.length];
let labels =
"<p>" +
colorSpan(color) +
" " +
item.seriesName +
": " +
nFormatter(item.data, 3);
("</p>");
tooltip += labels;
});
return tooltip;
},
valueFormatter(value, index) {
return nFormatter(value, 3);
},
},
toolbox: toolboxParams,
xAxis: {
data: dataArr.map((row) => row.date),
@ -28,13 +63,13 @@ function initEchart(dataArr) {
axisLine: axisLine,
},
grid: grid,
dataZoom: dataZoom(97),
dataZoom: dataZoom(0),
yAxis: [
{
type: "value",
name: "Rewards (USD)",
nameLocation: "middle",
nameGap: 35,
nameGap: 30,
nameTextStyle: textStyleMain,
position: "left",
alignTicks: true,
@ -52,7 +87,7 @@ function initEchart(dataArr) {
},
{
type: "value",
name: "Block Subsidy (BTC)",
name: "Subsidy (BTC)",
nameLocation: "middle",
nameGap: 20,
nameTextStyle: {
@ -75,8 +110,7 @@ function initEchart(dataArr) {
series: [
{
type: "line",
name: "Daily Subsidy (USD)",
smooth: true,
name: "Subsidy (USD)",
stack: "Total",
areaStyle: {},
symbol: "none",
@ -87,8 +121,7 @@ function initEchart(dataArr) {
},
{
type: "line",
name: "Daily Fees (USD)",
smooth: true,
name: "Fees (USD)",
stack: "Total",
areaStyle: {},
symbol: "none",
@ -99,8 +132,7 @@ function initEchart(dataArr) {
},
{
type: "line",
name: "Daily Total Reward (USD)",
smooth: true,
name: "Total (USD)",
symbol: "none",
lineStyle: {
width: 1,
@ -124,4 +156,14 @@ function initEchart(dataArr) {
myChart.setOption(option);
}
fetchDataForChart();
document.addEventListener("DOMContentLoaded", function () {
let periodIndex = 2;
periodDropdown(periods, periodIndex);
fetchDataForChart(periods[periodIndex]);
const selectElement = document.getElementById("select-period-dropdown");
selectElement.addEventListener("change", function (event) {
const selectedValue = event.target.value;
fetchDataForChart(selectedValue);
});
});