Problem scenario
You want to write a Flask program to display the high and low prices of a given cryptocurrency for a given day. You want the output to include the volume too. How do you do this?
Solution
Prerequisite
This assumes that you have installed Flask and pandas.
Procedures
Run this program. You may want to name it __crypto__.py
Then go to the IP address in a web browser or use curl. The way to compose the URL, see the usage instructions.
"""
Usage instructions:
Once running, the format of the URL to curl will look like one of these:
http://127.0.0.1:5000/crypto/BTC/2019-06-21
http://127.0.0.1:5000/crypto/ETH/2020-10-01
Change the dates to the date you want to see information for.
Change the currency symbol to the symbol you want to examine.
Written in March of 2021 by www.continualintegration.com
It was adapted from these postings:
https://towardsdatascience.com/cryptocurrency-analysis-with-python-buy-and-hold-c3b0bc164ffa
https://towardsdatascience.com/cryptocurrency-analysis-with-python-macd-452ceb251d7c?gi=12b983021ac2
"""
from flask import Flask, Response
import pandas as pd
import requests
from datetime import datetime
class Retriever:
def get_filename(from_symbol, to_symbol,
exchange, datetime_interval, download_date):
return '%s_%s_%s_%s_%s.csv' % (from_symbol, to_symbol,
exchange, datetime_interval, download_date)
def download_data(from_symbol, to_symbol, exchange, datetime_interval):
base_url = 'https://min-api.cryptocompare.com/data/histo'
url = '%s%s' % (base_url, datetime_interval)
params = {'fsym': from_symbol, 'tsym': to_symbol,
'limit': 2000, 'aggregate': 1,
'e': exchange}
request = requests.get(url, params=params)
data = request.json()
return data
def convert_to_dataframe(data):
df = pd.json_normalize(data, ['Data'])
df['datetime'] = pd.to_datetime(df.time, unit='s')
df = df[['datetime', 'low', 'high', 'open',
'close', 'volumefrom', 'volumeto']]
return df
def filter_empty_datapoints(df):
indices = df[df.sum(axis=1) == 0].index
df = df.drop(indices)
return df
def file_creator(from_symbol, to_symbol, exchange, datetime_interval):
data = Retriever.download_data(from_symbol, to_symbol,
exchange, datetime_interval)
df = Retriever.convert_to_dataframe(data)
df = Retriever.filter_empty_datapoints(df)
latest_date = datetime.now().date().isoformat()
filename = Retriever.get_filename(from_symbol, to_symbol, exchange,
datetime_interval, latest_date)
df.to_csv(filename, index=False)
def read_dataset(filename):
df = pd.read_csv(filename)
df.datetime = pd.to_datetime(df.datetime) # change to datetime
df = df.set_index('datetime')
df = df.sort_index() # sort by datetime
return df
def processor(from_symbol, date_to_see):
to_symbol = 'USD'
exchange = 'Coinbase' # "Bitstamp" is a valid option among others.
datetime_interval = 'day'
error_message = "INVALID FORMAT. The date must be in the format of YYYY-MM-DD. Use leading 0 for single digit months or days."
if date_to_see[0:4].isnumeric():
pass
else:
return "Letters found. " + error_message
if date_to_see[5:7].isnumeric():
pass
else:
return "Letters found. " + error_message
if date_to_see[8:].isnumeric():
pass
else:
return "Letters found. " + error_message
if len(date_to_see) != 10:
return error_message
if date_to_see[4] != "-":
return error_message
if date_to_see[7] != "-":
return error_message
if int(date_to_see[0]) > 2:
return "Year was too far in the future. "
if int(date_to_see[0]) < 2:
return "Year was too far in the past. "
Retriever.file_creator(from_symbol, to_symbol, exchange,
datetime_interval)
latest_date = datetime.now().date().isoformat()
btc_date = open((Retriever.get_filename(from_symbol, to_symbol,
exchange, datetime_interval, latest_date)), 'r')
get_top = btc_date.read()[0:-1]
for line in get_top.split():
if line.split(",")[0] == date_to_see:
return line
app = Flask(__name__)
@app.route("/")
def default():
return Response("remember the path is /crypto/BTC/2020-01-01 "), 200
@app.route("/crypto/<string:symbol>/<string:day_var>", strict_slashes=False)
def crypto(symbol, day_var):
res = Retriever.processor(symbol, day_var)
portion = ", the format is as follows: date,low,high,open,close,volume_from,volume_to"
compose = "For " + symbol + portion + "\n" + res
return Response(compose), 200
if __name__ == "__main__":
#app.run(debug=True) # Uncomment out this line, comment out line below to run on 127.0.0.1
app.run(host='192.168.1.15', debug=True)
If you want to receive free cryptocurrency by just learning more, try Coinbase; it is ideal for Americans. For Europeans, the platform/company Iconomi.com can allow you to buy crypto or learn more.