見出し画像

米株Python [3-4] スクリーニング出力

こんにちわ!トミィ(@toushi_tommy)です!そろそろ、銘柄選定のスクリーニングをやりたいと思いますが、今回、自分が作ったスクリーニング結果を簡単に出力する方法をご紹介したいと思います。YahooFinance米国版では既に様々なスクリーニングができたり、最初から設定されたスクリーニングを表示することができますので、まずはこちらをご確認ください。

サークルは無料で運営しております。記事内容も無料です。トミィにジュースでもおごってあげようと思った方は投げ銭いただけると、今後の運営の励みになります。(楽天証券で購入できる銘柄リストへの絞り方コードのみ有料記事にしておりますので、下記をご覧ください)

YahooFinanceでのスクリーニング

まず、YahooFinaceの米国版はこちらになります。

このなかの「screeners」を押していただくと、スクリーニングページに移動します。

画像1

この中でまず標準で用意されているものがいくつかあります。


無題

この中の一つを読み込んでみたいと思います。まずは、この中で「Day Gainers」を読んでみます。クリックしてアドレスURLをコピーしてください。

画像4

URLは
url = "https://finance.yahoo.com/screener/predefined/day_gainers"
になります。

以下のコードを実行してみてください。

##############################################
output_dir = '/content/drive/MyDrive/output/'
font_dir   = '/content/drive/MyDrive/fonts/'
##############################################
import os
if not os.path.isdir(output_dir): os.makedirs(output_dir)
import requests
import json
import pandas as pd
from matplotlib.font_manager import FontProperties
from PIL import Image, ImageDraw, ImageFont
import IPython
import time

# 最大出力カウント設定 ###############################
max_out = 25
# スクリーニングページ ###############################
url = "https://finance.yahoo.com/screener/predefined/day_gainers"
######################################################

url_base = url+'?offset=OFFSET&count=COUNT'
flag = 1
page_cnt = 250 # MAX 250
offset = 0
list_json=[]
while flag > 0:
 if offset!=0:time.sleep(3)
 url = url_base.replace("OFFSET", str(offset))
 cnt=max_out-offset if (len(list_json)+page_cnt)>max_out else page_cnt
 url = url.replace("COUNT",str(cnt))
 offset += page_cnt
 response = requests.get(url, headers={'User-Agent': 'Custom'})
 data = str(response.text)
 json_beg = data.find('"results":{"rows"')+18
 json_end = json_beg+1
 while data[json_end] != ']':json_end += 1
 str_json = data[json_beg: json_end+1]
 list_json_tmp = json.loads(str_json)
 list_json = list_json + list_json_tmp
 if len(list_json_tmp)!=page_cnt:flag = 0

######################################################
jap_font = '/content/drive/MyDrive/module/japanize_matplotlib/fonts/ipaexg.ttf'
japb_font = '/content/drive/MyDrive/module/japanize_matplotlib/fonts/ipaexg.ttf'
jap2_font = font_dir+'meiryo.ttc'
jap2b_font = font_dir+'meiryob.ttc'
if os.path.exists(jap2_font): jap_font = jap2_font
if os.path.exists(jap2b_font): japb_font = jap2b_font
######################################################
outfile = output_dir+'out.png'
######################################################
def xycenter(xp, yp, xw, yw, tx, fn):
 x,y = draw.textsize(tx,fn)
 return xp+(xw-x)/2, yp+(yw-y)/2
######################################################

# 出力データ・設定 ###################################
df = pd.DataFrame(
{ "No." : range(1,len(list_json)+1),
  "Ticker" : [s['symbol'] for s in list_json],
 "Name" : [s['longName'][:20] for s in list_json], 
 "時価総額" : [s['marketCap']['fmt'] if 'marketCap' in s else 'N/A' for s in list_json],
 "PER" : [s['trailingPE']['fmt'] if 'trailingPE' in s else 'N/A' for s in list_json],
 "出来高" : [s['regularMarketVolume']['fmt'] for s in list_json],
 "出来高\n(3ヵ月)" : [s['averageDailyVolume3Month']['fmt'] for s in list_json],
 "52週Lo" : [s['fiftyTwoWeekLow']['fmt'] for s in list_json],
 "株価" : [s['regularMarketPrice']['fmt'] for s in list_json],
 "52週Hi" : [s['fiftyTwoWeekHigh']['fmt'] for s in list_json],
 "前日比" : [s['regularMarketChangePercent']['fmt'] for s in list_json]
 }
)
######################################################
# カラム毎の横サイズ
x_width = {"No." :40,"Ticker" :80,"Name" :200,
       "時価総額" :80,"PER" :80,"出来高" :90,"出来高\n(3ヵ月)" :90,
       "52週Lo" :80,"株価" :80,"52週Hi" :80,"前日比" :80
}
y_height_hd = 50 # ヘッダ用 縦サイズ
y_height = 30 # 縦サイズ
split_line = [1,3,5,7,10] # 枠線作成時に縦に線を引く場所
color_cel = ["前日比"] # 出力時に数字に応じて色付け
######################################################

im = Image.new('RGB', (sum(x_width.values())+20, y_height_hd+(len(df))*y_height+20), 'white')
draw = ImageDraw.Draw(im)

x_start = 10
y_start = 10
xpos = x_start
ypos = y_start

# ヘッダ出力 #####
font_head=ImageFont.truetype(japb_font, 16)
for i in x_width:
 draw.rectangle([(xpos, ypos), (xpos+x_width[i], ypos+y_height_hd)], fill=(247, 203, 77), outline=(0,0,0),  width=1)
 draw.text((xycenter(xpos,ypos,x_width[i],y_height_hd,i,font_head)),i, (0,0,0),font=font_head)
 xpos+=x_width[i]

# データ出力 ####
font_txt=ImageFont.truetype(jap_font, 16)
ypos+=y_height_hd
for i in range(len(df)):
 xpos = x_start
 draw.rectangle([(xpos, ypos), (xpos+sum(x_width.values()), ypos+y_height)], outline=(0,0,0),  width=1
   , fill=((255,255,255) if i%2 == 0 else (254, 248, 227)))

 # データ ####
 for j in x_width:
   draw.rectangle([(xpos, ypos), (xpos+x_width[j], ypos+y_height)], outline=(0,0,0),  width=1)
   txt_color = (0,0,0) if j not in color_cel else 'red' if str(df[j][i])[:1]=='-' else 'blue'
   draw.text((xycenter(xpos,ypos,x_width[j],y_height,str(df[j][i]),font_txt)),str(df[j][i]), txt_color,font=font_txt)
   xpos+=x_width[j]
 ypos+=y_height

######################################################
# 枠線
# 外枠
draw.rectangle([(x_start, y_start), (xpos, y_start+y_height_hd)], outline='black', width=3)
# ヘッダ枠
draw.rectangle([(x_start, y_start), (xpos, ypos)], outline='black', width=3)
# 縦線
for i in split_line:
 draw.line((x_start+sum(list(x_width.values())[0:i]), y_start, x_start+sum(list(x_width.values())[0:i]), ypos), fill='black', width=3)

im.save(outfile)
IPython.display.Image(outfile)

実行結果はこちらです。

画像5

課題

その他のスクリーニング条件でデータを出力してみてください。「Most Shorted Stocks」「Undervalued Growth Stocks」「Growth Technology Stocks」等々

楽天証券で購入可能な銘柄に絞り、銘柄名、業種を日本語表記に出力したコードは有料部分(コーヒーをおごっていただいた方)のみ公開します。このような出力になります。

画像5

Yahoo Finance カスタムスクリーニング作成

標準のスクリーニングと同様に、自分でスクリーナーを作成して出力させることができます。ScreenersからEquity Screenerを選んでください。

画像6

ここで探したいスクリーニング条件を作成します。「Add another filter」を押して条件を追加します。

画像7

例えば、SmallCap/MidCapで前日比30%以上のペニー株(5ドル以下)を検索してみます。

画像8

検索条件を入力後、作成したURLをコピーします。

画像9

先ほどのコードの以下の部分を変更してみてください。

# 最大出力カウント設定 ###############################
max_out = 25
# スクリーニングページ ###############################
url = "https://finance.yahoo.com/screener/predefined/day_gainers"
######################################################

url部分及び出力したい最大銘柄数を変更します。

# 最大出力カウント設定 ###############################
max_out = 30
# スクリーニングページ ###############################
url = "https://finance.yahoo.com/screener/unsaved/23b5d996-54c0-4992-9459-1eecb818979b"
######################################################

出力結果は以下の通りです。

画像10

日本語版はこんな感じです

画像11

実際買える銘柄は一つしかないんですね・・・

課題

自分の好きなスクリーニング条件を作って出力してみましょう。

楽天証券で購入可能な銘柄出力

楽天証券で購入可能な銘柄に絞ってさらに出力を増やす場合のコードは以下になります。こちらのコードは有料(コーヒー代)でのご提供になります。(追加したのは# 日本語表記 追加部分の部分のみです。ちなみに、カスタムコード集にも掲載しますので、そちらをご購入いただいた方は見れるようにしておきます。)


ここから先は

5,503字

¥ 150

期間限定 PayPay支払いすると抽選でお得に!

サポートいただけますと、うれしいです。より良い記事を書く励みになります!