Skip to content

Instantly share code, notes, and snippets.

def addVerticalBarrier(tEvents, close, numDays=1):
"""
:param t_events: (series) series of events (symmetric CUSUM filter)
  :param close: (series) close prices
  :param numDays: (int) maximum number of days a trade can be active
 :return: (series) timestamps of vertical barriers
"""
t1=close.index.searchsorted(tEvents+pd.Timedelta(days=numDays))
t1=t1[t1<close.shape[0]]
t1=(pd.Series(close.index[t1],index=tEvents[:t1.shape[0]]))
def get_t_events(raw_price, threshold):
"""
:param raw_price: (series) of close prices.
:param threshold: (float) when the abs(change) is larger than the threshold, the
function captures it as an event.
:return: (datetime index vector) vector of datetimes when the events occurred. This is used later to sample.
"""
print('Applying Symmetric CUSUM filter.')
t_events = []
def get_daily_vol(close, lookback=100):
"""
:param close: (data frame) Closing prices
:param lookback: (int) lookback period to compute volatility
:return: (series) of daily volatility value
"""
print('Calculating daily volatility for dynamic thresholds')
df0 = close.index.searchsorted(close.index - pd.Timedelta(days=1))
df0 = df0[df0 > 0]
fig = go.Figure(data=[go.Candlestick(x=df.timestamp,
open=df.open, high=df.high,
low=df.low, close=df.close)])
fig.show()
def get_dollar_bars(time_bars, dollar_threshold): #function credit to Max Bodoia
# initialize an empty list of dollar bars
dollar_bars = []
# initialize the running dollar volume at zero
running_volume = 0
# initialize the running high and low with placeholder values
running_high, running_low = 0, math.inf
#create dataframe from lists
df = pd.DataFrame(
{'time': [datetime.strptime(x,"%Y-%m-%dT%H:%M:%S.%fZ") for x in time], #formatting our timestamp
'open': [float(x.strip('0')) for x in open], #removing trailing 0's and converting to float
'high': [float(x.strip('0')) for x in high],
'low': [float(x.strip('0')) for x in low],
'close': [float(x.strip('0')) for x in close],
'vol': [float(x.strip('0')) for x in vol]
})
#collecting historical candlestick data
shrimpy_public_key ='...'
shrimpy_secret_key = '...'
client = shrimpy.ShrimpyApiClient(shrimpy_public_key, shrimpy_secret_key)
candles = client.get_candles(
'coinbasepro', # exchange
'BTC', # base_trading_symbol
'USD', # quote_trading_symbol
'1m' # interval
)
import numpy as np
import pandas as pd
from datetime import datetime, timedelta
import math
import plotly
import shrimpy
import plotly.graph_objects as go
from plotly.subplots import make_subplots
@davidzhaodz
davidzhaodz / bars_1.py
Last active December 15, 2020 00:24
Financial Data Structures (Bars)
#install shrimpy
pip install shrimpy-python
#import requisite packages
import numpy as np
import pandas as pd
from datetime import datetime, timedelta
import math
import plotly
import shrimpy