katakyo
    • Create new note
    • Create a note from template
      • Sharing URL Link copied
      • /edit
      • View mode
        • Edit mode
        • View mode
        • Book mode
        • Slide mode
        Edit mode View mode Book mode Slide mode
      • Customize slides
      • Note Permission
      • Read
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Write
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Engagement control Commenting, Suggest edit, Emoji Reply
    • Invite by email
      Invitee

      This note has no invitees

    • Publish Note

      Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

      Your note will be visible on your profile and discoverable by anyone.
      Your note is now live.
      This note is visible on your profile and discoverable online.
      Everyone on the web can find and read all notes of this public team.
      See published notes
      Unpublish note
      Please check the box to agree to the Community Guidelines.
      View profile
    • Commenting
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
      • Everyone
    • Suggest edit
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
    • Emoji Reply
    • Enable
    • Versions and GitHub Sync
    • Note settings
    • Note Insights New
    • Engagement control
    • Make a copy
    • Transfer ownership
    • Delete this note
    • Save as template
    • Insert from template
    • Import from
      • Dropbox
      • Google Drive
      • Gist
      • Clipboard
    • Export to
      • Dropbox
      • Google Drive
      • Gist
    • Download
      • Markdown
      • HTML
      • Raw HTML
Menu Note settings Note Insights Versions and GitHub Sync Sharing URL Create Help
Create Create new note Create a note from template
Menu
Options
Engagement control Make a copy Transfer ownership Delete this note
Import from
Dropbox Google Drive Gist Clipboard
Export to
Dropbox Google Drive Gist
Download
Markdown HTML Raw HTML
Back
Sharing URL Link copied
/edit
View mode
  • Edit mode
  • View mode
  • Book mode
  • Slide mode
