teratail header banner
teratail header banner
質問するログイン新規登録

質問編集履歴

3

タイトルの変更

2021/08/01 04:48

投稿

6606akira
6606akira

スコア6

title CHANGED
@@ -1,1 +1,1 @@
1
- Pythonで日本株のスクリーニング
1
+ Pythonで日本株のスクリーニング 株価
body CHANGED
File without changes

2

誤りの修正

2021/08/01 04:48

投稿

6606akira
6606akira

スコア6

title CHANGED
File without changes
body CHANGED
@@ -11,13 +11,20 @@
11
11
  yf.pdr_override()
12
12
 
13
13
  # Variables
14
+ tickers = si.tickers_sp500()
15
+ tickers = [item.replace(".", "-") for item in tickers] # Yahoo Finance uses dashes instead of dots
16
+ index_name = '^GSPC' # S&P 500
14
17
  start_date = datetime.datetime.now() - datetime.timedelta(days=365)
15
18
  end_date = datetime.date.today()
19
+ exportList = pd.DataFrame(columns=['Stock', "RS_Rating", "50 Day MA", "150 Day Ma", "200 Day MA", "52 Week Low", "52 week High"])
20
+ returns_multiples = []
16
21
 
17
22
  # Index Returns
18
- index_df = pdr.get_data_yahoo('^GSPC', start_date, end_date)
23
+ index_df = pdr.get_data_yahoo(index_name, start_date, end_date)
24
+ index_df['Percent Change'] = index_df['Adj Close'].pct_change()
25
+ index_return = (index_df['Percent Change'] + 1).cumprod()[-1]
19
26
  ```
20
- これでS&P500の全銘柄の1年分の株価データは入手できるのでが、^GSPC部分を^N225に変更しても日本株の株価データが入手きません。すべての日経採用銘柄の株価データを入手したいとき、どのようなコードを書けばよいのでしょうか?いろいろなサイトで調べたのですが、日本株の場合一括で株価データを入手する手段が見当たりませんでした。
27
+ si.tickers_sp500()でS&P500の全銘柄の株価データは入手でき。こような方法ですべての日経採用銘柄の株価データを入手したいとき、どのようなコードを書けばよいのでしょうか?いろいろなサイトで調べたのですが、日本株の場合一括で株価データを入手する手段が見当たりませんでした。
21
28
  ちなみに以下のトレンド解析プログラムで米国株をスクリーニングしています。
22
29
  ```ここに言語を入力
23
30
  # Imports

1

プログラム全貌の追加

2021/08/01 04:22

投稿

6606akira
6606akira

スコア6

title CHANGED
File without changes
body CHANGED
@@ -17,4 +17,108 @@
17
17
  # Index Returns
18
18
  index_df = pdr.get_data_yahoo('^GSPC', start_date, end_date)
