Features (crypto): adds two features to Defi menu (#1180)

* added new terra features

* removed wrong multiplication

* allow aterra without --address arg

* Updating tests : crypto/defi

Co-authored-by: Chavithra PARANA <chavithra@gmail.com>
This commit is contained in:
jose-donato
2022-01-14 09:30:25 +00:00
committed by GitHub
parent 10c36013f0
commit 4d26b3f7db
15 changed files with 529 additions and 1 deletions

View File

@@ -6,7 +6,12 @@ import argparse
from typing import List
from prompt_toolkit.completion import NestedCompleter
from gamestonk_terminal.cryptocurrency.defi import graph_model, coindix_model
from gamestonk_terminal.cryptocurrency.defi import (
graph_model,
coindix_model,
terraengineer_model,
terraengineer_view,
)
from gamestonk_terminal.parent_classes import BaseController
from gamestonk_terminal import feature_flags as gtff
from gamestonk_terminal.menu import session
@@ -45,6 +50,8 @@ class DefiController(BaseController):
"swaps",
"stats",
"vaults",
"ayr",
"aterra",
]
def __init__(self, queue: List[str] = None):
@@ -53,6 +60,8 @@ class DefiController(BaseController):
if session and gtff.USE_PROMPT_TOOLKIT:
choices: dict = {c: {} for c in self.controller_choices}
choices["aterra"]["--asset"] = {c: {} for c in terraengineer_model.ASSETS}
choices["aterra"] = {c: {} for c in terraengineer_model.ASSETS}
choices["llama"]["-s"] = {c: {} for c in llama_model.LLAMA_FILTERS}
choices["tokens"]["-s"] = {c: {} for c in graph_model.TOKENS_FILTERS}
choices["pairs"]["-s"] = {c: {} for c in graph_model.PAIRS_FILTERS}
@@ -84,9 +93,75 @@ Uniswap:
pairs Recently added pairs on Uniswap
pools Pools by volume on Uniswap
swaps Recent swaps done on Uniswap
TerraEngineer:
aterra Displays 30-day history of specified asset in terra address
ayr Displays 30-day history of anchor yield reserve
"""
print(help_text)
def call_aterra(self, other_args: List[str]):
parser = argparse.ArgumentParser(
add_help=False,
formatter_class=argparse.ArgumentDefaultsHelpFormatter,
prog="aterra",
description="""
Displays the 30-day history of an asset in a certain terra address.
[Source: https://terra.engineer/]
""",
)
parser.add_argument(
"--asset",
dest="asset",
type=str,
help="Terra asset {ust,luna,sdt} Default: ust",
default=terraengineer_model.ASSETS[0],
choices=terraengineer_model.ASSETS,
)
parser.add_argument(
"--address",
dest="address",
type=str,
help="Terra address. Valid terra addresses start with 'terra'",
required=True,
)
if other_args and not other_args[0][0] == "-":
other_args.insert(0, "--asset")
ns_parser = parse_known_args_and_warn(
parser, other_args, EXPORT_ONLY_RAW_DATA_ALLOWED
)
if ns_parser:
terraengineer_view.display_terra_asset_history(
export=ns_parser.export,
address=ns_parser.address,
asset=ns_parser.asset,
)
def call_ayr(self, other_args: List[str]):
"""Process ayr command"""
parser = argparse.ArgumentParser(
add_help=False,
formatter_class=argparse.ArgumentDefaultsHelpFormatter,
prog="ayr",
description="""
Displays the 30-day history of the Anchor Yield Reserve.
An increasing yield reserve indicates that the return on collateral staked by borrowers in Anchor
is greater than the yield paid to depositors. A decreasing yield reserve means yield paid
to depositors is outpacing the staking returns of borrower's collateral.
TLDR: Shows the address that contains UST that is paid on anchor interest earn.
[Source: https://terra.engineer/]
""",
)
ns_parser = parse_known_args_and_warn(
parser, other_args, EXPORT_ONLY_RAW_DATA_ALLOWED
)
if ns_parser:
terraengineer_view.display_anchor_yield_reserve(export=ns_parser.export)
def call_dpi(self, other_args: List[str]):
"""Process dpi command"""
parser = argparse.ArgumentParser(

View File

@@ -0,0 +1,48 @@
"""Terra Engineer model"""
__docformat__ = "numpy"
import requests
import pandas as pd
api_url = "https://terra.engineer/en"
ASSETS = ["ust", "luna", "sdt"]
def get_history_asset_from_terra_address(
asset: str = "ust", address: str = ""
) -> pd.DataFrame:
"""Returns historical data of an asset in a certain terra address
[Source: https://terra.engineer/]
Parameters
----------
asset : str
Terra asset {ust,luna,sdt}
address : str
Terra address. Valid terra addresses start with 'terra'
Returns
-------
pd.DataFrame
historical data
"""
if asset.lower() not in ASSETS:
raise Exception(f"Select a valid asset from {', '.join(ASSETS)}")
if not address.startswith("terra"):
raise Exception(
"Select a valid address. Valid terra addresses start with 'terra'"
)
response = requests.get(
f"{api_url}/terra_addresses/{address}/show_snapshot_data.json?asset={asset.lower()}"
)
if response.status_code != 200:
raise Exception(f"Status code: {response.status_code}. Reason: {response.text}")
data = response.json()
df = pd.DataFrame(data[0]["data"])
df["x"] = pd.to_datetime(df["x"])
return df

View File

@@ -0,0 +1,106 @@
"""Terra Engineer View"""
__docformat__ = "numpy"
import os
import matplotlib.pyplot as plt
from matplotlib import ticker, dates as mdates
from gamestonk_terminal.cryptocurrency.defi import terraengineer_model
from gamestonk_terminal.helper_funcs import (
export_data,
plot_autoscale,
long_number_format,
)
from gamestonk_terminal import feature_flags as gtff
from gamestonk_terminal.config_plot import PLOT_DPI
def display_terra_asset_history(
asset: str = "", address: str = "", export: str = ""
) -> None:
"""Displays the 30-day history of specified asset in terra address
[Source: https://docs.llama.fi/api]
Parameters
----------
asset : str
Terra asset {ust,luna,sdt}
address : str
Terra address. Valid terra addresses start with 'terra'
export : str
Export dataframe data to csv,json,xlsx file
"""
df = terraengineer_model.get_history_asset_from_terra_address(
address=address, asset=asset
)
fig, ax = plt.subplots(figsize=plot_autoscale(), dpi=PLOT_DPI)
ax.plot(df["x"], df["y"])
ax.set_xlabel("Time")
ax.tick_params(axis="x", labelrotation=45)
ax.set_xlim(df["x"].iloc[0], df["x"].iloc[-1])
dateFmt = mdates.DateFormatter("%m/%d/%Y")
fig.tight_layout(pad=4)
ax.xaxis.set_major_formatter(dateFmt)
ax.set_ylabel(f"{asset.upper()} Amount")
ax.grid(alpha=0.5)
ax.set_title(f"{asset.upper()} Amount in Address {address}")
ax.get_yaxis().set_major_formatter(
ticker.FuncFormatter(lambda x, _: long_number_format(x))
)
if gtff.USE_ION:
plt.ion()
plt.show()
print("")
export_data(
export,
os.path.dirname(os.path.abspath(__file__)),
"aterra",
df,
)
def display_anchor_yield_reserve(export: str = "") -> None:
"""Displays the 30-day history of the Anchor Yield Reserve.
[Source: https://docs.llama.fi/api]
Parameters
----------
export : str
Export dataframe data to csv,json,xlsx file
"""
df = terraengineer_model.get_history_asset_from_terra_address(
address="terra1tmnqgvg567ypvsvk6rwsga3srp7e3lg6u0elp8"
)
fig, ax = plt.subplots(figsize=plot_autoscale(), dpi=PLOT_DPI)
ax.plot(df["x"], df["y"])
ax.set_xlabel("Time")
ax.tick_params(axis="x", labelrotation=45)
ax.set_xlim(df["x"].iloc[0], df["x"].iloc[-1])
dateFmt = mdates.DateFormatter("%m/%d/%Y")
fig.tight_layout(pad=4)
ax.xaxis.set_major_formatter(dateFmt)
ax.set_ylabel("UST Amount")
ax.grid(alpha=0.5)
ax.set_title("Anchor UST Yield Reserve")
ax.get_yaxis().set_major_formatter(
ticker.FuncFormatter(lambda x, _: long_number_format(x))
)
if gtff.USE_ION:
plt.ion()
plt.show()
print("")
export_data(
export,
os.path.dirname(os.path.abspath(__file__)),
"ayr",
df,
)

View File

@@ -11,4 +11,6 @@ tokens
stats
pools
swaps
ayr
aterra --asset luna --address terra1tmnqgvg567ypvsvk6rwsga3srp7e3lg6u0elp8
exit

View File

@@ -0,0 +1,63 @@
interactions:
- request:
body: null
headers:
Accept:
- '*/*'
Accept-Encoding:
- gzip, deflate
Connection:
- keep-alive
User-Agent:
- python-requests/2.26.0
method: GET
uri: https://terra.engineer/en/terra_addresses/terra1tmnqgvg567ypvsvk6rwsga3srp7e3lg6u0elp8/show_snapshot_data.json?asset=ust
response:
body:
string: '[{"id":"UST","data":[{"x":"2021-12-16 00:00:00","y":77386761.1048762},{"x":"2021-12-17
00:00:00","y":77107417.4955988},{"x":"2021-12-18 00:00:00","y":76761418.06876892},{"x":"2021-12-19
00:00:00","y":76402060.63818446},{"x":"2021-12-20 00:00:00","y":76049371.1771107},{"x":"2021-12-21
00:00:00","y":75717916.11125192},{"x":"2021-12-22 00:00:00","y":75334594.8653725},{"x":"2021-12-23
00:00:00","y":74801529.79565395},{"x":"2021-12-24 00:00:00","y":74313496.35167404},{"x":"2021-12-25
00:00:00","y":73840418.004713},{"x":"2021-12-26 00:00:00","y":73372333.94158259},{"x":"2021-12-27
00:00:00","y":72928202.62041229},{"x":"2021-12-28 00:00:00","y":72397414.56039554},{"x":"2021-12-29
00:00:00","y":71780278.9789995},{"x":"2021-12-30 00:00:00","y":71106231.95636792},{"x":"2021-12-31
00:00:00","y":70404839.98317608},{"x":"2022-01-01 00:00:00","y":69668570.19673496},{"x":"2022-01-02
00:00:00","y":68949424.91223967},{"x":"2022-01-03 00:00:00","y":68188371.91197796},{"x":"2022-01-04
00:00:00","y":67426977.55449104},{"x":"2022-01-05 00:00:00","y":66614477.86699833},{"x":"2022-01-06
00:00:00","y":65796018.71301971},{"x":"2022-01-07 00:00:00","y":64743978.62680196},{"x":"2022-01-08
00:00:00","y":63561335.10273054},{"x":"2022-01-09 00:00:00","y":62351850.45086063},{"x":"2022-01-10
00:00:00","y":61192301.62778163},{"x":"2022-01-11 00:00:00","y":59839712.407501414},{"x":"2022-01-12
00:00:00","y":58579165.89207462},{"x":"2022-01-13 00:00:00","y":57610692.37354207}],"label":"UST
in Address terra1tmnqgvg567ypvsvk6rwsga3srp7e3lg6u0elp8","color":"#4d00ff"}]'
headers:
Cache-Control:
- max-age=0, private, must-revalidate
Content-Type:
- application/json; charset=utf-8
Date:
- Thu, 13 Jan 2022 14:00:57 GMT
Etag:
- W/"98daebd8fe11f2edab563233ea6ff67f"
Referrer-Policy:
- strict-origin-when-cross-origin
Transfer-Encoding:
- chunked
X-Content-Type-Options:
- nosniff
X-Download-Options:
- noopen
X-Frame-Options:
- SAMEORIGIN
X-Permitted-Cross-Domain-Policies:
- none
X-Request-Id:
- 42bcbf89-ea7a-488e-8586-c79595de50bf
X-Runtime:
- '0.003172'
X-Xss-Protection:
- 1; mode=block
status:
code: 200
message: OK
version: 1

View File

@@ -0,0 +1,63 @@
interactions:
- request:
body: null
headers:
Accept:
- '*/*'
Accept-Encoding:
- gzip, deflate
Connection:
- keep-alive
User-Agent:
- python-requests/2.26.0
method: GET
uri: https://terra.engineer/en/terra_addresses/terra1tmnqgvg567ypvsvk6rwsga3srp7e3lg6u0elp8/show_snapshot_data.json?asset=ust
response:
body:
string: '[{"id":"UST","data":[{"x":"2021-12-16 00:00:00","y":77386761.1048762},{"x":"2021-12-17
00:00:00","y":77107417.4955988},{"x":"2021-12-18 00:00:00","y":76761418.06876892},{"x":"2021-12-19
00:00:00","y":76402060.63818446},{"x":"2021-12-20 00:00:00","y":76049371.1771107},{"x":"2021-12-21
00:00:00","y":75717916.11125192},{"x":"2021-12-22 00:00:00","y":75334594.8653725},{"x":"2021-12-23
00:00:00","y":74801529.79565395},{"x":"2021-12-24 00:00:00","y":74313496.35167404},{"x":"2021-12-25
00:00:00","y":73840418.004713},{"x":"2021-12-26 00:00:00","y":73372333.94158259},{"x":"2021-12-27
00:00:00","y":72928202.62041229},{"x":"2021-12-28 00:00:00","y":72397414.56039554},{"x":"2021-12-29
00:00:00","y":71780278.9789995},{"x":"2021-12-30 00:00:00","y":71106231.95636792},{"x":"2021-12-31
00:00:00","y":70404839.98317608},{"x":"2022-01-01 00:00:00","y":69668570.19673496},{"x":"2022-01-02
00:00:00","y":68949424.91223967},{"x":"2022-01-03 00:00:00","y":68188371.91197796},{"x":"2022-01-04
00:00:00","y":67426977.55449104},{"x":"2022-01-05 00:00:00","y":66614477.86699833},{"x":"2022-01-06
00:00:00","y":65796018.71301971},{"x":"2022-01-07 00:00:00","y":64743978.62680196},{"x":"2022-01-08
00:00:00","y":63561335.10273054},{"x":"2022-01-09 00:00:00","y":62351850.45086063},{"x":"2022-01-10
00:00:00","y":61192301.62778163},{"x":"2022-01-11 00:00:00","y":59839712.407501414},{"x":"2022-01-12
00:00:00","y":58579165.89207462},{"x":"2022-01-13 00:00:00","y":57610692.37354207}],"label":"UST
in Address terra1tmnqgvg567ypvsvk6rwsga3srp7e3lg6u0elp8","color":"#4d00ff"}]'
headers:
Cache-Control:
- max-age=0, private, must-revalidate
Content-Type:
- application/json; charset=utf-8
Date:
- Thu, 13 Jan 2022 14:00:49 GMT
Etag:
- W/"98daebd8fe11f2edab563233ea6ff67f"
Referrer-Policy:
- strict-origin-when-cross-origin
Transfer-Encoding:
- chunked
X-Content-Type-Options:
- nosniff
X-Download-Options:
- noopen
X-Frame-Options:
- SAMEORIGIN
X-Permitted-Cross-Domain-Policies:
- none
X-Request-Id:
- 698eaff8-d885-4c33-8d2e-4d0845300e4d
X-Runtime:
- '0.004107'
X-Xss-Protection:
- 1; mode=block
status:
code: 200
message: OK
version: 1

View File

@@ -0,0 +1,63 @@
interactions:
- request:
body: null
headers:
Accept:
- '*/*'
Accept-Encoding:
- gzip, deflate
Connection:
- keep-alive
User-Agent:
- python-requests/2.26.0
method: GET
uri: https://terra.engineer/en/terra_addresses/terra1tmnqgvg567ypvsvk6rwsga3srp7e3lg6u0elp8/show_snapshot_data.json?asset=ust
response:
body:
string: '[{"id":"UST","data":[{"x":"2021-12-16 00:00:00","y":77386761.1048762},{"x":"2021-12-17
00:00:00","y":77107417.4955988},{"x":"2021-12-18 00:00:00","y":76761418.06876892},{"x":"2021-12-19
00:00:00","y":76402060.63818446},{"x":"2021-12-20 00:00:00","y":76049371.1771107},{"x":"2021-12-21
00:00:00","y":75717916.11125192},{"x":"2021-12-22 00:00:00","y":75334594.8653725},{"x":"2021-12-23
00:00:00","y":74801529.79565395},{"x":"2021-12-24 00:00:00","y":74313496.35167404},{"x":"2021-12-25
00:00:00","y":73840418.004713},{"x":"2021-12-26 00:00:00","y":73372333.94158259},{"x":"2021-12-27
00:00:00","y":72928202.62041229},{"x":"2021-12-28 00:00:00","y":72397414.56039554},{"x":"2021-12-29
00:00:00","y":71780278.9789995},{"x":"2021-12-30 00:00:00","y":71106231.95636792},{"x":"2021-12-31
00:00:00","y":70404839.98317608},{"x":"2022-01-01 00:00:00","y":69668570.19673496},{"x":"2022-01-02
00:00:00","y":68949424.91223967},{"x":"2022-01-03 00:00:00","y":68188371.91197796},{"x":"2022-01-04
00:00:00","y":67426977.55449104},{"x":"2022-01-05 00:00:00","y":66614477.86699833},{"x":"2022-01-06
00:00:00","y":65796018.71301971},{"x":"2022-01-07 00:00:00","y":64743978.62680196},{"x":"2022-01-08
00:00:00","y":63561335.10273054},{"x":"2022-01-09 00:00:00","y":62351850.45086063},{"x":"2022-01-10
00:00:00","y":61192301.62778163},{"x":"2022-01-11 00:00:00","y":59839712.407501414},{"x":"2022-01-12
00:00:00","y":58579165.89207462},{"x":"2022-01-13 00:00:00","y":57610692.37354207}],"label":"UST
in Address terra1tmnqgvg567ypvsvk6rwsga3srp7e3lg6u0elp8","color":"#4d00ff"}]'
headers:
Cache-Control:
- max-age=0, private, must-revalidate
Content-Type:
- application/json; charset=utf-8
Date:
- Thu, 13 Jan 2022 14:00:50 GMT
Etag:
- W/"98daebd8fe11f2edab563233ea6ff67f"
Referrer-Policy:
- strict-origin-when-cross-origin
Transfer-Encoding:
- chunked
X-Content-Type-Options:
- nosniff
X-Download-Options:
- noopen
X-Frame-Options:
- SAMEORIGIN
X-Permitted-Cross-Domain-Policies:
- none
X-Request-Id:
- f821728b-5f50-405d-bdfd-38276bb07f06
X-Runtime:
- '0.003649'
X-Xss-Protection:
- 1; mode=block
status:
code: 200
message: OK
version: 1

View File

@@ -0,0 +1,30 @@
,x,y
0,2021-12-16,77386761.1048762
1,2021-12-17,77107417.4955988
2,2021-12-18,76761418.06876892
3,2021-12-19,76402060.63818446
4,2021-12-20,76049371.1771107
5,2021-12-21,75717916.11125192
6,2021-12-22,75334594.8653725
7,2021-12-23,74801529.79565395
8,2021-12-24,74313496.35167404
9,2021-12-25,73840418.004713
10,2021-12-26,73372333.94158259
11,2021-12-27,72928202.62041229
12,2021-12-28,72397414.56039554
13,2021-12-29,71780278.9789995
14,2021-12-30,71106231.95636792
15,2021-12-31,70404839.98317608
16,2022-01-01,69668570.19673496
17,2022-01-02,68949424.91223967
18,2022-01-03,68188371.91197796
19,2022-01-04,67426977.55449104
20,2022-01-05,66614477.86699833
21,2022-01-06,65796018.71301971
22,2022-01-07,64743978.62680196
23,2022-01-08,63561335.10273054
24,2022-01-09,62351850.45086063
25,2022-01-10,61192301.62778163
26,2022-01-11,59839712.407501414
27,2022-01-12,58579165.89207462
28,2022-01-13,57610692.37354207
1 x y
2 0 2021-12-16 77386761.1048762
3 1 2021-12-17 77107417.4955988
4 2 2021-12-18 76761418.06876892
5 3 2021-12-19 76402060.63818446
6 4 2021-12-20 76049371.1771107
7 5 2021-12-21 75717916.11125192
8 6 2021-12-22 75334594.8653725
9 7 2021-12-23 74801529.79565395
10 8 2021-12-24 74313496.35167404
11 9 2021-12-25 73840418.004713
12 10 2021-12-26 73372333.94158259
13 11 2021-12-27 72928202.62041229
14 12 2021-12-28 72397414.56039554
15 13 2021-12-29 71780278.9789995
16 14 2021-12-30 71106231.95636792
17 15 2021-12-31 70404839.98317608
18 16 2022-01-01 69668570.19673496
19 17 2022-01-02 68949424.91223967
20 18 2022-01-03 68188371.91197796
21 19 2022-01-04 67426977.55449104
22 20 2022-01-05 66614477.86699833
23 21 2022-01-06 65796018.71301971
24 22 2022-01-07 64743978.62680196
25 23 2022-01-08 63561335.10273054
26 24 2022-01-09 62351850.45086063
27 25 2022-01-10 61192301.62778163
28 26 2022-01-11 59839712.407501414
29 27 2022-01-12 58579165.89207462
30 28 2022-01-13 57610692.37354207

View File

@@ -0,0 +1,15 @@
import pytest
from gamestonk_terminal.cryptocurrency.defi import terraengineer_model
@pytest.mark.vcr
@pytest.mark.parametrize(
"asset,address",
[("ust", "terra1tmnqgvg567ypvsvk6rwsga3srp7e3lg6u0elp8")],
)
def test_get_history_asset_from_terra_address(asset, address, recorder):
df = terraengineer_model.get_history_asset_from_terra_address(
asset=asset, address=address
)
recorder.capture(df)

View File

@@ -0,0 +1,27 @@
import pytest
from gamestonk_terminal.cryptocurrency.defi import terraengineer_view
@pytest.mark.vcr
@pytest.mark.record_stdout
def test_display_anchor_yield_reserve(mocker):
# MOCK CHARTS
mocker.patch.object(target=terraengineer_view.gtff, attribute="USE_ION", new=True)
mocker.patch(target="gamestonk_terminal.stocks.options.yfinance_view.plt.ion")
mocker.patch(target="gamestonk_terminal.stocks.options.yfinance_view.plt.show")
terraengineer_view.display_anchor_yield_reserve()
@pytest.mark.vcr
@pytest.mark.record_stdout
def test_display_terra_asset_history(mocker):
# MOCK CHARTS
mocker.patch.object(target=terraengineer_view.gtff, attribute="USE_ION", new=True)
mocker.patch(target="gamestonk_terminal.stocks.options.yfinance_view.plt.ion")
mocker.patch(target="gamestonk_terminal.stocks.options.yfinance_view.plt.show")
terraengineer_view.display_terra_asset_history(
asset="ust", address="terra1tmnqgvg567ypvsvk6rwsga3srp7e3lg6u0elp8"
)

View File

@@ -0,0 +1,17 @@
```
usage: aterra [--asset {ust,luna,sdt}]
[--address ADDRESS]
[--export {csv,json,xlsx}]
[-h]
```
Displays the 30-day history of an asset in a certain terra address. [Source: https://terra.engineer/]
```
optional arguments:
--asset {ust,luna,sdt} Terra asset {ust,luna,sdt} Default: ust
--address ADDRESS Terra address. Valid terra addresses start with 'terra'
--export {csv,json,xlsx}
Export dataframe data to csv,json,xlsx file
-h, --help Show help message (default: False)
```

View File

@@ -0,0 +1,13 @@
```
usage: ayr [--export {csv,json,xlsx}] [-h]
```
Displays the 30-day history of the Anchor Yield Reserve. An increasing yield reserve indicates that the return on collateral staked by borrowers in Anchor is greater than the yield paid to depositors. A decreasing yield reserve means yield paid to depositors is outpacing the staking returns of borrower's collateral. [Source: https://terra.engineer/]
TLDR: Shows the address that contains UST that is paid on anchor interest earn.
```
optional arguments:
--export {csv,json,xlsx}
Export dataframe data to csv,json,xlsx file (default:)
-h, --help show this help message (default: False)
```

View File

@@ -867,6 +867,10 @@ main:
- name: defi
ref: "/cryptocurrency/defi"
sub:
- name: ayr
ref: "/cryptocurrency/defi/ayr"
- name: aterra
ref: "/cryptocurrency/defi/aterra"
- name: llama
ref: "/cryptocurrency/defi/llama"
- name: tvl