Skip to content

Instantly share code, notes, and snippets.

@fxborg
Last active October 6, 2016 19:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fxborg/0d99b161e1ce8b5ad167c71443e52208 to your computer and use it in GitHub Desktop.
Save fxborg/0d99b161e1ce8b5ad167c71443e52208 to your computer and use it in GitHub Desktop.
# -*- coding: utf-8 -*-
"""
This file shows how to calculate the EWMAC trading rule for crude oil futures
As in chapter 7 / appendix B of "Systematic Trading" by Robert Carver (www.systematictrading.org)
Required: pandas, matplotlib
USE AT YOUR OWN RISK! No warranty is provided or implied.
Handling of NAN's and Inf's isn't done here (except within pandas),
And there is no error handling!
"""
import pandas as pd
import matplotlib.pyplot as plt
from common import pd_readcsv, cap_series, ewmac_forecast_scalar, get_price_for_instrument
"""
get some data
"""
## This is the stitched price series
## We can't use the price of the contract we're trading, or the volatility will be jumpy
## And we'll miss out on the rolldown. See http://qoppac.blogspot.co.uk/2015/05/systems-building-futures-rolling.html
# 価格データを取得
code="CRUDE_W"
price=get_price_for_instrument(code)
## Shouldn't need changing
# ボラティリティの期間
vol_lookback=25
"""
Calculate the ewmac trading fule forecast, given a price and EWMA speeds Lfast, Lslow and vol_lookback
Assumes that 'price' is daily data
"""
# EMAの期間
Lfast=16
Lslow=4*Lfast
d1=pd.datetime(2007,1,1)
d2=pd.datetime(2009,12,31)
## We don't need to calculate the decay parameter, just use the span directly
#slow_ewma=pd.ewma(price, span=Lslow)
#fast_ewma=pd.ewma(price, span=Lfast)
# EMAを計算
fast_ewma=price.ewm(span=Lfast).mean()
slow_ewma=price.ewm(span=Lslow).mean()
# 2本のEMAの距離を計算
raw_ewmac=fast_ewma - slow_ewma
data_to_plot=pd.concat([price, fast_ewma, slow_ewma], axis=1)
data_to_plot.columns=['Price', 'Fast', 'Slow']
data_to_plot[d1:d2].plot()
plt.show()
raw_ewmac[d1:d2].plot()
plt.title("Raw EWMAC")
plt.show()
## volatility adjustment
#stdev_returns=pd.ewmstd(price - price.shift(1), span=vol_lookback)
# 単純日時リターンの指数ウエイト標準偏差を計算
stdev_returns=(price - price.shift(1)).ewm(span=vol_lookback).std(bias=False)
# ボラティリティで割る
vol_adj_ewmac=raw_ewmac/stdev_returns
vol_adj_ewmac[d1:d2].plot()
plt.title("Vol adjusted ")
plt.show()
## scaling adjustment
# 予測値リスケーリング用のウェイト値を取得(予め計算した値が返る)
f_scalar=ewmac_forecast_scalar(Lfast, Lslow)
# 予測値スカラーによるリスケーリング
forecast=vol_adj_ewmac*f_scalar
cap_forecast=cap_series(forecast, capmin=-20.0,capmax=20.0)
data_to_plot=pd.concat([forecast, cap_forecast], axis=1)
data_to_plot.columns=['Scaled Forecast', 'Capped forecast']
data_to_plot[d1:d2].plot()
plt.show()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment