Skip to content

Instantly share code, notes, and snippets.

View evanaze's full-sized avatar

Evan Azevedo evanaze

View GitHub Profile
@evanaze
evanaze / dig_asset_sharpe.py
Last active October 12, 2021 07:31
Using Amberdata to get the daily Sharpe Ratio of BTC
# our first token to try out
token = "btc"
# the url for our token
url = f"https://web3api.io/api/v2/market/metrics/{token}/historical/sharpe"
# our API key
headers = {'x-api-key': api_key["AMBERDATA_API_KEY"]}
# the start and end of the period
# load the data into a DataFrame and rename the columns
data = pd.DataFrame(response["data"]).rename({0: "date", 1: "volatility", 2: "sharpe"}, axis=1)
# turn the date column into datetime type
data["date"] = pd.to_datetime(data["date"])
# set the date as the index
data.set_index("date", inplace=True)
# The S&P 500 Index
spy = pdr.get_data_yahoo("SPY", start, end)
# Gold futures
gold = pdr.get_data_yahoo("GC=F", start, end)
# Apple Stock
aapl = pdr.get_data_yahoo("AAPL", start, end)
# Bond index
bond = pdr.get_data_yahoo("BND", start, end)
@evanaze
evanaze / fin_metrics.py
Created August 21, 2020 16:36
Some methods for calculating financial metrics
# helper functions
def CAGR(DF):
"Calculates the Compound Annual Growth Rate"
df = DF.copy()
df['daily_ret'] = df['Adj Close'].pct_change()
df['cum_return'] = (1 + df['daily_ret']).cumprod()
return (df['cum_return'])**(252/len(df)) - 1
def volatility(DF):
"Calculates the daily Volatility over a year, given we trade 252x a year"
# helper functions
def to_df(response):
"Turns the repsonse into a dataframe"
# load the data into a DataFrame and rename the columns
data = pd.DataFrame(response["data"]).rename({0: "date", 1: "volatility", 2: "sharpe"}, axis=1)
# turn the date column into datetime type
data["date"] = pd.to_datetime(data["date"])
# set the date as the index
data.set_index("date", inplace=True)
return data
@evanaze
evanaze / jumping_window_ohlcv.py
Created August 23, 2020 21:04
Get high resolution historical Bitcoin OHLCV from Amberdata using a jumping rather than sliding window.
dfs = []
n_days = 5
for i in range(n_days):
print(f"Iteration: {i}")
# get the start and end dates in timestamps
startDate = results.timestamp.min() + timedelta(i-1)
endDate = startDate + timedelta(1)
# convert to UNIX format
@evanaze
evanaze / websocket_listen.py
Last active August 23, 2020 21:11
A method for listening to streaming data on an Amberdata websocket
async def listen(api_key):
"Opens the websocket connection and listens for pending transactions"
# the amberdata websocket uri
uri = 'wss://ws.web3api.io'
# our headers for the connection
headers = {
"x-api-key": api_key["AMBERDATA_API_KEY"],
"x-amberdata-blockchain-id": "408fa195a34b533de9ad9889f076045e"
}
# outer loop
@evanaze
evanaze / activity_spikes.py
Created August 23, 2020 22:42
Collecting all instances of large pending transactions, and group transactions close together as a single instance
i = 0 # initializing i
win_size = 7 # the window size after a large txn
windows = [] # an array for saving our windows
# iterate through the ohlcv data
while i <= len(ohlcv):
# if the transaction is a large transaction
if ohlcv.iloc[i, -1] == True:
# save the txn and the minutes after
windows.append(ohlcv.iloc[i:i+win_size])
@evanaze
evanaze / single_sent_txn.py
Created August 24, 2020 00:05
Seeing if the large transaction actually went through.
def parse_addresses(i: int = 0, n: int = 0) -> str:
"""Returns the address from record i in position n"""
# parse the list of addresses
address_list = data_sorted.iloc[i, 1].split("['")[-1].split("']")[0]
return address_list.split("', '")[n]
# the top transaction number we consider
i = 0
# the sender's address
sender = parse_addresses(i)
def get_transaction_data(txn_hash):
"gets the data for the specified transaction hash"
# the url with the given hash
url = f"https://web3api.io/api/v2/transactions/{txn_hash}"
# the headers
headers = {
"x-amberdata-blockchain-id": "bitcoin-mainnet",
"x-api-key": api_key["AMBERDATA_API_KEY"]
}
# get the response