Created
November 21, 2019 03:55
-
-
Save mostlyinteresting/66d6ab55663121e2df3bd92e2537919c to your computer and use it in GitHub Desktop.
Rolling n Year Max DD for BTC
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import os | |
import pandas as pd | |
import datetime as dt | |
import seaborn as sns | |
import matplotlib.pyplot as plt | |
import ccxt | |
from dateutil import relativedelta | |
import numpy as np | |
sns.set(style = 'ticks', context = 'talk') | |
plt.style.use("dark_background") | |
pd.options.mode.chained_assignment = None | |
#Millisecond UTC timestamp to datetime | |
def ms2dt(x): | |
return dt.datetime.utcfromtimestamp(x//1000).replace(microsecond=x%1000*1000) | |
#Datetime to millisecond | |
def dt2ms(x): | |
return int(float(pd.to_datetime(x).to_datetime64()) / 1e6) | |
def get_max_dd(nvs = pd.Series(), window=None): | |
n = len(nvs) | |
if window is None: | |
window = n | |
peak_series = nvs.rolling(window=window, min_periods=1).max() | |
return (nvs / peak_series - 1.0).min() | |
if __name__ == '__main__': | |
symbol = 'BTC/USDT' | |
btcStr = 'Bitcoin' | |
goldStr = 'Gold' | |
startDate = dt.datetime(year = 2010, month = 1, day = 1) | |
today = dt.datetime.now() | |
today = dt.datetime(year = today.year, month = today.month, day = today.day) | |
lastYr = today - pd.Timedelta(days = 365) | |
startDate = startDate.strftime('%Y-%m-%d') | |
endDate = today.strftime('%Y-%m-%d') | |
polo = ccxt.poloniex() | |
startDate = dt.datetime(year = 2010, month = 1, day = 3) | |
startDateMS = dt2ms(startDate) | |
btc = polo.fetch_ohlcv(symbol, timeframe = '1d', since = startDateMS) | |
btc = pd.DataFrame(btc, columns = ['Date','Open','High','Low','Close','Volume']) | |
btc['Date'] = btc['Date'].apply( lambda x: ms2dt(x)) | |
btc.set_index('Date', inplace = True) | |
btc = btc[ btc.index < today ] | |
prices = btc[['Close']] | |
prices.rename( columns = {'Close':btcStr}, inplace = True) | |
returns = prices.pct_change() | |
returns.dropna(how = 'any', axis = 'rows', inplace = True) | |
#Drawdowns | |
maxDate = prices.index.max() | |
rolling = [] | |
years = list(range(1,4)) | |
for year in years: | |
strYear = str(year) + ' Year' | |
for i in range(prices.shape[0]): | |
t0 = prices.index[i] | |
t1 = t0 + relativedelta.relativedelta(years=year) | |
if t1 <= maxDate: | |
p0 = prices[btcStr][ (prices.index >= t0) & (prices.index <= t1) ] | |
rolling.append([ strYear, t1, get_max_dd(p0)*-1 ]) | |
rolling = pd.DataFrame.from_records(rolling, columns = ['Horizon','Date','Max Drawdown']) | |
dd1Y = rolling[['Date','Max Drawdown']][rolling['Horizon'] == '1 Year'] | |
dd1Y.set_index('Date', inplace = True) | |
dd1Y.rename( columns = {'Max Drawdown':'Historical 1Y Max DD'}, inplace = True) | |
g = dd1Y.plot() | |
vals = g.get_yticks() | |
g.set_yticklabels(['{:,.0%}'.format(x) for x in vals]) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment