lab_1_solution
lab_1_solution
import numpy as np
import matplotlib.pyplot as plt
Loading dataset
You will find stock_indexes.npz in the directory /home/jovyan/public/datasets/world-stock-markets/ .
data = np.load('/home/jovyan/public/datasets/world-stock-markets/stock_indexes.npz',
allow_pickle=True)
trades = data['trades']
dates = data['dates']
markets = data['markets']
info = data['info']
info
The trades numpy array has the shape of (104224, 4) . The rows are the days of trade for all 14 markets.
The four columns corresponds to Open, Close, High and Low.
Open: the price at the opening of the market on that day
Close: the price at the closing of the market on that day
trades
# @workUnit
market_name = ...
# @solution
'GSPTSE'
# @check
# @title: Canadian exchange name
market_name
'GSPTSE'
# @workUnit
mask_canada = ...
# @solution
# @check
# @title: mask shape and value
mask_canada.shape, np.sum(mask_canada)
((104224,), 10526)
Note: You should have a boolean mask of length 104224, with 10526 entries that are true .
# @workUnit
# @solution
trades_canada = trades[mask_canada, :]
# @check
# @title: Canada trades
trades_canada.shape
(10526, 4)
We can also extract the rows corresponding to the trades that happened in Canada.
This requires masked selection on the dates numpy array.
# @workUnit
# @solution
dates_canada = dates[mask_canada]
# @check
# @title: Canada trading dates range
dates_canada[0], dates_canada[-1]
('1979-06-29', '2021-05-31')
# @workUnit
plt.plot(trades_canada[:, 1]);
plt.title(f'Closing prices from {dates_canada[0]} to {dates_canada[-1]}');
plt.xlabel('Dates')
plt.ylabel('$ CAD')
# @workUnit
tickers = ...
labels = ...
# @solution
# @workUnit
buy_price = ...
sell_price = ...
# @solution
buy_price = trades_canada[0, 0]
sell_price = trades_canada[-1, 1]
# @check
# @title: gain of long term hold
1221.96
Note: over the last 40 years, this strategy would get about 1200% gain, averaging at about 6.5% return.
# @workUnit
buy_prices = ...
sell_prices = ...
# @solution
buy_prices = trades_canada[::2, 0]
sell_prices = trades_canada[::2, 1]
# @workUnit
# @solution
plt.plot(sell_prices / buy_prices);
Now, let’s see how you have done using this strategy. For this, we need to multiply all the gains together:
gains = sell_prices / buy_prices
gain = gains[0] * gains[1] * gains[2] * ...
Luckily we have a numpy function np.prod that does the multiplication for us.
# @workUnit
# @solution
114.01953486649484
Note:
So, compare to the 1200% long term hold, how well did the blind daily trading do?