19
19
  ```
20
- これでS&P500の全銘柄の1年分の株価データは入手できるのですが、^GSPCの部分を^N225に変更しても日本株の株価データが入手できません。すべての日経採用銘柄の株価データを入手したいとき、どのようなコードを書けばよいのでしょうか?いろいろなサイトで調べたのですが、日本株の場合一括で株価データを入手する手段が見当たりませんでした。
20
+ これでS&P500の全銘柄の1年分の株価データは入手できるのですが、^GSPCの部分を^N225に変更しても日本株の株価データが入手できません。すべての日経採用銘柄の株価データを入手したいとき、どのようなコードを書けばよいのでしょうか?いろいろなサイトで調べたのですが、日本株の場合一括で株価データを入手する手段が見当たりませんでした。
21
+ ちなみに以下のトレンド解析プログラムで米国株をスクリーニングしています。
22
+ ```ここに言語を入力
23
+ # Imports
24
+ from pandas_datareader import data as pdr
25
+ from yahoo_fin import stock_info as si
26
+ from pandas import ExcelWriter
27
+ import yfinance as yf
28
+ import pandas as pd
29
+ import datetime
30
+ import time
31
+ yf.pdr_override()
32
+
33
+ # Variables
34
+ tickers = si.tickers_sp500()
35
+ tickers = [item.replace(".", "-") for item in tickers] # Yahoo Finance uses dashes instead of dots
36
+ index_name = '^GSPC' # S&P 500
37
+ start_date = datetime.datetime.now() - datetime.timedelta(days=365)
38
+ end_date = datetime.date.today()
39
+ exportList = pd.DataFrame(columns=['Stock', "RS_Rating", "50 Day MA", "150 Day Ma", "200 Day MA", "52 Week Low", "52 week High"])
40
+ returns_multiples = []
41
+
42
+ # Index Returns
43
+ index_df = pdr.get_data_yahoo(index_name, start_date, end_date)
44
+ index_df['Percent Change'] = index_df['Adj Close'].pct_change()
45
+ index_return = (index_df['Percent Change'] + 1).cumprod()[-1]
46
+
47
+ # Find top 30% performing stocks (relative to the S&P 500)
48
+ for ticker in tickers:
49
+ # Download historical data as CSV for each stock (makes the process faster)
50
+ df = pdr.get_data_yahoo(ticker, start_date, end_date)
51
+ df.to_csv(f'{ticker}.csv')
52
+
53
+ # Calculating returns relative to the market (returns multiple)
54
+ df['Percent Change'] = df['Adj Close'].pct_change()
55
+ stock_return = (df['Percent Change'] + 1).cumprod()[-1]
56
+
57
+ returns_multiple = round((stock_return / index_return), 2)
58
+ returns_multiples.extend([returns_multiple])
59
+
60
+ print (f'Ticker: {ticker}; Returns Multiple against S&P 500: {returns_multiple}\n')
61
+
62
+ # Creating dataframe of only top 30%
63
+ rs_df = pd.DataFrame(list(zip(tickers, returns_multiples)), columns=['Ticker', 'Returns_multiple'])
64
+ rs_df['RS_Rating'] = rs_df.Returns_multiple.rank(pct=True) * 100
65
+ rs_df = rs_df[rs_df.RS_Rating >= rs_df.RS_Rating.quantile(.70)]
66
+
67
+ # Checking Minervini conditions of top 30% of stocks in given list
68
+ rs_stocks = rs_df['Ticker']
69
+ for stock in rs_stocks:
70
+ try:
71
+ df = pd.read_csv(f'{stock}.csv', index_col=0)
72
+ sma = [50, 150, 200]
73
+ for x in sma:
74
+ df["SMA_"+str(x)] = round(df['Adj Close'].rolling(window=x).mean(), 2)
75
+
76
+ # Storing required values
77
+ currentClose = df["Adj Close"][-1]
78
+ moving_average_50 = df["SMA_50"][-1]
79
+ moving_average_150 = df["SMA_150"][-1]
80
+ moving_average_200 = df["SMA_200"][-1]
81
+ low_of_52week = round(min(df["Low"][-260:]), 2)
82
+ high_of_52week = round(max(df["High"][-260:]), 2)
83
+ RS_Rating = round(rs_df[rs_df['Ticker']==stock].RS_Rating.tolist()[0])
84
+
85
+ try:
86
+ moving_average_200_20 = df["SMA_200"][-20]
87
+ except Exception:
88
+ moving_average_200_20 = 0
89
+
90
+ # Condition 1: Current Price > 150 SMA and > 200 SMA
91
+ condition_1 = currentClose > moving_average_150 > moving_average_200
92
+
93
+ # Condition 2: 150 SMA and > 200 SMA
94
+ condition_2 = moving_average_150 > moving_average_200
95
+
96
+ # Condition 3: 200 SMA trending up for at least 1 month
97
+ condition_3 = moving_average_200 > moving_average_200_20
98
+
99
+ # Condition 4: 50 SMA> 150 SMA and 50 SMA> 200 SMA
100
+ condition_4 = moving_average_50 > moving_average_150 > moving_average_200
101
+
102
+ # Condition 5: Current Price > 50 SMA
103
+ condition_5 = currentClose > moving_average_50
104
+
105
+ # Condition 6: Current Price is at least 30% above 52 week low
106
+ condition_6 = currentClose >= (1.3*low_of_52week)
107
+
108
+ # Condition 7: Current Price is within 25% of 52 week high
109
+ condition_7 = currentClose >= (.75*high_of_52week)
110
+
111
+ # If all conditions above are true, add stock to exportList
112
+ if(condition_1 and condition_2 and condition_3 and condition_4 and condition_5 and condition_6 and condition_7):
113
+ exportList = exportList.append({'Stock': stock, "RS_Rating": RS_Rating ,"50 Day MA": moving_average_50, "150 Day Ma": moving_average_150, "200 Day MA": moving_average_200, "52 Week Low": low_of_52week, "52 week High": high_of_52week}, ignore_index=True)
114
+ print (stock + " made the Minervini requirements")
115
+ except Exception as e:
116
+ print (e)
117
+ print(f"Could not gather data on {stock}")
118
+
119
+ exportList = exportList.sort_values(by='RS_Rating', ascending=False)
120
+ print('\n', exportList)
121
+ writer = ExcelWriter("ScreenOutput.xlsx")
122
+ exportList.to_excel(writer, "Sheet1")
123
+ writer.save()
124
+ ```