旅好きエンジニアのメモ

旅のこと映画、統計、会計、プログラミングなど、気の向くままに語ります

25日の移動平均線をpythonで求める方法

亀のような遅さでトレードの自動売買システムを作成しています。。。 djangoで作ろうとしているので完成が見えない。。。(フロントなくそうかな。。。bottleにしようか。。。)

今回は25日の移動平均線を求めてみました。

はい、下のコードで終わりです!!(pandasすごく便利です)

import pandas as pd
moving_average_list = pd.rolling_mean(daily_bars, 25, 1)

まぁ、実際はここから色々な指標を作成していますがここでは書かないです(笑)

rubyで引数の初期値がある時の順番の個人的に良い方法

引数の初期値がある時の順番で困る時ってありますよね 例えば、第二引数の初期値を設定する時

def file(name="foo.jpg", mode="rb")
  File.open(name, mode)
end

こういう時、第一引数を変えずに、第二引数だけ変えて 呼び出すときは以下のようにしないといけません。

file("foo.jpg", "r")

ただ、これって無駄な感じがします。 なので、以下のように順番を入れ替えたり。。。

def file(mode="rb", name="foo.jpg")
  File.open(name, mode)
end

となる人おもいるかと思いますが、ぶっちゃけ順番に意味があったり、引数増えたりすると、どんどんわかりにくくなります。

なので、個人的にはキーワード引数にするのがいい気がします。

def file(name: "foo.jpg", mode: "rb")
  File.open(name, mode)
end

すると以下のように呼び出せるので。

file(mode: "rb")

まぁ、引数をどうするかは時と場合の設計によるので常々ベストプラクティス考えながら実装できれば良いと思います。

rubyの引数を初期値で配列にするってどうなの?

rubyって色々便利なものがあるんですよね、そこで引数について考察です。 例えば、引数を配列にするとか。

①と②の例は同じことをしていますが①はスッキリしていますが、②は冗長的です。 おそらくruby的に美しいのは①なのでしょう。

①引数を配列にする
argu = "test"
def func1(*argu_list)
  p argu_list
end
func1(argu)
②引数を配列にしない
argu = "test"
def func2(argu)
  argu_list = []
  argu_list << argu
  p argu_list
end
func2(argu)

ただ、個人的にはこれってrubyに慣れ親しんでないとわからない気がします。 いわゆる、はじめからリストを引数に渡せば良いような気もします。

*argu_list使うメリットとしてはインターフェースとして良い場合があるのでメリットも大きいのですが、個人的にはどちらでも良いかなという印象です。

ruby有識者が多いプロジェクトなら *argu_list使って、そうでもないなら使わなくても良いかなと思います。

gitとかはてなブログでプログラムのコードを入れたい時

gitとかはてなブログでプログラムのコードを入れたい時ってありますよね。

その時はバッククオートを3つ使いましょう。 (マークダウン方式の書き方です、はてなブログの場合は設定でマークダウンで書く設定にしましょう。)

pythonならバッククオート3つのあとに"python"とうってあげるとpythonコードになります。 (指定なしでもOK)

・書き方(ちょっと見にくい。。。 良い書き方知ってる人いたら教えてください!) ```python def back_quote(): pass ```

・表示

def back_quote():
    pass

vagrant install方法 (とりあえずまとめてみた)

Vagrantの使い方

virtualboxのインストール

https://www.virtualbox.org/wiki/Downloads

Vagrantのインストール

https://www.vagrantup.com

下記コマンドでバージョンが表示されたらインストール成功です。

vagrant -v

下記URLから好きなOSを選びます

http://www.vagrantbox.es

vagrantをターミナルで打つとVagrantのコマンド一覧が表示されます。

$ vagrant
Usage: vagrant [options] <command> [<args>]

    -v, --version                    Print the version and exit.
    -h, --help                       Print this help.

