LoginSignup
1
5

More than 3 years have passed since last update.

外為で勝つために その1

Posted at

みなさんは外為、してますか?
私はしてます。そして負けが多いです。

なぜ勝てないのか。
センスはひとまず置いておき、
まずは情報を集めて整理して、手元に並べておくという基本的なことを考えました。

要するにデータ不足が原因ではないかと、そう思ったわけです。

この記事で実現したいこと

相場の基本である「トレンド」を捉えること。
相場は「トレンド」と「レンジ」しかないと誰かが言ってました。

  • トレンド:上昇・下降いずれかに大きく動く相場
  • レンジ:上下に大きく動くことのない安定した相場

ならば、トレンドを押さえるにはレンジを排除すれば良いことになります。
(多分)

そこで、次の問題。
レンジを排除するにはどうしたら良いか?

ちなみに、
絶えずチャートを見続けるのはイヤです。
視界いっぱいに液晶モニターを並べるのはもっとイヤです。
(だから勝てないって言われたら、厳しいなあ)

じゃあプログラムで解決しよう。

相場を一定間隔でモニタリングし、
安値・高値の幅が小さいときはレンジとみなし
大きく乖離していたらトレンドの可能性ありとして通知します。

こういう常時稼働的なものは我らがラズパイにお任せするのが一番でしょう。

準備

デバイス:Raspberry pi 3 Model B Rev 1.2
言語:Python 3.5.3
API:OANDA.jp (REST API)

API の利用申請

