def test_with_dash_dates(self): df = stock.get_market_price_change_by_ticker(fromdate="2021-01-04", todate="20210111") temp = df.iloc[0:5, 1] == np.array([4615, 25150, 4895, 135500, 5680]) self.assertEqual(temp.sum(), 5) df = stock.get_market_price_change_by_ticker(fromdate="2021-01-04", todate="2021-01-11") temp = df.iloc[0:5, 1] == np.array([4615, 25150, 4895, 135500, 5680]) self.assertEqual(temp.sum(), 5)
def test_price_query(self): # holiday - holiday df = stock.get_market_price_change_by_ticker("20040418", "20040418") self.assertEqual(df.empty, True) # holiday - weekday # - 상장 폐지 종목 079660 (20190625) df = stock.get_market_price_change_by_ticker("20190624", "20190630") print(df.loc['079660']) self.assertEqual(df.loc['079660']['종가'], 0) self.assertEqual(df.loc['079660']['등락률'], -100) # weekday - weekday df = stock.get_market_price_change_by_ticker("20040420", "20040422") self.assertNotEqual(df.empty, True)
def getTop10(self, start, end): # df인 이유는 데이터프레임 객체이기 때문 # 모든 종목에 대한 데이터 프레임이 반환됨 df = stock.get_market_price_change_by_ticker(start, end) #sort_values는 데이터프레임 객체에 존재하는 함수 등락률을 기준으로 내림차순 정렬 할것임 #head함수를 통해 데이터 슬라이싱 return self.to_dict(df.sort_values("등락률", ascending=False).head(10))
def test_with_valid_business_days(self): df = stock.get_market_price_change_by_ticker(fromdate="20210104", todate="20210111") # 종목명 시가 종가 변동폭 등락률 거래량 거래대금 # 티커 # 095570 AJ네트웍스 4615 4360 -255 -553.0 3445854 16332546190 # 006840 AK홀딩스 25150 24800 -350 -139.0 605351 15190840550 # 027410 BGF 4895 4690 -205 -419.0 3296226 16198124270 # 282330 BGF리테일 135500 135500 0 0.0 399330 54474898000 # 138930 BNK금융지주 5680 5720 40 70.0 2211455 125465685660 self.assertIsInstance(df, pd.DataFrame) temp = df.iloc[0:5, 1] == np.array([4615, 25150, 4895, 135500, 5680]) self.assertEqual(temp.sum(), 5)
def test_not_empty_result(self): df = stock.get_market_ohlcv_by_date("20190225", "20190228", "000660") self.assertNotEqual(df.empty, True) df = stock.get_market_price_change_by_ticker("20180301", "20180320") self.assertNotEqual(df.empty, True) df = stock.get_market_fundamental_by_ticker("20180305", "KOSPI") self.assertNotEqual(df.empty, True) df = stock.get_market_fundamental_by_date("20180301", "20180320", '005930') self.assertNotEqual(df.empty, True)
def test_not_empty_result(self): df = stock.get_market_ohlcv_by_date("20190225", "20190228", "000660") self.assertFalse(df.empty) df = stock.get_market_cap_by_date("20190101", "20190131", "005930") self.assertFalse(df.empty) df = stock.get_market_cap_by_ticker("20200625") self.assertFalse(df.empty) df = stock.get_market_price_change_by_ticker("20180301", "20180320") self.assertFalse(df.empty) df = stock.get_market_fundamental_by_ticker("20180305", "KOSPI") self.assertFalse(df.empty) df = stock.get_market_fundamental_by_date("20180301", "20180320", '005930') self.assertFalse(df.empty)
def run_monthly_low_per(year, month, portfolio_num=5): # 거래일 business_day = stock.get_business_days(year, month) start = business_day[0] end = business_day[-1] # PER 0인 종목 필터링 df = stock.get_market_fundamental_by_ticker(date=start, market="KOSPI") cond = df["PER"] != 0 df = df[cond] # PER이 낮은 n개 종목 선정 low_per = df["PER"].nsmallest(n=portfolio_num) # 등락률 fluctuation = stock.get_market_price_change_by_ticker(start, end) df = fluctuation.loc[low_per.index] # 수익률 ror = 1 + (df['등락률'].mean() * 0.01) return ror
def run_annual_pbr_per_combo(year, month=6, portfolio_num=30): # 거래일 business_day = stock.get_business_days(year, month) start = business_day[0] business_day = stock.get_business_days(year + 1, month - 1) end = business_day[-1] # 2.5 <= PER <= 10 df = stock.get_market_fundamental_by_ticker(date=start, market="KOSPI") cond = (df["PER"] >= 2.5) & (df["PER"] <= 10) # 괄호 주의 df = df[cond] # PBR이 낮은 30 종목 low_per = df["PBR"].nsmallest(n=portfolio_num) # 등락률 fluctuation = stock.get_market_price_change_by_ticker(start, end) df = fluctuation.loc[low_per.index] # 수익률 ror = 1 + (df['등락률'].mean() * 0.01) return ror
def test_io_for_holiday(self): df = stock.get_market_price_change_by_ticker("20040418", "20040418") self.assertEqual(df.empty, True)
def test_with_holidays(self): df = stock.get_market_price_change_by_ticker(fromdate="20210710", todate="20210711") self.assertIsInstance(df, pd.DataFrame) self.assertTrue(df.empty)
def printstock(): now = time.strftime('%Y%m%d') df = stock.get_market_price_change_by_ticker(now, now) return jsonify({df.iloc[i].name:df.iloc[i,:].to_dict() for i in range(len(df))})
from pykrx import stock import json # 회사 이름에 대응되는 ticker라는 것이 있는데 그걸 받아온다 tickers = stock.get_market_ticker_list() # print(tickers) myJSON = {} for ticker in tickers: myJSON[ticker] = stock.get_market_ticker_name(ticker) # name = stock.get_market_ticker_name("000540") with open("tickerlist.json", "w") as JSON: json.dump(myJSON, JSON, ensure_ascii=False) # with open("tickerlist.json", "r") as JSON: # myJSON = json.load(JSON) print(myJSON) ohlcv = stock.get_market_ohlcv_by_date("20200501", "20200510", "000660") print(ohlcv) df = stock.get_market_price_change_by_ticker("20200501", "20200510") print(df)
from pykrx import stock df = stock.get_market_price_change_by_ticker("20200319", "20200503") print(df.loc["019170", '시가']) print(df.loc["019170", '종가']) df = stock.get_market_ohlcv_by_date("20200319", "20200503", "019170") print(df.iloc[0]['시가']) print(df.iloc[-1]['종가'])
def test_io_for_weekday(self): df = stock.get_market_price_change_by_ticker("20040420", "20040422") self.assertIsNotNone(df) self.assertNotEqual(df.empty, True)
from pykrx import stock df = stock.get_market_price_change_by_ticker("20100104", "20100129") print(df) #print(df.loc["005880"]["등락률"]) #print(df.loc["009280"]["등락률"])
def test_io_for_delisting(self): # - 상장 폐지 종목 079660 (20190625) df = stock.get_market_price_change_by_ticker("20190624", "20190630") self.assertEqual(df.loc['079660']['종가'], 0) self.assertEqual(df.loc['079660']['등락률'], -100)
font_family = "AppleGothic" elif system_name == "Windows": font_family = "Malgun Gothic" else: # Linux # colab에서는 runtime을 <꼭> 재시작 해야합니다. # 런타임을 재시작 하지 않고 폰트 설치를 하면 기본 설정 폰트가 로드되어 한글이 깨집니다. import matplotlib.font_manager as fm fontpath = '/usr/share/fonts/truetype/nanum/NanumBarunGothic.ttf' font = fm.FontProperties(fname=fontpath, size=9) fm._rebuild() font_family = "NanumBarunGothic" return font_family get_font_family() import matplotlib.pyplot as plt font_family = get_font_family() plt.rc("font", family=font_family) plt.rc("axes", unicode_minus=False) plt.style.use("ggplot") df1 = stock.get_market_price_change_by_ticker("20200102", "20201230") df2 = df1["변동폭"] df1.to_excel('d:/finance/2020주가.xlsx') df2.to_excel('d:/finance/2020변동폭.xlsx') print(df2) df2.plot() plt.show()
from pykrx import stock import pandas as pd import itertools nameList = list() #tickers = stock.get_market_ticker_list() #for each in map(lambda x : stock.get_market_ticker_name(x),tickers): # nameList.append(each) # 랭킹 매길때 df = stock.get_market_price_change_by_ticker("20200401", "20200427") #print(df.sort_values('등락률',ascending=False)) #{df.iloc[i].name:df.iloc[i,:].to_dict() for i in range(len(df))} #for i in itertools.islice(df.items(),2): # print(i) #print({df.iloc[i].name:df.iloc[i,:].to_dict() for i in range(3)}) df = df.sort_values("등락률",ascending=False).head(10) print({df.iloc[i].name:df.iloc[i,:].to_dict() for i in range(len(df))}) #종목별 그래프 그릴 때 #df = stock.get_market_ohlcv_by_date("20200401", "20200402", "950140", "d") #print(df.head(3))
def getTop10(self, start, end): df = stock.get_market_price_change_by_ticker(start, end) return self.to_dict(df.sort_values("등락률", ascending=False).head(10))