mirror of
https://github.com/OpenBB-finance/OpenBB.git
synced 2026-11-08 18:32:21 +00:00
Co-authored-by: jmaslek <jmaslek11@gmail.com> Co-authored-by: Chavithra <chavithra@gmail.com> Co-authored-by: Theodore Aptekarev <aptekarev@gmail.com> Co-authored-by: Danglewood <85772166+deeleeramone@users.noreply.github.com> Co-authored-by: Didier Rodrigues Lopes <dro.lopes@campus.fct.unl.pt> * improve user experience phase 1 * add difflib replacement * implement auto-complete on discovery menu * auoto-complete, difflib,jump through menus with cd * Updating tests : terminal * improve navigation on gst * add q command to terminal.py * usage instructions * Updating tests : terminal * fix cd command * vars updated * show menu when user is going through menus * allow user to forget the intiail / on scripting * terminal to accept text file with configuration * refactor -n to -l and clean code * add all commands to the tests_stocks_disc * remove fds from disc since we have search on stocks/ and stocks/sia * hopefully fix tests * skip test * fix completer type and calling menu after command for stocks/disc * show help menu when moving forward/backwards in menus * skip test * skip test - bug fix * add reset, help and quit to choices * improve stocks/disc controller * refactor sia menu * UX improvements for sia menu * improve ux design * refactor ca controller * fix infinite loop * improve ux on dps controller * Add capability of going back from a menu going into a menu * Ux economy (#1056) * First round of UX improvements on economy menu * Do fred menu + sample tests file * revert to > on menu * rename jobs file to .gst * remove cd option * improve return * final refactoring of disc_controller * fix ca,dps,sia,disc,stocks and terminal controllers * work on ba_controller menu * fix reset and try_except * UX on screener controller * fix for full reset name * Ux etfs (#1059) * Refactor ETF menu for new UX * Add couple more examples to test * r->reset * Clean up switch * gov menu refactored * fix reset issue * 80% of refactoring options and pricing/payoff menu is done * improve payoff controller * minor fix * fix: refactor pred and ta stocks controller * fix: refactor fa(and fmp) controllers * fix: refactored dd controller (still missing .gst tests) * fix infinite loop bug * refactor options controller * add tests for payoff and pricing * fix reset for options * UX Upgrade for Crypto controller(s) (#1049) * refactor crypto controller * refactor crypto/defi controller * added simple test and fixes not returning queue in commands * Clean up unused functions / iex load (#1047) * Clean up unused functions and adjust iex load function to not depend on dates * Had an incorrect tab on s_start definition * wrong default arg * regenerate pytest yml * Comment out parametrization * Tests : Stocks > Discovery (#1050) * Updating tests : stocks/discovery/ark * Updating tests : stocks/discovery/fidelity * Updating tests : stocks/discovery/fidelity * Updating tests : stocks/discovery/fidelity * Updating tests : stocks/discovery/seeking_alpha * Updating tests : stocks/discovery/seeking_alpha * Updating tests : stocks/discovery/shortinterest * Updating tests : stocks/discovery/shortinterest * Updating tests : stocks/discovery/seeking_alpha * Updating tests : stocks/discovery/shortinterest * Updating tests : stocks/discovery/disc_controller * Updating tests : stocks/dd * Updating tests : stocks/fa * Updating tests : stocks/discovery/financedatabase * Updating tests : stocks/discovery/finnhub * Updating tests : stocks/discovery/geekofwallstreet * Updating tests : stocks/discovery/marketbeat * Updating tests : stocks/discovery/nasdaq * Updating tests : stocks / discovery / yahoofinance * Updating tests : black * Updating tests : unused import * Updating tests : stocks/discovery/ark * Tests : Stocks > Doc + Helpers + Government (#1051) * Updating tests : stocks/government/controller * Updating tests : stocks/government * Updating tests : conftest * Updating tests : stocks > government * Updating tests : stocks/government * Updating tests : docs * Tests : Stocks > Insider (#1054) * Updating tests : stocks > helper * Updating tests : doc * Updating tests : clean stocks > fa > av * Updating tests : stocks/insider/controller * Updating tests : stocks/insider/business insider * Updating tests : stocks/insider/finviz * Updating tests : stocks/insider/openinsider * Updating tests : stocks/insider/controller * Updating tests : black * Updating tests : stocks/insider/controller * Tests : Stocks > Backtesting + Behavioural Analysis (#1057) * Updating tests : add __init__ files * Updating tests : stocsk/behavioural_analysis * Updating tests : black * Updating tests : stocks/backtesting * Updating tests : stocks/backtesting * fix: converted top to limit arguments * fix: refactor disc controller, updated docs * fix: refactor dd_controller and docs * fix: refactor nft controller and docs * fix: pass test temporarily, onchain controller refactor, docs * fix: overview controller refactor, fix quit command * fix: linting issues * fix: refacot ta controller * fix: refactor pred controller * fix: linting * fix: crypto controller * fix: added tests, updated all controlers * fix: menu print renamed from stocks to crypto controller, added tests * fix: fix faster function execution * Fix annoying pylint C0201 error * fix: renamed commands to long format * DISC Cleanup (#1058) * Get rid/cleanup of marketbeat functions * Get rid of last unused disc function + fix related tests * fix test * Dividend History Chart (#1053) * Dividend History Chart * changed to default number 10 * changed divs flag default to false * updating the expected result for test_fa_controller. * else statement * fix: added load on dd * fix: added autocompletion in all commands with argument choices * fix: linting * Workflows + Stocks > Insider (#1061) * Updating code : stocks/insider remove unused file * Updating workflows : tests - set mypy==0.910 * fix: linting * Fixing Linting (#1062) * Updating code : fixing linting mypy message = Too many arguments for <lambda> * Updating workflows : allow newest mypy version * Updating code : apply black * Updating code : black * fix: updated predict controller help to match stocks * Ux: portfolio (#1063) * First step of portfolio UX * Add all broker controllers to UX stuff * UX Improvement for PO Co-authored-by: Didier Rodrigues Lopes <dro.lopes@campus.fct.unl.pt> * UX Improvement for resources (#1064) Co-authored-by: Didier Rodrigues Lopes <dro.lopes@campus.fct.unl.pt> * UX: stock/bt (#1065) * UX: stocks>qa (#1068) * fix mypy lambda * skip tests for now * remove unused paths.py * rename tests/simulator to tests/e2e * refactor options/screener menu * UX : move `gst` files location * fix stocks_controller * UX upgrade of the Forex menu (#1048) * Add basic forex menu test * Add forex routes to terminal paths * Remove commands from paths because they're not menus * WIP Refactor forex controller * refactor crypto controller * Remove commented code * Improve user output with printed text * Add "help" back to the list of choices * Enable the command queue for the forex controller * refactor crypto/defi controller * Fix candle chart blocking the terminal * Black * Return help and reset to the list of known args * added simple test and fixes not returning queue in commands * Add currency codes loading to the av_model * Return the queue in edge cases (when commands don't process) * Split select into to and from to enable autocompletion * Style text output * Stop printing help after the execution of every command * Update test scenarios * Black * fix: converted top to limit arguments * fix: refactor disc controller, updated docs * Delete oanda the old view file that was moved into the oanda menu * fix: refactor dd_controller and docs * fix: refactor nft controller and docs * fix: pass test temporarily, onchain controller refactor, docs * fix: overview controller refactor, fix quit command * fix: linting issues * fix: refacot ta controller * fix: refactor pred controller * fix: linting * fix: crypto controller * fix: added tests, updated all controlers * fix: menu print renamed from stocks to crypto controller, added tests * fix: fix faster function execution * Implement basic UX improvement of the oanda controller * Update the forex controller * Fix annoying pylint C0201 error * Add latest convention changes to the forex controller * fix: renamed commands to long format * fix: added load on dd * Merge the latest updates of the controller design * fix: added autocompletion in all commands with argument choices * fix: linting * fix: linting * fix: updated predict controller help to match stocks * Update the forex menu e2e test scripts * Add check_non_negative_float helper * Update the controller with the latest changes to the convention * Update the currency pair loading mechanism * Move data models logic to the models file * Update update oanda views to be interact with the models * Upgrade oanda controller * Remove raw stocks ba and eda code from the forex menu * Update "help wanted" banner for ba and eda in forex menu * Remove remainders of stocks ba and eda from forex context * Improve typing, docstrings and error messages * Remove stocks ba and eda code that was merged from other ux branches * Add fixes that prevented incorrect argument handling * Remove -argument from the candles call If there is an expected agr `-g` and you put an incorrect argument `-argument` the difflib will interpret `argument` as `g` Co-authored-by: jose-donato <zmcdonato@gmail.com> Co-authored-by: Didier Rodrigues Lopes <dro.lopes@campus.fct.unl.pt> * fix reset for menus that require ticker * UX improvement on research menu * skip insider controller test * initial refactoring of insider_controller * improve insider controller ux part 2 * finish refactoring ins controller ux menu * fix bug of when commands in queue have args * skip test * comment test stuff * UX: stocks>qa (#1071) * refactor return self.queue * fix return None * minor fix * minor tabulate fix * Get rid of leading '/' in terminal and add some newlines on quits. (#1074) * Get rid of leading '/' in terminal and add some newlines on quits. * print crypto help on menu entry * looks like a format issue here... * newlines on quit * remove unnecessary line break * fix pylint issue * refactor * refactor * allow portfolio optimization to quit context * add exit at end of scripts * improve dd_controller * test ux in stocks/dd menu * Ux upgrade for reports context (#1075) * Refactor reports and upgrade them with the latest controller convention * Add test scenarios for the reports context * test ux stocks/ta * ux branch scripts/ta * improvement on main param * Upgrades for the UX upgrade for the fa and fa/fmp menus (#1076) * Change --num to --limit * Remove inconsistent/unreliable functions from the choices list * Improve docstring compliance with numpy doc format * Fix hardcoded class id in dcf scrapper * Fix annoying pylint error in discordbot that was blocking the hook * Add test scenarios for the fa and fa/fmp menus * Fix forgotten replacement of --num to --limit * Fix tests * Return some excluded commands to the choices list * Fix dd report to reflect the updates * Fix set function not returning the queue * Update gst test files * fix exit on ca from another submenu * fix changes of options/screener * fix dps controller * fix fa when running out of AV calls * Fix TVL plot locking interpreter during defi test * Add exception handling for broken coingecko scrapper * skip fa/av test that fails * fix dps tests Co-authored-by: Chavithra PARANA <chavithra@gmail.com> Co-authored-by: jmaslek <jmaslek11@gmail.com> Co-authored-by: jose-donato <zmcdonato@gmail.com> Co-authored-by: jose-donato <43375532+jose-donato@users.noreply.github.com> Co-authored-by: Theodore Aptekarev <aptekarev@gmail.com> Co-authored-by: Danglewood <85772166+deeleeramone@users.noreply.github.com>
585 lines
16 KiB
Python
585 lines
16 KiB
Python
"""CoinGecko model"""
|
|
__docformat__ = "numpy"
|
|
|
|
import pandas as pd
|
|
from pycoingecko import CoinGeckoAPI
|
|
from requests.adapters import RetryError
|
|
from gamestonk_terminal.cryptocurrency.dataframe_helpers import (
|
|
percent_to_float,
|
|
create_df_index,
|
|
wrap_text_in_df,
|
|
)
|
|
from gamestonk_terminal.cryptocurrency.pycoingecko_helpers import (
|
|
changes_parser,
|
|
replace_qm,
|
|
clean_row,
|
|
collateral_auditors_parse,
|
|
swap_columns,
|
|
scrape_gecko_data,
|
|
get_btc_price,
|
|
GECKO_BASE_URL,
|
|
)
|
|
|
|
PERIODS = {
|
|
"1h": "?time=h1",
|
|
"24h": "?time=h24",
|
|
"7d": "?time=d7",
|
|
"14d": "?time=d14",
|
|
"30d": "?time=d30",
|
|
"60d": "?time=d60",
|
|
"1y": "?time=y1",
|
|
}
|
|
|
|
CATEGORIES = {
|
|
"trending": 0,
|
|
"most_voted": 1,
|
|
"positive_sentiment": 2,
|
|
"recently_added": 3,
|
|
"most_visited": 4,
|
|
}
|
|
|
|
GAINERS_FILTERS = ["Rank", "Symbol", "Name", "Volume", "Price", "Change"]
|
|
TRENDING_FILTERS = [
|
|
"Rank",
|
|
"Name",
|
|
"Price_BTC",
|
|
"Price_USD",
|
|
]
|
|
RECENTLY_FILTERS = [
|
|
"Rank",
|
|
"Name",
|
|
"Symbol",
|
|
"Price",
|
|
"Change_1h",
|
|
"Change_24h",
|
|
"Added",
|
|
"Url",
|
|
]
|
|
|
|
YFARMS_FILTERS = [
|
|
"Rank",
|
|
"Name",
|
|
"Value_Locked",
|
|
"Return_Year",
|
|
]
|
|
|
|
CAP_FILTERS = [
|
|
"Rank",
|
|
"Name",
|
|
"Symbol",
|
|
"Price",
|
|
"Change_1h",
|
|
"Change_24h",
|
|
"Change_7d",
|
|
"Volume_24h",
|
|
"Market_Cap",
|
|
]
|
|
|
|
DEX_FILTERS = [
|
|
"Name",
|
|
"Rank",
|
|
"Volume_24h",
|
|
"Coins",
|
|
"Pairs",
|
|
"Visits",
|
|
"Most_Traded",
|
|
"Market_Share",
|
|
]
|
|
|
|
# TODO: convert Volume and other str that should be int to int otherwise sort won't work
|
|
|
|
|
|
def get_gainers_or_losers(period: str = "1h", typ: str = "gainers") -> pd.DataFrame:
|
|
"""Scrape data about top gainers - coins which gain the most in given period and
|
|
top losers - coins that lost the most in given period of time. [Source: CoinGecko]
|
|
|
|
Parameters
|
|
----------
|
|
period: str
|
|
One from [1h, 24h, 7d, 14d, 30d, 60d, 1y]
|
|
typ: str
|
|
Either "gainers" or "losers"
|
|
Returns
|
|
-------
|
|
pandas.DataFrame
|
|
Top Gainers / Top Losers - coins which gain/lost most in price in given period of time.
|
|
Columns: Symbol, Name, Volume, Price, %Change_{period}, Url
|
|
"""
|
|
|
|
category = {
|
|
"gainers": 0,
|
|
"losers": 1,
|
|
}
|
|
|
|
if period not in PERIODS:
|
|
raise ValueError(
|
|
f"Wrong time period\nPlease chose one from list: {PERIODS.keys()}"
|
|
)
|
|
|
|
url = f"https://www.coingecko.com/en/coins/trending{PERIODS.get(period)}"
|
|
try:
|
|
scraped_data = scrape_gecko_data(url)
|
|
except RetryError as e:
|
|
print(e)
|
|
return pd.DataFrame()
|
|
rows = scraped_data.find_all("tbody")[category.get(typ)].find_all("tr")
|
|
results = []
|
|
for row in rows:
|
|
url = GECKO_BASE_URL + row.find("a")["href"]
|
|
symbol, name, *_, volume, price, change = clean_row(row)
|
|
try:
|
|
change = percent_to_float(change)
|
|
except (ValueError, TypeError) as e:
|
|
print(e)
|
|
results.append([symbol, name, volume, price, change, url])
|
|
df = pd.DataFrame(
|
|
results,
|
|
columns=[
|
|
"Symbol",
|
|
"Name",
|
|
"Volume",
|
|
"Price",
|
|
f"%Change_{period}",
|
|
"Url",
|
|
],
|
|
)
|
|
df.index = df.index + 1
|
|
df.reset_index(inplace=True)
|
|
df = df.rename(columns={"index": "Rank"})
|
|
df["Price"] = df["Price"].apply(lambda x: float(x.strip("$").replace(",", "")))
|
|
return df
|
|
|
|
|
|
def get_discovered_coins(category: str = "trending") -> pd.DataFrame:
|
|
"""Scrapes data from "https://www.coingecko.com/en/discover" [Source: CoinGecko]
|
|
- Most voted coins
|
|
- Most popular coins
|
|
- Recently added coins
|
|
- Most positive sentiment coins
|
|
|
|
Parameters
|
|
----------
|
|
category: str
|
|
- one from list: [trending, most_voted, positive_sentiment,recently_added, most_visited]
|
|
Returns
|
|
-------
|
|
pandas.DataFrame:
|
|
Most voted, most trending, recently added, most positive sentiment coins.
|
|
Columns: Name, Price_BTC, Price_USD, Url
|
|
"""
|
|
|
|
if category not in CATEGORIES:
|
|
raise ValueError(
|
|
f"Wrong category name\nPlease chose one from list: {CATEGORIES.keys()}"
|
|
)
|
|
url = "https://www.coingecko.com/en/discover"
|
|
try:
|
|
scraped_data = scrape_gecko_data(url)
|
|
except RetryError as e:
|
|
print(e)
|
|
return pd.DataFrame()
|
|
popular = scraped_data.find_all("div", class_="col-12 col-sm-6 col-md-6 col-lg-4")[
|
|
CATEGORIES[category]
|
|
]
|
|
rows = popular.find_all("a")
|
|
results = []
|
|
btc_price = get_btc_price()
|
|
|
|
for row in rows:
|
|
name, *_, price = clean_row(row)
|
|
url = GECKO_BASE_URL + row["href"]
|
|
if price.startswith("BTC"):
|
|
price = price.replace("BTC", "").replace(",", ".")
|
|
|
|
price_usd = (int(btc_price) * float(price)) if btc_price else None
|
|
results.append([name, price, price_usd, url])
|
|
return pd.DataFrame(
|
|
results,
|
|
columns=[
|
|
"Name",
|
|
"Price_BTC",
|
|
"Price_USD",
|
|
"Url",
|
|
],
|
|
)
|
|
|
|
|
|
def get_recently_added_coins() -> pd.DataFrame:
|
|
"""Scrape recently added coins on CoinGecko from "https://www.coingecko.com/en/coins/recently_added"
|
|
[Source: CoinGecko]
|
|
|
|
Returns
|
|
-------
|
|
pandas.DataFrame
|
|
Recently Added Coins on CoinGecko
|
|
Columns: Name, Symbol, Price, Change_1h, Change_24h, Added
|
|
"""
|
|
|
|
columns = [
|
|
"Name",
|
|
"Symbol",
|
|
"Price",
|
|
"Change_1h",
|
|
"Change_24h",
|
|
"Added",
|
|
"Url",
|
|
]
|
|
|
|
url = "https://www.coingecko.com/en/coins/recently_added"
|
|
try:
|
|
scraped_data = scrape_gecko_data(url)
|
|
except RetryError as e:
|
|
print(e)
|
|
return pd.DataFrame()
|
|
rows = scraped_data.find("tbody").find_all("tr")
|
|
results = []
|
|
|
|
for row in rows:
|
|
url = GECKO_BASE_URL + row.find("a")["href"]
|
|
row_cleaned = clean_row(row)
|
|
(
|
|
name,
|
|
symbol,
|
|
_,
|
|
price,
|
|
*changes,
|
|
_,
|
|
_volume,
|
|
last_added,
|
|
) = row_cleaned
|
|
change_1h, change_24h, _ = changes_parser(changes)
|
|
results.append([name, symbol, price, change_1h, change_24h, last_added, url])
|
|
df = replace_qm(pd.DataFrame(results, columns=columns))
|
|
df.index = df.index + 1
|
|
df.reset_index(inplace=True)
|
|
df.rename(columns={"index": "Rank"}, inplace=True)
|
|
df["Price"] = df["Price"].apply(lambda x: float(x.strip("$").replace(",", "")))
|
|
return df
|
|
|
|
|
|
def get_yield_farms() -> pd.DataFrame:
|
|
"""Scrapes yield farms data from "https://www.coingecko.com/en/yield-farming" [Source: CoinGecko]
|
|
|
|
Returns
|
|
-------
|
|
pandas.DataFrame
|
|
Top Yield Farms
|
|
Columns: Rank, Name, Pool, Audits, Collateral, Value Locked, Return Year, Return Hour
|
|
"""
|
|
|
|
columns = [
|
|
"Rank",
|
|
"Name",
|
|
"Pool",
|
|
"Audits",
|
|
"Collateral",
|
|
"Value_Locked",
|
|
"Return_Year",
|
|
]
|
|
url = "https://www.coingecko.com/en/yield-farming"
|
|
try:
|
|
scraped_data = scrape_gecko_data(url)
|
|
except RetryError as e:
|
|
print(e)
|
|
return pd.DataFrame()
|
|
rows = scraped_data.find("tbody").find_all("tr")
|
|
results = []
|
|
for row in rows:
|
|
row_cleaned = clean_row(row)[:-2]
|
|
if " New" in row_cleaned: # find better way to fix it in future
|
|
row_cleaned.remove(" New")
|
|
|
|
if len(row_cleaned) == 7:
|
|
row_cleaned.insert(2, None)
|
|
(
|
|
rank,
|
|
name,
|
|
pool,
|
|
*others,
|
|
_,
|
|
value_locked,
|
|
apy1,
|
|
_, # hourly removed for most cases it's 0.00 so it doesn't bring any value for user
|
|
) = row_cleaned
|
|
auditors, collateral = collateral_auditors_parse(others)
|
|
auditors = ", ".join(aud.strip() for aud in auditors)
|
|
collateral = ", ".join(coll.strip() for coll in collateral)
|
|
results.append(
|
|
[
|
|
rank,
|
|
name,
|
|
pool,
|
|
auditors,
|
|
collateral,
|
|
value_locked,
|
|
apy1,
|
|
]
|
|
)
|
|
df = pd.DataFrame(results, columns=columns).replace({"": None})
|
|
for col in ["Return_Year"]:
|
|
df[col] = df[col].apply(
|
|
lambda x: x.replace(" Yearly", "") if isinstance(x, str) else x
|
|
)
|
|
df["Rank"] = df["Rank"].astype(int)
|
|
df = wrap_text_in_df(df, w=30)
|
|
return df
|
|
|
|
|
|
def get_top_volume_coins() -> pd.DataFrame:
|
|
"""Scrapes top coins by trading volume "https://www.coingecko.com/en/coins/high_volume" [Source: CoinGecko]
|
|
|
|
Returns
|
|
-------
|
|
pandas.DataFrame
|
|
Top Coins by Trading Volume
|
|
Columns: Rank, Name, Symbol, Price, Change_1h, Change_24h, Change_7d, Volume_24h, Market_Cap
|
|
"""
|
|
|
|
columns = [
|
|
"Rank",
|
|
"Name",
|
|
"Symbol",
|
|
"Price",
|
|
"Change_1h",
|
|
"Change_24h",
|
|
"Change_7d",
|
|
"Volume_24h",
|
|
"Market_Cap",
|
|
]
|
|
url = "https://www.coingecko.com/en/coins/high_volume"
|
|
try:
|
|
scraped_data = scrape_gecko_data(url)
|
|
except RetryError as e:
|
|
print(e)
|
|
return pd.DataFrame()
|
|
rows = scraped_data.find("tbody").find_all("tr")
|
|
results = []
|
|
for row in rows:
|
|
row_cleaned = clean_row(row)
|
|
if len(row_cleaned) == 9:
|
|
row_cleaned.insert(0, "?")
|
|
row_cleaned.pop(3)
|
|
results.append(row_cleaned)
|
|
df = replace_qm(pd.DataFrame(results, columns=columns))
|
|
df.drop("Rank", axis=1, inplace=True)
|
|
create_df_index(df, "Rank")
|
|
df["Price"] = df["Price"].apply(lambda x: float(x.strip("$").replace(",", "")))
|
|
return df
|
|
|
|
|
|
def get_top_defi_coins() -> pd.DataFrame:
|
|
"""Scrapes top decentralized finance coins "https://www.coingecko.com/en/defi" [Source: CoinGecko]
|
|
|
|
Returns
|
|
-------
|
|
pandas.DataFrame
|
|
Top Decentralized Finance Coins
|
|
Columns: Rank, Name, Symbol, Price, Change_1h, Change_24h, Change_7d, Volume_24h, Market_Cap, Url
|
|
"""
|
|
|
|
url = "https://www.coingecko.com/en/defi"
|
|
try:
|
|
scraped_data = scrape_gecko_data(url)
|
|
except RetryError as e:
|
|
print(e)
|
|
return pd.DataFrame()
|
|
rows = scraped_data.find("tbody").find_all("tr")
|
|
results = []
|
|
for row in rows:
|
|
|
|
row_cleaned = clean_row(row)
|
|
row_cleaned.pop(2)
|
|
url = GECKO_BASE_URL + row.find("a")["href"]
|
|
row_cleaned.append(url)
|
|
if len(row_cleaned) == 11:
|
|
row_cleaned.insert(4, "?")
|
|
results.append(row_cleaned)
|
|
|
|
df = pd.DataFrame(
|
|
results,
|
|
columns=[
|
|
"Rank",
|
|
"Name",
|
|
"Symbol",
|
|
"Price",
|
|
"Change_1h",
|
|
"Change_24h",
|
|
"Change_7d",
|
|
"Volume_24h",
|
|
"Market_Cap",
|
|
"Fully Diluted Market Cap",
|
|
"Market Cap to TVL Ratio",
|
|
"Url",
|
|
],
|
|
)
|
|
df.drop(
|
|
["Fully Diluted Market Cap", "Market Cap to TVL Ratio"],
|
|
axis=1,
|
|
inplace=True,
|
|
)
|
|
df["Rank"] = df["Rank"].astype(int)
|
|
df["Price"] = df["Price"].apply(lambda x: float(x.strip("$").replace(",", "")))
|
|
return df
|
|
|
|
|
|
def get_top_dexes() -> pd.DataFrame:
|
|
"""Scrapes top decentralized exchanges from "https://www.coingecko.com/en/dex" [Source: CoinGecko]
|
|
|
|
Returns
|
|
-------
|
|
pandas.DataFrame
|
|
Top Decentralized Crypto Exchanges
|
|
Columns: Name, Rank, Volume_24h, Coins, Pairs, Visits, Most_Traded, Market_Share
|
|
"""
|
|
|
|
columns = [
|
|
"Name",
|
|
"Rank",
|
|
"Volume_24h",
|
|
"Coins",
|
|
"Pairs",
|
|
"Visits",
|
|
"Most_Traded",
|
|
"Market_Share",
|
|
]
|
|
url = "https://www.coingecko.com/en/dex"
|
|
try:
|
|
scraped_data = scrape_gecko_data(url)
|
|
except RetryError as e:
|
|
print(e)
|
|
return pd.DataFrame()
|
|
rows = scraped_data.find("tbody").find_all("tr")
|
|
results = []
|
|
for row in rows:
|
|
row_cleaned = clean_row(row)
|
|
if " Trading Incentives" in row_cleaned:
|
|
row_cleaned.remove(" Trading Incentives")
|
|
if len(row_cleaned) == 8:
|
|
row_cleaned.insert(-3, "N/A")
|
|
results.append(row_cleaned)
|
|
df = pd.DataFrame(results)
|
|
df["Name"] = df.iloc[:, 1] + " " + df.iloc[:, 2].replace("N/A", "")
|
|
df.drop(df.columns[1:3], axis=1, inplace=True)
|
|
df = swap_columns(df)
|
|
df.columns = columns
|
|
df["Most_Traded"] = (
|
|
df["Most_Traded"]
|
|
.apply(lambda x: x.split("$")[0])
|
|
.str.replace(",", "", regex=True)
|
|
.str.replace(".", "", regex=True)
|
|
)
|
|
df["Most_Traded"] = df["Most_Traded"].apply(lambda x: None if x.isdigit() else x)
|
|
df["Rank"] = df["Rank"].astype(int)
|
|
df.set_index("Rank", inplace=True)
|
|
return df.reset_index()
|
|
|
|
|
|
def get_top_nfts() -> pd.DataFrame:
|
|
"""Scrapes top nfts from "https://www.coingecko.com/en/nft" [Source: CoinGecko]
|
|
|
|
Returns
|
|
-------
|
|
pandas.DataFrame
|
|
Top NFTs (Non-Fungible Tokens)
|
|
Columns: Rank, Name, Symbol, Price, Change_1d, Change_24h, Change_7d, Market_Cap, Url
|
|
"""
|
|
|
|
url = "https://www.coingecko.com/en/nft"
|
|
try:
|
|
scraped_data = scrape_gecko_data(url)
|
|
except RetryError as e:
|
|
print(e)
|
|
return pd.DataFrame()
|
|
rows = scraped_data.find("tbody").find_all("tr")
|
|
results = []
|
|
for row in rows:
|
|
link = GECKO_BASE_URL + row.find("a")["href"]
|
|
row_cleaned = clean_row(row)
|
|
if len(row_cleaned) == 9:
|
|
row_cleaned.insert(5, "N/A")
|
|
row_cleaned.append(link)
|
|
row_cleaned.pop(3)
|
|
results.append(row_cleaned)
|
|
df = pd.DataFrame(
|
|
results,
|
|
columns=[
|
|
"Rank",
|
|
"Name",
|
|
"Symbol",
|
|
"Price",
|
|
"Change_1h",
|
|
"Change_24h",
|
|
"Change_7d",
|
|
"Volume_24h",
|
|
"Market_Cap",
|
|
"Url",
|
|
],
|
|
)
|
|
df["Rank"] = df["Rank"].astype(int)
|
|
df["Price"] = df["Price"].apply(lambda x: x.strip("$").replace(",", ""))
|
|
return df
|
|
|
|
|
|
def get_coin_list() -> pd.DataFrame:
|
|
"""Get list of coins available on CoinGecko [Source: CoinGecko]
|
|
|
|
Returns
|
|
-------
|
|
pandas.DataFrame
|
|
Coins available on CoinGecko
|
|
Columns: id, symbol, name
|
|
"""
|
|
|
|
client = CoinGeckoAPI()
|
|
return pd.DataFrame(
|
|
client.get_coins_list(),
|
|
columns=["id", "symbol", "name"],
|
|
).reset_index()
|
|
|
|
|
|
def get_coins_for_given_exchange(exchange_id: str = "binance", page: int = 1) -> dict:
|
|
"""Helper method to get all coins available on binance exchange [Source: CoinGecko]
|
|
|
|
Parameters
|
|
----------
|
|
exchange_id: str
|
|
id of exchange
|
|
page: int
|
|
number of page. One page contains 100 records
|
|
|
|
Returns
|
|
-------
|
|
dict
|
|
dictionary with all trading pairs on binance
|
|
"""
|
|
|
|
client = CoinGeckoAPI()
|
|
binance_coins = client.get_exchanges_tickers_by_id(id=exchange_id, page=page)
|
|
return binance_coins["tickers"]
|
|
|
|
|
|
def get_mapping_matrix_for_exchange(exchange_id: str, pages: int = 12) -> dict:
|
|
"""Creates a matrix with all coins available on Binance with corresponding coingecko coin_id. [Source: CoinGecko]
|
|
|
|
Parameters
|
|
----------
|
|
exchange_id: str
|
|
id of exchange: binance
|
|
pages: int
|
|
number of pages. One page contains 100 records
|
|
|
|
Returns
|
|
-------
|
|
dict
|
|
dictionary with all coins: {"ETH" : "ethereum"}
|
|
"""
|
|
|
|
coins_dct = {}
|
|
for i in range(pages):
|
|
coins = get_coins_for_given_exchange(exchange_id=exchange_id, page=i)
|
|
for coin in coins:
|
|
bin_symbol, gecko_id = coin["base"], coin["coin_id"]
|
|
if bin_symbol not in coins_dct:
|
|
coins_dct[bin_symbol] = gecko_id
|
|
return coins_dct
|