LoginSignup
2
0

More than 5 years have passed since last update.

#Quantopian で Future の残存期間を調べる

Last updated at Posted at 2018-02-19

天然ガスが気になる

先週から天然ガス先物が気になっているしんせいたろうです.こんにちわ.

<中国>天然ガス輸入急増 「青空作戦」で価格は半年で2倍(毎日新聞)や,北海道の開発含む 中国「氷上のシルクロード」東京ですでに説明会(フィスコ)を読んで天然ガスとかLNGが気になって気になって,夜しか眠れません.

とりあえず,手始めに天然ガスの先物を調べてみようと思い,Quantopianで先物のデータを取得するところを学んだので,メモ程度ですがシェアします.

Quantopianのチュートリアル

本家のチュートリアルはココにあります.
Quantopian Tutorials

天然ガスのcontinuous future を取得

天然ガス以外の先物symbol名はavailable futuresをご参照下さい.下記のコードのroot_symbolを変更すればどれでも取れると思います.

from quantopian.research.experimental import continuous_future, history
import pandas as pd

root_symbol = 'NG' #Natural Gas
future0 = continuous_future(root_symbol)
future1 = continuous_future(root_symbol, offset=1,) # offset を指定しない場合は期近.offset=1 で次の限月.

futures = history([future0,future1], fields='price', frequency="daily",
                  start="2015-1-1", end="2016-1-1")

# コラム名にfuture objectが入るので,扱いやすくするためにシンボル名とオフセット番号に書き換えます
futures.columns = futures.columns.map(lambda x: x.root_symbol + str(x.offset))

Screenshot from 2018-02-19 14-58-39.png

残存期間を取得

2018/02/24 Updated 間違ってました!書き直しましたごめんなさい。

参照 : python - Right way to reverse pandas.DataFrame? - Stack Overflow

from quantopian.research.experimental import continuous_future, history
import numpy as np

root_symbol = 'NG'
future0 = continuous_future(root_symbol)
future1 = continuous_future(root_symbol, offset=1, )

futures = history([future0,future1], fields=['price', 'contract'],frequency="daily",
                  start="2017-1-1", end="2018-2-1")

futures.minor_axis = futures.minor_axis.map(lambda x: x.root_symbol + str(x.offset))


def nan_or_1(x):
    if x:
        return np.nan
    else: 
        return 1

def remaining_days(s_rolldate):
    v = s_rolldate.apply(nan_or_1).iloc[::-1] ## iloc[::-1] は index を reverse する一番簡単な方法
    n = np.isnan(v)
    a = ~n
    c = np.cumsum(a)
    d = np.diff(np.concatenate(([0.], c[n])))
    v[n] = -d
    return np.cumsum(v).iloc[::-1]

contract = futures['contract']
contract["rolldate?"] = contract["NG0"] != contract["NG0"].shift(-1)
contract["remaining_days"] = remaining_days(contract["rolldate?"] )

contract

Screenshot from 2018-02-24 17-37-27.png

次回のQuantopian勉強会

次回勉強会はTokyo Quantopian User Group Vol.03 ペアトレを学ぼうです.先物に関しては何もしませんが,Quantopianやペアトレーディングに興味がある方はぜひお越し下さい(^^)

2
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
0