Common commands:
     box             manages boxes: installation, removal, etc.
     connect         connect to a remotely shared Vagrant environment
     destroy         stops and deletes all traces of the vagrant machine
     global-status   outputs status Vagrant environments for this user
     halt            stops the vagrant machine
     help            shows the help for a subcommand
     init            initializes a new Vagrant environment by creating a Vagrantfile
     login           log in to HashiCorp's Vagrant Cloud
     package         packages a running vagrant environment into a box
     plugin          manages plugins: install, uninstall, update, etc.
     port            displays information about guest port mappings
     powershell      connects to machine via powershell remoting
     provision       provisions the vagrant machine
     push            deploys code in this environment to a configured destination
     rdp             connects to machine via RDP
     reload          restarts vagrant machine, loads new Vagrantfile configuration
     resume          resume a suspended vagrant machine
     share           share your Vagrant environment with anyone in the world
     snapshot        manages snapshots: saving, restoring, etc.
     ssh             connects to machine via SSH
     ssh-config      outputs OpenSSH valid configuration to connect to the machine
     status          outputs status of the vagrant machine
     suspend         suspends the machine
     up              starts and provisions the vagrant environment
     validate        validates the Vagrantfile
     version         prints current and latest Vagrant version

For help on any individual command run `vagrant COMMAND -h`

Additional subcommands are available, but are either more advanced
or not commonly used. To see all subcommands, run the command
`vagrant list-commands`.

今回はubuntu16.04を選びます

$ vagrant box add ubuntu16.04 https://atlas.hashicorp.com/bento/boxes/ubuntu-16.04/versions/2.3.0/providers/virtualbox.box

==> box: Box file was not detected as metadata. Adding it directly...
A name is required when adding a box file directly. Please pass
the `--name` parameter to `vagrant box add`. See
`vagrant box add -h` for more help.
$ 
$ vagrant box add Ubuntu16.04 https://cloud-images.ubuntu.com/xenial/current/xenial-server-cloudimg-amd64-vagrant.box
==> box: Box file was not detected as metadata. Adding it directly...
==> box: Adding box 'Ubuntu16.04' (v0) for provider: 
    box: Downloading: https://cloud-images.ubuntu.com/xenial/current/xenial-server-cloudimg-amd64-vagrant.box
==> box: Successfully added box 'Ubuntu16.04' (v0) for 'virtualbox'!

以下でubuntuがインストールされたかを確認

$ vagrant box list
Ubuntu16.04 (virtualbox, 0)

Vagrantfileを生成

$ mkdir ubuntu
$ cd ubuntu/
$ vagrant init ubuntu16.04
A `Vagrantfile` has been placed in this directory. You are now
ready to `vagrant up` your first virtual environment! Please read
the comments in the Vagrantfile as well as documentation on
`vagrantup.com` for more information on using Vagrant.

ubuntuを起動

$ vagrant up
Bringing machine 'default' up with 'virtualbox' provider...
==> default: Importing base box 'ubuntu16.04'...
==> default: Matching MAC address for NAT networking...
==> default: Setting the name of the VM: ubuntu_default_1501122558979_21668
==> default: Clearing any previously set network interfaces...
==> default: Preparing network interfaces based on configuration...
    default: Adapter 1: nat
==> default: Forwarding ports...
    default: 22 (guest) => 2222 (host) (adapter 1)
==> default: Running 'pre-boot' VM customizations...
==> default: Booting VM...
==> default: Waiting for machine to boot. This may take a few minutes...
    default: SSH address: 127.0.0.1:2222
    default: SSH username: ubuntu
    default: SSH auth method: password
    default: Warning: Connection reset. Retrying...
    default: Warning: Remote connection disconnect. Retrying...
    default: Warning: Connection reset. Retrying...
    default: Warning: Remote connection disconnect. Retrying...
    default: Warning: Connection reset. Retrying...
    default: 
    default: Inserting generated public key within guest...
    default: Removing insecure key from the guest if it's present...
    default: Key inserted! Disconnecting and reconnecting using new SSH key...
==> default: Machine booted and ready!
==> default: Checking for guest additions in VM...
    default: The guest additions on this VM do not match the installed version of
    default: VirtualBox! In most cases this is fine, but in rare cases it can
    default: prevent things such as shared folders from working properly. If you see
    default: shared folder errors, please make sure the guest additions within the
    default: virtual machine match the version of VirtualBox you have installed on
    default: your host and reload your VM.
    default: 
    default: Guest Additions Version: 5.0.40
    default: VirtualBox Version: 5.1
==> default: Mounting shared folders...
    default: /vagrant => /Users/XXX/ubuntu

sshコマンドでubuntuに接続