Edit mode View mode Book mode Slide mode
Customize slides
Note Permission
Read
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Write
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Engagement control Commenting, Suggest edit, Emoji Reply
  • Invite by email
    Invitee

    This note has no invitees

  • Publish Note

    Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

    Your note will be visible on your profile and discoverable by anyone.
    Your note is now live.
    This note is visible on your profile and discoverable online.
    Everyone on the web can find and read all notes of this public team.
    See published notes
    Unpublish note
    Please check the box to agree to the Community Guidelines.
    View profile
    Engagement control
    Commenting
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    • Everyone
    Suggest edit
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    Emoji Reply
    Enable
    Import from Dropbox Google Drive Gist Clipboard
       Owned this note    Owned this note      
    Published Linked with GitHub
    • Any changes
      Be notified of any changes
    • Mention me
      Be notified of mention me
    • Unsubscribe
    # QuantXに触ってみよう 細かい説明を省き簡単に実装できるところだけ書きました。 細かい説明などは以下のリンクで行なっているので参考にしてください。 https://qiita.com/katakyo/private/c4e0f13247e4d52856a1 ## サンプルコード 今日はこちらをメインに使います https://factory.quantx.io/developer/aa318fa292304975ad45f858ba475a4a Cloneというボタンを押して自分のプロジェクト一覧に保存して使ってみてください。 ### ライブラリーのimport(2~7行目) サンプルコードの2~7行目はライブラリーのimportをしています。 `import 使用したいライブラリー名`でimportできます。 例として ```python= import pandas as pd ``` だとpandasというライブラリーをimportしてきて今後pandasはpdと呼ぶことにするという意味になります。 QuantXで使えるライブラリーは以下になります。 | packages | version | |:--|:--| | Python | 3.6.7 | | numpy | 1.16.3 | | pandas | 0.23.4 | | statsmodels | 0.9.0 | | scikit-learn | 0.21.1 | | scipy | 1.3.0 | | TA-lib | 0.4.17 | | cvxopt | 1.2.3 | | xgboost | 0.90 | | Keras | 2.2.4 | | chainer | 6.0.0 | | tensorflow | 1.13.1 | ## 銘柄、株価データの設定(10~32行目) アルゴリズムで使用する銘柄、株価を登録します。 証券コード7201,1305,9984,9983の銘柄の始値、終値、高値、安値、出来高、売買代金を使用するときは以下のように記述します。 ```python= # 銘柄、株価データの設定 def initialize(ctx): # 設定 ctx.logger.debug("initialize() called") ctx.configure( channels={ # 利用チャンネル "jp.stock": { "symbols": [ "jp.stock.7201", "jp.stock.1305", "jp.stock.9984", "jp.stock.9983", ], "columns": [ "open_price_adj", # 始値(株式分割調整後) "close_price_adj", # 終値(株式分割調整後) "high_price_adj", # 高値(株式分割調整後) "low_price_adj", # 安値(株式分割調整後) "volume_adj", # 出来高 "txn_volume", # 売買代金 ] } } ) ``` enish(3667)のコードを加えたいと思ったらSymbolsの配列に`"jp.stock.3667"`を追加します。 ```python= # 銘柄、株価データの設定 def initialize(ctx): # 設定 ctx.logger.debug("initialize() called") ctx.configure( channels={ # 利用チャンネル "jp.stock": { "symbols": [ "jp.stock.7201", "jp.stock.1305", "jp.stock.9984", "jp.stock.9983", "jp.stock.3667", ], "columns": [ "open_price_adj", # 始値(株式分割調整後) "close_price_adj", # 終値(株式分割調整後) "high_price_adj", # 高値(株式分割調整後) "low_price_adj", # 安値(株式分割調整後) "volume_adj", # 出来高 "txn_volume", # 売買代金 ] } } ) ``` ## 売買シグナルの作成(35~70行目) 今回はRSIが30より大きい時に買い、70より大きい時に売るシグナルを書きます。 ```python= # シグナル定義 def _my_signal(data): # 株価データの取得 cp = data["close_price_adj"].fillna(method='ffill') # op = data["open_price_adj"].fillna(method='ffill') # hp = data["high_price_adj"].fillna(method='ffill') # lp = data["low_price_adj"].fillna(method='ffill') # vol = data["volume_adj"].fillna(method='ffill') # txn = data["txn_volume"].fillna(method='ffill') # テクニカル分析 rsi = pd.DataFrame(data = 0, columns=[], index = cp.index) for (sym, val) in cp.items(): rsi[sym] = ta.RSI(cp[sym],timeperiod = 14) # 売買シグナルを定義 buy_sig = rsi < 30 sell_sig = rsi > 70 # 市況シグナルの定義 market_sig = pd.DataFrame(data=0.0, columns=cp.columns, index=cp.index) # buy_sigがTrueのとき1.0、sell_sigがTrueのとき-1.0とおく market_sig[buy_sig == True] = 1.0 market_sig[sell_sig == True] = -1.0 market_sig[(buy_sig == True) & (sell_sig == True)] = 0.0 # loggerに関しましては右画面のノートをご覧ください⑦ # ctx.logger.debug(market_sig) return { "rsi": rsi, "market:sig": market_sig, } # シグナル登録 ctx.regist_signal("my_signal", _my_signal) ``` 長ったらしいコードですが、別の指標を使いたいと思った時に弄るコードは ```python= # テクニカル分析 rsi = pd.DataFrame(data = 0, columns=[], index = cp.index) for (sym, val) in cp.items(): rsi[sym] = ta.RSI(cp[sym],timeperiod = 14) # 売買シグナルを定義 buy_sig = rsi < 30 sell_sig = rsi > 70 ``` この部分だけです ではRSIの計算をMACDの計算に変えてみましょう。 計算にはTA-Libというライブラリーを使います。 https://mrjbq7.github.io/ta-lib/func_groups/momentum_indicators.html MACDの項目を見ると ``` macd, macdsignal, macdhist = MACD(close, fastperiod=12, slowperiod=26, signalperiod=9) ``` 書いてあるのでこれに従ってコードを書き換えます。 MACDでは計算結果がmacd, macdsignal, macdhistと計算結果が3つ出てくるのが注意です。 ```python= # テクニカル分析 macd = pd.DataFrame(data = 0, columns=[], index = cp.index) macdsignal = pd.DataFrame(data = 0, columns=[], index = cp.index) macdhist = pd.DataFrame(data = 0, columns=[], index = cp.index) for (sym, val) in cp.items(): macd[sym], macdsignal[sym], macdhist[sym] = ta.MACD(cp[sym], fastperiod=12, slowperiod=26, signalperiod=9) # 売買シグナルを定義 buy_sig = (macd > macdsignal) & (macd.shift(1) < macdsignal.shift(1)) sell_sig = (macd < macdsignal) & (macd.shift(1) > macdsignal.shift(1)) ``` また計算する指標が変わったので関数の返り値も変えましょう ```python= return { "macd": macd, "macdsignal":macdsignal, "macdhist":macdhist, "market:sig": market_sig, } ``` MACDに差し替えたサンプルコード https://factory.quantx.io/developer/f3d3a19d92ea48ada7a3c5eb1e6089e7 ## 約定の設定(72~111行目) ここでは損切りや利確の設定や注文の方法を決めます ```python= def handle_signals(ctx, date, current): ''' current: pd.DataFrame ''' market_sig = current["market:sig"] done_syms = set([]) # 損切り、利確の設定 for (sym, val) in ctx.portfolio.positions.items(): returns = val["returns"] if returns < -0.03: # 株の注文方法に関しましては右画面のノートをご覧ください⑨ sec = ctx.getSecurity(sym) sec.order(-val["amount"], comment="損切り(%f)" % returns) done_syms.add(sym) elif returns > 0.05: sec = ctx.getSecurity(sym) sec.order(-val["amount"], comment="利益確定売(%f)" % returns) done_syms.add(sym) # 買いシグナル buy = market_sig[market_sig > 0.0] for (sym, val) in buy.items(): if sym in done_syms: continue sec = ctx.getSecurity(sym) sec.order_percent(0.2, orderType=maron.OrderType.MARKET_OPEN, comment="SIGNAL BUY") #ctx.logger.debug("BUY: %s, %f" % (sec.code(), val)) pass # 売りシグナル sell = market_sig[market_sig < 0.0] for (sym, val) in sell.items(): if sym in done_syms: continue sec = ctx.getSecurity(sym) sec.order_target(0,orderType=maron.OrderType.MARKET_OPEN, comment="SIGNAL SELL") #ctx.logger.debug("SELL: %s, %f" % (sec.code(), val)) pass ``` ### 損切りのパーセンテージを変える時 `if returns < -0.03:` の数値だけ変えましょう。 例えば4%損失が出た時に損切りしたいときは `if returns < -0.04:` と記述してください。 ### 約定の方法を変えるとき ``` `sec.order_percent(0.2, orderType=maron.OrderType.MARKET_OPEN, comment="SIGNAL BUY") ` ``` と記述してある部分の`order_percent`とその数を変えます。 現在ポートフォリオ比率で注文するようになっているので 買いシグナルが出たら一単元株数購入するように変更します。 ``` sec.order(sec.unit() * 1, orderType=maron.OrderType.MARKET_OPEN, comment="SIGNAL BUY") ``` 6種類のオーダー方法がありますので、詳しくはリファレンスをみてください。 https://factory.quantx.io/handbook/ja/api.html#Security ` # Q&A 質問等がございましたらSlackにてご質問ください。 # 応用編 Qiitaにたくさん記事があります。 機会学習を使ったりと様々なものがあるのでみ参考にしてください。 https://qiita.com/Miku_F/items/ffa208d373f7d1c4f942

    Import from clipboard

    Paste your markdown or webpage here...

    Advanced permission required

    Your current role can only read. Ask the system administrator to acquire write and comment permission.

    This team is disabled

    Sorry, this team is disabled. You can't edit this note.

    This note is locked

    Sorry, only owner can edit this note.

    Reach the limit

    Sorry, you've reached the max length this note can be.
    Please reduce the content or divide it to more notes, thank you!

    Import from Gist

    Import from Snippet

    or

    Export to Snippet

    Are you sure?

    Do you really want to delete this note?
    All users will lose their connection.

    Create a note from template

    Create a note from template

    Oops...
    This template has been removed or transferred.
    Upgrade
    All
    • All
    • Team
    No template.

    Create a template

    Upgrade

    Delete template

    Do you really want to delete this template?
    Turn this template into a regular note and keep its content, versions, and comments.

    This page need refresh

    You have an incompatible client version.
    Refresh to update.
    New version available!
    See releases notes here
    Refresh to enjoy new features.
    Your user state has changed.
    Refresh to load new user state.

    Sign in

    Forgot password

    or

    By clicking below, you agree to our terms of service.

    Sign in via Facebook Sign in via Twitter Sign in via GitHub Sign in via Dropbox Sign in with Wallet
    Wallet ( )
    Connect another wallet

    New to HackMD? Sign up

    Help

    • English
    • 中文
    • Français
    • Deutsch
    • 日本語
    • Español
    • Català
    • Ελληνικά
    • Português
    • italiano
    • Türkçe
    • Русский
    • Nederlands
    • hrvatski jezik
    • język polski
    • Українська
    • हिन्दी
    • svenska
    • Esperanto
    • dansk

    Documents

    Help & Tutorial

    How to use Book mode

    Slide Example

    API Docs

    Edit in VSCode

    Install browser extension

    Contacts

    Feedback

    Discord

    Send us email

    Resources

    Releases

    Pricing

    Blog

    Policy

    Terms

    Privacy

    Cheatsheet

    Syntax Example Reference
    # Header Header 基本排版
    - Unordered List
    • Unordered List
    1. Ordered List
    1. Ordered List
    - [ ] Todo List
    • Todo List
    > Blockquote
    Blockquote
    **Bold font** Bold font
    *Italics font* Italics font
    ~~Strikethrough~~ Strikethrough
    19^th^ 19th
    H~2~O H2O
    ++Inserted text++ Inserted text
    ==Marked text== Marked text
    [link text](https:// "title") Link
    ![image alt](https:// "title") Image
    `Code` Code 在筆記中貼入程式碼
    ```javascript
    var i = 0;
    ```
    var i = 0;
    :smile: :smile: Emoji list
    {%youtube youtube_id %} Externals
    $L^aT_eX$ LaTeX
    :::info
    This is a alert area.
    :::

    This is a alert area.

    Versions and GitHub Sync
    Get Full History Access

    • Edit version name
    • Delete

    revision author avatar     named on  

    More Less

    Note content is identical to the latest version.
    Compare
      Choose a version
      No search result
      Version not found
    Sign in to link this note to GitHub
    Learn more
    This note is not linked with GitHub
     

    Feedback

    Submission failed, please try again

    Thanks for your support.

    On a scale of 0-10, how likely is it that you would recommend HackMD to your friends, family or business associates?

    Please give us some advice and help us improve HackMD.

     

    Thanks for your feedback

    Remove version name

    Do you want to remove this version name and description?

    Transfer ownership

    Transfer to
      Warning: is a public team. If you transfer note to this team, everyone on the web can find and read this note.

        Link with GitHub

        Please authorize HackMD on GitHub
        • Please sign in to GitHub and install the HackMD app on your GitHub repo.
        • HackMD links with GitHub through a GitHub App. You can choose which repo to install our App.
        Learn more  Sign in to GitHub

        Push the note to GitHub Push to GitHub Pull a file from GitHub

          Authorize again
         

        Choose which file to push to

        Select repo
        Refresh Authorize more repos
        Select branch
        Select file
        Select branch
        Choose version(s) to push
        • Save a new version and push
        • Choose from existing versions
        Include title and tags
        Available push count

        Pull from GitHub

         
        File from GitHub
        File from HackMD

        GitHub Link Settings

        File linked

        Linked by
        File path
        Last synced branch
        Available push count

        Danger Zone

        Unlink
        You will no longer receive notification when GitHub file changes after unlink.

        Syncing

        Push failed

        Push successfully