OANDA.jp (https://www.oanda.jp/) でデモ口座を開きました。
Personal Access Token を取得しておきます。

本番口座の勧誘するけど、いいよね?
という条件に同意する必要がありますが、ここは致し方ないでしょう。

パッケージのインストール

Python で必要なパッケージをインストールします。
(Python3 は既にインストール済み)

pi@raspberrypi:~ $ pip3 install oandapyV20
pi@raspberrypi:~ $ pip3 install pandas

oandapyV20: OANDA REST API を利用するためのラッパー
pandas: テスト表示の整形用

ちなみに、Python 2.7 では何故か pandas がインストールできませんでした。
もう古いのかな。
なので pip3 を使ってます。

コード

まずは通貨ペアが取得できるかテスト。
デモ口座(practice)から主要19通貨ペアの5分足データを取得します。
最新の時刻だと、まだローソクが完成していないので5分前のデータが良好のようです。

5分間隔で(1秒ずつ休止しながら)19リクエストなら負荷もそれほど大きくなく
1分間隔のようなリアルタイムで取得する必要は今のところ感じないので、
以下のコードに落ち着きました。

import json
import time
from datetime import datetime, timedelta
from pytz import timezone
from oandapyV20 import API
from oandapyV20.exceptions import V20Error
import oandapyV20.endpoints.instruments as instruments
import pandas as pd


# ---------- Settings ----------

# OANDA Personal Access Token
access_token = "## Your Personal Access Token ##"

# Environment (practice / live)
environment = "practice"

# Currency pair
instrument_list = [
    "USD_JPY", "EUR_JPY", "GBP_JPY", "AUD_JPY", "NZD_JPY",
    "CAD_JPY", "CHF_JPY", "TRY_JPY", "ZAR_JPY",
    "EUR_USD", "GBP_USD", "AUD_USD", "NZD_USD", "EUR_GBP",
    "EUR_AUD", "GBP_AUD", "EUR_CHF", "GBP_CHF", "USD_CHF"
]

# Start time (Before 5 min)
minutes = 5
delta = timedelta(minutes=minutes)

# Parameters
# granularity price
# ----------- ------
# S1: 1sec    B: Bid
# M1: 1min    A: Ask
# H1: 1hour
# D : day
# W : Week
# M : Month
params = {
    "from": "",
    "count": 1,
    "granularity": "M" + str(minutes),
    "price": "B"
}


# ----- Main routine -----

api = API(access_token=access_token, environment=environment)

def request_data():

    data = []
    for instrument in instrument_list:
        instruments_candles = instruments.InstrumentsCandles(instrument=instrument, params=params)

        try:
            api.request(instruments_candles)
            response = instruments_candles.response

            # Print raw data
            # print(json.dumps(response, indent=4))

            for raw in response["candles"]:
                data.append([
                    raw["time"],
                    response["instrument"],
                    raw["bid"]["o"],
                    raw["bid"]["h"],
                    raw["bid"]["l"],
                    raw["bid"]["c"]
                ])

            # Wait 1 sec
            time.sleep(1)

        except V20Error as e:
            print("Error: {}".format(e))

    # Print formatted data
    df = pd.DataFrame(data)
    df.columns = ["time", "instrument", "open", "high", "low", "close"]
    df = df.set_index("time")
    df.index = pd.to_datetime(df.index)
    print(df)
    print("row(s) count: {}".format(len(data)))

# Entry point
while 1:

    # Current time
    now = datetime.now(timezone("UTC"))

    # Run if current minute is a multiple of 'minutes'
    if now.minute % minutes == 0 and now.second == 0:
        now -= delta
        params["from"] = now.strftime("%Y-%m-%dT%H:%M:00.000000Z")

        # Request to OANDA
        request_data()

    # Wait 1 sec
    time.sleep(1)

エラー発生

実行したらエラーになりました。
最近、エラーになると少しホッとするのは何ででしょうね。

Traceback (most recent call last):
  File "/home/pi/python/fx/oanda_candle.py", line 9, in <module>
    import pandas as pd
  File "/home/pi/.local/lib/python3.5/site-packages/pandas/__init__.py", line 17, in <module>
    "Unable to import required dependencies:\n" + "\n".join(missing_dependencies)
ImportError: Unable to import required dependencies:
numpy: 

IMPORTANT: PLEASE READ THIS FOR ADVICE ON HOW TO SOLVE THIS ISSUE!

Importing the numpy c-extensions failed.
- Try uninstalling and reinstalling numpy.
- If you have already done that, then:
  1. Check that you expected to use Python3.5 from "/usr/bin/python3",
     and that you have no directories in your PATH or PYTHONPATH that can
     interfere with the Python and numpy version "1.17.4" you're trying to use.
  2. If (1) looks fine, you can open a new issue at
     https://github.com/numpy/numpy/issues.  Please include details on:
     - how you installed Python
     - how you installed numpy
     - your operating system
     - whether or not you have multiple versions of Python installed
     - if you built from source, your compiler versions and ideally a build log

- If you're working with a numpy git repository, try `git clean -xdf`
  (removes all files not under version control) and rebuild numpy.

Note: this error has many possible causes, so please don't comment on
an existing issue about this - open a new one instead.

Original error was: libf77blas.so.3: cannot open shared object file: No such file or directory

で、このエラーの言いたいことは

  • nampy はどこ?
  • nampy を再インストールしてみたら?
  • パスが通ってないんじゃね?
  • Git 使っているならリビルドしたら?

だそうですがどれも的外れ。

pi@raspberrypi:~ $ sudo apt-get install libatlas-base-dev

正解は「上記のパッケージをインストールする」でした。
pandas と nampy はテスト表示で使いたいだけなので今回重要ではないです。

出力結果

                          instrument     open     high      low    close
time                                                                    
2019-12-05 02:50:00+00:00    USD_JPY  108.908  108.908  108.866  108.866
2019-12-05 02:50:00+00:00    EUR_JPY  120.684  120.684  120.642  120.650
2019-12-05 02:50:00+00:00    GBP_JPY  142.797  142.797  142.741  142.752
2019-12-05 02:50:00+00:00    AUD_JPY   74.527   74.527   74.479   74.483
2019-12-05 02:50:00+00:00    NZD_JPY   71.207   71.216   71.175   71.180
2019-12-05 02:50:00+00:00    CAD_JPY   82.568   82.568   82.530   82.543
2019-12-05 02:50:00+00:00    CHF_JPY  110.194  110.194  110.161  110.165
2019-12-05 02:50:00+00:00    TRY_JPY   18.903   18.903   18.888   18.893
2019-12-05 02:50:00+00:00    ZAR_JPY    7.457    7.457    7.457    7.457
2019-12-05 02:50:00+00:00    EUR_USD  1.10807  1.10816  1.10807  1.10816
2019-12-05 02:50:00+00:00    GBP_USD  1.31110  1.31120  1.31110  1.31120
2019-12-05 02:50:00+00:00    AUD_USD  0.68423  0.68427  0.68408  0.68413
2019-12-05 02:50:00+00:00    NZD_USD  0.65381  0.65389  0.65367  0.65378
2019-12-05 02:50:00+00:00    EUR_GBP  0.84503  0.84505  0.84502  0.84504
2019-12-05 02:50:00+00:00    EUR_AUD  1.61917  1.61975  1.61917  1.61965
2019-12-05 02:50:00+00:00    GBP_AUD  1.91579  1.91655  1.91577  1.91633
2019-12-05 02:50:00+00:00    EUR_CHF  1.09509  1.09509  1.09500  1.09504
2019-12-05 02:50:00+00:00    GBP_CHF  1.29574  1.29575  1.29558  1.29564
2019-12-05 02:50:00+00:00    USD_CHF  0.98821  0.98821  0.98809  0.98810
row(s) count: 19

時刻は UTC なので、東京/アジアだから +9 時間で脳内変換します。正しく5分前のデータが取れましたね。
high と low の差が値幅なので、これを判断基準にして通知をさせたらいいと思います。

続く。

1
5
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
1
5