$ vagrant ssh 
Welcome to Ubuntu 16.04.2 LTS (GNU/Linux 4.4.0-87-generic x86_64)

 * Documentation:  https://help.ubuntu.com
 * Management:     https://landscape.canonical.com
 * Support:        https://ubuntu.com/advantage

  Get cloud support with Ubuntu Advantage Cloud Guest:
    http://www.ubuntu.com/business/services/cloud

0 packages can be updated.
0 updates are security updates.


ubuntu@ubuntu-xenial:~$ 

下記コマンドで不要なosを停止したり削除できます。

$ vagrant halt //停止
$ vagrant destroy //削除

GUIの表示

Vagrantfileの以下の部分のコメントアウトを外すと、VirtualBoxの窓が出てくる。

  config.vm.provider "virtualbox" do |vb|
    # Display the VirtualBox GUI when booting the machine
    vb.gui = true

    # Customize the amount of memory on the VM:
    vb.memory = "1024"
  end

reloadしてあげる

$ vagrant reload

ログインするには

- user : vagrant
- password : vagrant

で、ログインが可能

ubuntu desktopのインストール $ sudo apt-get install ubuntu-desktop

インストール後 $ startx $ sudo reboot

Google Apps Script ローカル環境構築やってみた

ローカル環境を構築する前に node.jsを入れましょう。(下記urlから取得できます)

https://nodejs.org/ja/download/

一応、下記のコマンドでインストール先とバージョンを確認しておきましょう。

インストール先の確認

$ which node

バージョンの確認

$ node --version

node.jsが入ったらnpmコマンドが使えるはずなので以下のパッケージをインストールしましょう。 (npmとは、rubyで言うとgem,pythonで言うとpipのようなパッケージ管理)

$ npm install -g node-google-apps-script

developer consoleの認証情報、OAuth2、その他のアプリケーションでキーが作成され jsonで落とせるはずなので落とす。

https://console.developers.google.com

そしてそのjsonファイルを以下のコマンドで実行する

$ gapps auth ./client_secret_<client_secret_key>.json

するとurlが表示されるので urlをコピーしてブラウザで表示して認証を行う。

次に、GAPを新規に作成して保存を行う。 URLにプロジェクトIDがあるのでコピーをする。("d/"のあとで、次の"/"の部分まで) 下記urlのproject_idと書いている部分である

https://script.google.com/d/project_id/edit?usp=drive_web&folder=00000000000000&splash=yes

コピーしたurlを下記コマンドで実行するとプロジェクトをインストールできる。 $ gapps init

ローカル上でファイルを編集して、下記コマンドを実行するとdrive上のGASも更新される。 ただし、まずDrive APIを有効にしないといけない。(https://console.developers.google.com/apis/library)

$ gapps upload

また下記のurlのコードをコピーしてファイル名を「The basics」と変更して保存し、実行する必要がある

https://developers.google.com/apps-script/guides/docs

参考(すごい参考になりました) http://tech.speee.jp/entry/2016/04/28/190236

※この記事は上記記事を自分なりに必要なところをまとめただけです。

pythonでseleniumでブラウザ自動で動かしてみた(mac)

運営しているサイトを全画面自動でとりあえずたくさん開きたい時ってないですか? (アプリケーションエラーは拾ってくれるようにしてるので、とりあえずページ開いちゃってバグを洗い出すとな感じです。)

今回はとりあえずyahoo finance(米)で試してみます。

pythonselenium を入れてみよう!

pip install selenium

次にchrome用のドライバを入れてください Chrome用ドライバーのインストール

https://sites.google.com/a/chromium.org/chromedriver/downloads

なお、自分はmacですので、下記コマンドで入れました。(こっちのほうがpathとか気にしなくていいので楽です)

brew install chromedriver

以下、6つのyahoo financeの銘柄を開くコードです。 from selenium import webdriver

def start_site_open_test():
    #chrome開きます
    driver = webdriver.Chrome()
    #画面おっきくします
    driver.maximize_window()
    #行きたいページのurl打ち込みます(今回はyahoo)
    url_a = 'https://finance.yahoo.com/quote/'
    url_b = '/history'
    site_open(driver,url_a, url_b)
    driver.close()

def site_open(driver, url_a, url_b):
    #とりあえず6つの銘柄だけ(任意で変えてください)
    stock = ['FB','SNAP','AAPL','NVDA','MSFT','GOOG']
    for i in stock:
        url = url_a + i + url_b
        driver.get(url)

start_site_open_test()