To ease the retrival of multiple days of intraday data ntfdl.multi will merge that data into one dataframe for your convenience. Netfonds ASA kindly makes 20 days including today and non trading days (weekends/holidays) available for free. Hence number of actual trading days is less than 20 days depending on weekday and holidays.
In [4]:
%matplotlib inline
%pylab inline --no-import-all
pylab.rcParams['figure.figsize'] = (18, 10)
In [5]:
from ntfdl import Multi
from matplotlib.finance import candlestick_ohlc
from datetime import datetime, timedelta
In [6]:
# Instantiate multi with instrument FOE from Oslo exchange (OSS)
foe = Multi('FOE', exchange='OSE')
Multi just calls dl.get_trades() and merges the data. Netfonds makes 20 days including today available, hence some days are not trading days (weekends, holidays) and the number of days might be less than expected.
In [7]:
# Make a timerange from to
end = datetime.now() #Today
start = end - timedelta(days=20) #20 days ago
trades = foe.get_trades(start, end)
In [8]:
# Plotting without gaps
fig, ax = plt.subplots()
ax.plot(range(trades.price.size), trades.price)
ax.set_xticklabels(trades.index.date.tolist())
# Plot max and min line
ax.axhline(y=trades.price.max(), linestyle='--', color='r')
ax.axhline(y=trades.price.min(), linestyle='--', color='g')
# Adding axis right hand side
ax.tick_params(labeltop=False, labelright=True)
# Annotate last quote
xmin, xmax = ax.get_xlim()
plt.annotate(trades.iloc[-1].price, xy=(1, trades.iloc[-1].price), xytext=(0, 0), \
xycoords=('axes fraction', 'data'), textcoords='offset points', backgroundcolor='k', color='w')
#ax.plot(xmax, trades.iloc[-1].price, '<k', markersize=18, markeredgecolor='k')
fig.autofmt_xdate()
plt.grid()
In [9]:
ohlcv = foe.get_ohlcv(start, end, '1min')
In [10]:
ohlcv.tail()
Out[10]:
Matplotlib and Pandas really do not have any financial plot that fits the user cases of a trader. Having gaps in the plots are cumbersome to overcome and volume overlay is a pain to say the least. weekday_candlestick is a function to ease the plotting of multiday data. Note that the freq parameter is used to place xticks (which is a bad implementation).
For descent charting see the Techan.js example
In [11]:
def weekday_candlestick(ohlc_data, ax, fmt='%b %d', freq=7, **kwargs):
""" Wrapper function for matplotlib.finance.candlestick_ohlc
that artificially spaces data to avoid gaps from weekends or
other periodes without data """
# No volume overlay for this one
del ohlc_data['volume']
# Convert data to numpy array
ohlc_data_arr = np.array(ohlc_data)
#print(ohlc_data_arr[:,1:]) #open, high, low, close
#print(ohlc_data_arr[:,0:]) #time
ohlc_data_arr2 = np.hstack(
[np.arange(ohlc_data_arr[:,0].size)[:,np.newaxis], ohlc_data_arr[:,1:]])
ndays = ohlc_data_arr2[:,0] # array([0, 1, 2, ... n-2, n-1, n])
dates = ohlc_data_arr[:,0]
date_strings = []
for date in dates:
date_strings.append(date.strftime(fmt))
# Plot candlestick chart
candlestick_ohlc(ax, ohlc_data_arr2, **kwargs)
# Format x axis
ax.set_xticks(ndays[::freq])
ax.set_xticklabels(date_strings[::freq], rotation=45, ha='right')
#ax.set_xlim(ndays.min(), ndays.max())
# Adding axis right hand side
ax.tick_params(labeltop=False, labelright=True)
# Show grid
plt.grid()
plt.show()
In [12]:
# Get data
ohlcv = foe.get_ohlcv(start, end, '30min')
fig, ax = plt.subplots(ncols=1)
# Calculate frequency, assumes all days are same number.
# Note that spacing of xtick can be borked if not.
freq = ohlcv[ohlcv.time > ohlcv["time"].map(lambda t: t.date()).unique()[-1]].shape[0]
weekday_candlestick(ohlcv, ax=ax, fmt='%b %d %H:%M', freq=freq, width=0.5, colorup='g', colordown='r')
fig.tight_layout()
In [13]:
positions = foe.get_positions(start, end)
In [14]:
positions.head()
Out[14]:
In [15]:
# Plotting without gaps
fig, ax = plt.subplots()
ax.plot(range(positions.ask.size), positions.ask)
ax.plot(range(positions.bid.size), positions.bid)
ax.set_xticklabels(positions.index.date.tolist())
# Adding axis right hand side
ax.tick_params(labeltop=False, labelright=True)
fig.autofmt_xdate()
plt.grid()
In [16]:
# Export to csv
#positions.to_csv('foe.csv', sep=',', encoding='utf-8', columns=['time','bid', 'ask'], index=False)