Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/bin/env python
- # coding: utf-8
- # In[4]:
- import numpy as np
- import pandas as pd
- import matplotlib.pyplot as plt
- import ffn
- import bt
- get_ipython().run_line_magic('matplotlib', 'inline')
- plt.style.use('ggplot')
- plt.rcParams['figure.figsize'] = (12.0, 4)
- # # Exploratory Data Analysis
- # In[69]:
- tickers = [
- # which tickers?
- 'BZ=F',
- 'NG=F',
- # '0P0000732C.TO', # nuttals fund
- 'vet.to',
- 'wcp.to',
- 'arch',
- 'btu',
- 'whc.ax'
- ]
- # In[79]:
- # fetch some data
- data = bt.get(
- tickers=tickers,
- start='2017-12-01',
- end='2022-06-16',
- )
- data
- # ## backtest - good
- # In[73]:
- buy_days_before_qend = 1
- sell_days_after_qend= 7
- s = data.index.quarter.to_series().diff().abs().shift(-1).fillna(0)
- s = s.replace(0, np.nan).ffill(limit=sell_days_after_qend).bfill(limit=buy_days_before_qend).fillna(0)
- signal = data.copy()
- signal[:] =np.array([s]*7).T
- signal
- # In[74]:
- signal.loc['2021-03-25':'2021-04-15']
- # # try for each equity
- # In[82]:
- data.columns
- # In[85]:
- tests = []
- for c in data.columns:
- s1 = bt.Strategy(
- c,
- [
- bt.algos.RunDaily(),
- bt.algos.SelectWhere(signal[[c]]),
- bt.algos.WeighEqually(),
- bt.algos.Rebalance()
- ]
- )
- t1 = bt.Backtest(s1, data[[c]])
- tests.append(t1)
- res = bt.run(*tests)
- res.plot()
- res.plot_security_weights()
- res.display()
- # res.stats.T['daily_sharpe'].sort_values()[::-1]
- # # all
- # In[75]:
- s1 = bt.Strategy(
- 'esg',
- [
- bt.algos.RunDaily(),
- bt.algos.SelectWhere(signal),
- bt.algos.WeighEqually(),
- bt.algos.Rebalance()
- ]
- )
- t1 = bt.Backtest(s1, data)
- res = bt.run(t1)
- res.plot()
- res.plot_security_weights()
- res.display()
- res.stats.T['daily_sharpe'].sort_values()[::-1]
- # In[76]:
- # Lets try just 2021 onwards
- s1 = bt.Strategy(
- 'esg',
- [
- bt.algos.RunDaily(),
- bt.algos.SelectWhere(signal.loc['2021':]),
- bt.algos.WeighEqually(),
- bt.algos.Rebalance()
- ]
- )
- t1 = bt.Backtest(s1, data.loc['2021':])
- res = bt.run(t1)
- res.plot()
- res.plot_security_weights()
- res.display()
- res.stats.T['daily_sharpe'].sort_values()[::-1]
- # In[ ]:
- # In[ ]:
- # In[ ]:
- # In[ ]:
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement