見出し画像

米株Python [4-2] スクリーニングデータベース確認

こんにちわ!トミィ(@toushi_tommy)です!4章ではスクリーニングをどんどんやっていきたいと思います。[4-1] でデーベースを作りましたが、さらに強化させていこうと思ってます。また、作ったデータベースを元に、具体的に、どのようにスクリーニングさせるかなどを今後検討していきます。是非、皆様のアイデアも募集してます。(注意:スクリーニングを使って、Finvizサイトから全銘柄のデータを取ってきますので、サーバーへ負荷がかかります。できるだけ時間を空けて実行するようにお願いします。また、スクレイピングを禁止している場合もございますので、自己責任にて実行をお願いします。)

サークルは無料で運営しております。記事内容も無料です。トミィにジュースでもおごってあげようと思った方は投げ銭いただけると、今後の運営の励みになります。

スクレイピング用データーベース作成

まずは、データベースを作ります。このページの最初のプログラムを実行してください。ちなみに、多少変更してアップデートしてますので、もう一度コピーして実行してみてください。

データベースの中身確認

ダウンロードして、csvファイルを見れますが、特定の銘柄を簡単に見るプログラムを書きました。以下の ticker = ’MSFT' の部分を見たい銘柄に変更して実行してみてください。プログラムはこちら

data_dir = '/content/drive/MyDrive/input/'
out_dir = '/content/drive/MyDrive/output/'
module_dir = '/content/drive/MyDrive/module'
font_dir = '/content/drive/MyDrive/fonts/'
import os
import sys
sys.path.append(module_dir)
import pandas as pd
import glob
import plotly.graph_objects as go
from bs4 import BeautifulSoup
import re
import requests
import math
from matplotlib.font_manager import FontProperties
from PIL import Image, ImageDraw, ImageFont
import warnings
warnings.simplefilter('ignore')
import mplfinance as mpf

ticker = 'MSFT'

df_data = pd.read_csv(sorted(glob.glob(data_dir+'stock_data*.csv'), key=lambda f: os.stat(f).st_mtime, reverse=True)[0], index_col=0)
df_base = pd.read_csv(sorted(glob.glob(data_dir+'stock_base*.csv'), key=lambda f: os.stat(f).st_mtime, reverse=True)[0], index_col=0)
########################################################################3
# フォント
jap_font = '/content/drive/MyDrive/module/japanize_matplotlib/fonts/ipaexg.ttf'
jap2_font = font_dir+'meiryo.ttc'
japb_font = '/content/drive/MyDrive/module/japanize_matplotlib/fonts/ipaexg.ttf'
jap3_font = font_dir+'meiryob.ttc'
if os.path.exists(jap2_font): jap_font = jap2_font
if os.path.exists(jap3_font): japb_font = jap3_font
font_cate = ImageFont.truetype(jap_font, 12)
font_cont = ImageFont.truetype(japb_font, 12)
########################################################################3
x_height_all = 1080
y_height_all = 1350
im = Image.new('RGB', (x_height_all, y_height_all), (255,255,255))
draw = ImageDraw.Draw(im)

# グラフ作成 ###
url = 'https://charts2.finviz.com/chart.ashx?ta=1&p=d&t='+ticker
response = requests.get(url, headers={'User-Agent': 'Custom'})
image = response.content
open(out_dir+'tmp.png', 'wb').write(image)
im.paste(Image.open(out_dir+'tmp.png').copy(), (90,20))

# リスト作成 ###
x_num = 4
x_size = 250
y_size = 18
x_start = 40
x_pos = x_start
y_pos = 400
draw.text((x_pos+5, y_pos-20),'stock_base','black',font=font_cont)
for a ,cnt in zip(df_base,range(len(df_base))):
 draw.rectangle([(x_pos, y_pos), (x_pos+int(x_size/2), y_pos+y_size)], fill=(244,244,244), outline=(211,211,211), width=1)
 draw.text((x_pos+5, y_pos+2),a,'black',font=font_cate)
 draw.rectangle([(x_pos+int(x_size/2), y_pos), (x_pos+x_size, y_pos+y_size)], fill=(244,244,244), outline=(211,211,211), width=1)
 str_txt = str(df_base.loc[ticker,a]) 
 col_type = 'blue' if(str_txt[-1:]=='%')&(str_txt[:1]!='-') else 'red' if(str_txt[-1:]=='%')&(str_txt[:1]=='-') else 'black'
 draw.text((x_pos+int(x_size/2)+5, y_pos+2),str_txt,col_type,font=font_cont)
 x_pos = x_start if(cnt%x_num)==(x_num-1) else x_pos + x_size
 y_pos = y_pos + y_size if(cnt%x_num)==(x_num-1) else y_pos

x_pos = x_start
y_pos+=50
draw.text((x_pos+5, y_pos-20),'stock_data','black',font=font_cont)
for a ,cnt in zip(df_data,range(len(df_data))):
 draw.rectangle([(x_pos, y_pos), (x_pos+int(x_size/2), y_pos+y_size)], fill=(244,244,244), outline=(211,211,211), width=1)
 draw.text((x_pos+5, y_pos+2),a,'black',font=font_cate)
 draw.rectangle([(x_pos+int(x_size/2), y_pos), (x_pos+x_size, y_pos+y_size)], fill=(244,244,244), outline=(211,211,211), width=1)
 str_txt = str(df_data.loc[ticker,a]).replace('::','\n')
 draw.text((x_pos+int(x_size/2)+5, y_pos+2),str_txt,'black',font=font_cont)
 x_pos = x_start if(cnt%x_num)==(x_num-1) else x_pos + x_size
 y_pos = y_pos + y_size if(cnt%x_num)==(x_num-1) else y_pos

im.save(out_dir+'screen.png')
import IPython
IPython.display.Image(out_dir+'screen.png')

出力結果はこのようになります。

画像3

二つのファイルstock_base, stock_dataの中身を表示しております。これを見ながらどの項目でどのようにスクリーニングさせるかを決めることができます。

チャートパターンでのスクリーニング

以下、チャートパターンでのスクリーニングになります。ダブルボトムを検索してみましょう。順番は前日比の値上がり順の出力になります。

data_dir = '/content/drive/MyDrive/input/'
import os
import pandas as pd
import glob
import plotly.graph_objects as go

df_data = pd.read_csv(sorted(glob.glob(data_dir+'stock_data*.csv'), key=lambda f: os.stat(f).st_mtime, reverse=True)[0], index_col=0)
df_base = pd.read_csv(sorted(glob.glob(data_dir+'stock_base*.csv'), key=lambda f: os.stat(f).st_mtime, reverse=True)[0], index_col=0)

# 日本で購入できる銘柄に絞る
df_data = df_data.dropna(subset=['銘柄名'])

############################################################################
# テクニカル
# 'Horizontal S/R','TL Resistance','TL Support','Wedge Up','Wedge Down','Triangle Ascending','Triangle Descending',
# 'Wedge','Channel Up','Channel Down','Channel','Double Top','Double Bottom','Multiple Top','Multiple Bottom',
# 'Head & Shoulders','Head & Shoulders Inverse'

title = 'ダブルボトム銘柄'
df_screening = df_data.copy()
df_screening = df_screening[
 (df_screening['Double Bottom']>0)
 ]

# 並び替え(前日値上がり順)
df_screening.sort_values('Change', ascending = False, inplace = True)
df_disp = df_base.loc[df_screening.index,]

##### 表示 #####
fig = go.Figure(data=[go.Table(
 header=dict(values=['No','Ticker','銘柄名','業種','時価総額','RS', 'ROE','EPS YoY','Salse YoY','前日比'], line_color='black', fill_color='rgb(247,203,77)',
             align='center', font_color='black',font_size=16, height=30),
 cells=dict(values=[list(range(1,len(df_disp)+1)),df_disp.index, df_disp['銘柄名'], df_disp['業種'], df_disp['Market Cap'], 
                    ['{:.0f}'.format(s) for s in df_screening['RS']], 
                    df_disp['ROE'], df_disp['EPS Q/Q'], df_disp['Sales Q/Q'],df_disp['Change']],
            line_color='black',
            fill_color=[['rgb(254,248,227)','rgb(255,255,255)']*(int(len(df_disp)/2)+1)],
            align=['center'],
            font_size=16, height=30)
 )],
)
title = title +' ('+str(len(df_screening))+'銘柄)'
fig.update_layout(
 title={'text': title, 'y': 0.9, 'x': 0.5},
 font={ 'family': 'Noto Sans CJK JP', 'size': 16},
 width=1100
)
fig.show()

出力結果は以下の通り

画像1

ローソク足でのスクリーニング

次にローソク足パターンでの検索を行います。十字線で検索してみます。同様に前日比値上がり順です。

data_dir = '/content/drive/MyDrive/input/'
import os
import pandas as pd
import glob
import plotly.graph_objects as go

df_data = pd.read_csv(sorted(glob.glob(data_dir+'stock_data*.csv'), key=lambda f: os.stat(f).st_mtime, reverse=True)[0], index_col=0)
df_base = pd.read_csv(sorted(glob.glob(data_dir+'stock_base*.csv'), key=lambda f: os.stat(f).st_mtime, reverse=True)[0], index_col=0)

# 日本で購入できる銘柄に絞る
df_data = df_data.dropna(subset=['銘柄名'])

############################################################################
# CandleStick
# 'Long Lower Shadow','Long Upper Shadow','Hammer','Inverted Hammer','Spinning Top White','Spinning Top Black','Doji',
# 'Dragonfly Doji','Gravestone Doji','Marubozu White','Marubozu Black'

title = '十字線銘柄'
df_screening = df_data.copy()
df_screening = df_screening[
 (df_screening['Candlestick']=='Doji')
 ]

# 並び替え(前日値上がり順)
df_screening.sort_values('Change', ascending = False, inplace = True)
df_disp = df_base.loc[df_screening.index,]

##### 表示 #####
fig = go.Figure(data=[go.Table(
 header=dict(values=['No','Ticker','銘柄名','業種','時価総額','RS', 'ROE','EPS YoY','Salse YoY','前日比'], line_color='black', fill_color='rgb(247,203,77)',
             align='center', font_color='black',font_size=16, height=30),
 cells=dict(values=[list(range(1,len(df_disp)+1)),df_disp.index, df_disp['銘柄名'], df_disp['業種'], df_disp['Market Cap'], 
                    ['{:.0f}'.format(s) for s in df_screening['RS']], 
                    df_disp['ROE'], df_disp['EPS Q/Q'], df_disp['Sales Q/Q'],df_disp['Change']],
            line_color='black',
            fill_color=[['rgb(254,248,227)','rgb(255,255,255)']*(int(len(df_disp)/2)+1)],
            align=['center'],
            font_size=16, height=30)
 )],
)
title = title +' ('+str(len(df_screening))+'銘柄)'
fig.update_layout(
 title={'text': title, 'y': 0.9, 'x': 0.5},
 font={ 'family': 'Noto Sans CJK JP', 'size': 16},
 width=1100
)
fig.show()

出力結果は以下の通り

画像2

本日は以上です

ここから先は

0字

¥ 150

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

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