はじめに
SBI証券で、ひふみプラスにちょいちょい積立をしているのですが、基準価額の増減がポートフォリオに反映されるのは1日待たないといけません。
また、ひふみプラスはTwitterで基準価額が毎日ツイートされるのですが、いちいちTLを読み返して計算するのも面倒です。
なので毎日通知してくれるバッチをrubyで作りました。
追記
WashBulletを使う際、独自のラッパーを使用していたため、WashBulletのみで動作するように修正しました。
使うGem
Gemは以下の3つを使用しています。
gem 'trading_day_jp'
gem 'washbullet'
gem 'twitter'
trading_day_jpは市場が開いている日か判別するため、
washbulletはPushBulletをrubyで使うため、
twitterはTwitterをrubyで検索するために使用しています。
内容
PushBulletのデバイスIDを取得する方法は、Ruby で Pushbullet を使う - ゆっくり技術ノート!を参考にしました。
# -*- encoding: utf-8 -*-
def getDeviceId (token)
api_response = `curl -s -u #{token}: https://api.pushbullet.com/v2/devices`
deviceInfo = JSON.parse(api_response)
deviceIds = Array.new
deviceInfo["devices"].size.times do |i|
deviceId = deviceInfo["devices"][i]["iden"]
deviceName = deviceInfo["devices"][i]["nickname"]
deviceModel = deviceInfo["devices"][i]["model"]
deviceIds.push([deviceId, deviceName, deviceModel])
end
return deviceIds
end
PUSHBULLET_TOKEN = "PushBulletToken"
TWITTER_KEY = "TwitterKey"
TWITTER_SECRET = "TwitterSecret"
date = Date.today
num = 100000
buy_rate = 30000
washbullet = Washbullet::Client.new(PUSHBULLET_TOKEN)
twitter = Twitter::REST::Client.new(
consumer_key: TWITTER_KEY,
consumer_secret: TWITTER_SECRET,
)
if date.trading_day_jp?
begin
query = "本日の基準価額です。 ☆ひふみ投信"
result_tweets = twitter.search(query,
count: 10,
result_type: "recent",
lang: "ja",
since: "#{date.year}-#{date.month}-#{date.day}_15:00:00_JST",
until: "#{date.year}-#{date.month}-#{date.day}_18:00:00_JST")
if result_tweets.count > 0
text = result_tweets.first.full_text
tmp = text.split("☆")[2].split(" ")
now_rate = tmp[0].split(" ")[1].gsub(/(\d{0,3}),(\d{3})/, '\1\2').to_i
diff_rate = tmp[1].gsub(/(\d{0,3}),(\d{3})/, '\1\2').to_i
buy = num * buy_rate / 10000
now = num * now_rate / 10000
before = num * (now_rate - diff_rate) / 10000
diff = num * diff_rate / 10000
washbullet.push_note(
receiver: :device,
identifier: getDeviceId(PUSHBULLET_TOKEN),
params: {
title: "ひふみプラス #{Time.zone.now}",
body: "¥#{buy.to_s(:delimited)} -> ¥#{before.to_s(:delimited)} -> ¥#{now.to_s(:delimited)} diff: ¥#{diff.to_s(:delimited)}"
}
)
else
raise "Tweet is zero."
end
rescue Twitter::Error::TooManyRequests => error
puts error.rate_limit.reset_at
puts error.rate_limit.reset_in
sleep error.rate_limit.reset_in
retry
rescue => e
puts e.message
sleep 60
retry
end
end
ツイートを取得して、ひふみプラスの基準価額を抜き出しているだけです。
tmp = text.split("☆")[2].split(" ")
を
tmp = text.split("☆")[1].split(" ")
にすることでひふみ投信、
tmp = text.split("☆")[3].split(" ")
にすることでひふみ年金を抜き出します。
大体17時ごろにはツイートされているのですが、たまに17時を過ぎることがあるのでリトライ処理を入れています。
通知内容
ひふみプラス 2017-05-29 17:16:04 +0900
¥300,000 -> ¥310,000 -> ¥312,000 diff: ¥2,000
というように、原資、前日の評価額、当日の評価額、前日比を通知しています。
あとがき
私はこのスクリプトを毎日17時に回しています。
PushBulletというプッシュアプリを入れることで、夕方にはいくら上下したか把握することができます。