add(SAP) : added reordered code files · pcwpower1/StockAnalysisInPython@f8170df · GitHub
Skip to content

Commit f8170df

Browse files
committed
add(SAP) : added reordered code files
1 parent 213b3e2 commit f8170df

41 files changed

Lines changed: 1736 additions & 0 deletions

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.
Lines changed: 50 additions & 0 deletions
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
from pandas_datareader import data as pdr
2+
import yfinance as yf
3+
yf.pdr_override()
4+
import matplotlib.pyplot as plt
5+
6+
kospi = pdr.get_data_yahoo('^KS11', '2004-01-04')
7+
8+
window = 252
9+
peak = kospi['Adj Close'].rolling(window, min_periods=1).max()
10+
drawdown = kospi['Adj Close']/peak - 1.0
11+
max_dd = drawdown.rolling(window, min_periods=1).min()
12+
13+
plt.figure(figsize=(9, 7))
14+
plt.subplot(211)
15+
kospi['Close'].plot(label='KOSPI', title='KOSPI MDD', grid=True, legend=True)
16+
plt.subplot(212)
17+
drawdown.plot(c='blue', label='KOSPI DD', grid=True, legend=True)
18+
max_dd.plot(c='red', label='KOSPI MDD', grid=True, legend=True)
19+
plt.show()
20+
21+
22+
Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
import pandas as pd
2+
from pandas_datareader import data as pdr
3+
import yfinance as yf
4+
yf.pdr_override()
5+
6+
dow = pdr.get_data_yahoo('^DJI', '2000-01-04')
7+
kospi = pdr.get_data_yahoo('^KS11', '2000-01-04')
8+
9+
df = pd.DataFrame({'DOW' dow['Close'], 'KOSPI' kospi['Close']})
10+
df = df.fillna(method='bfill')
11+
df = df.fillna(method='ffill')
12+
13+
import matplotlib.pyplot as plt
14+
plt.figure(figsize=(7, 7))
15+
plt.scatter(df['DOW'], df['KOSPI'], marker='.')
16+
plt.xlabel('Dow Jones Industrial Average')
17+
plt.ylabel('KOSPI')
18+
plt.show()
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
import pandas as pd
2+
from pandas_datareader import data as pdr
3+
import yfinance as yf
4+
yf.pdr_override()
5+
from scipy import stats
6+
import matplotlib.pylab as plt
7+
8+
dow = pdr.get_data_yahoo('^DJI', '2000-01-04')
9+
kospi = pdr.get_data_yahoo('^KS11', '2000-01-04')
10+
11+
df = pd.DataFrame({'X' dow['Close'], 'Y' kospi['Close']})
12+
df = df.fillna(method='bfill')
13+
df = df.fillna(method='ffill')
14+
15+
regr = stats.linregress(df.X, df.Y)
16+
regr_line = f'Y = {regr.slope.2f} X + {regr.intercept.2f}'
17+
18+
plt.figure(figsize=(7, 7))
19+
plt.plot(df.X, df.Y, '.')
20+
plt.plot(df.X, regr.slope df.X + regr.intercept, 'r')
21+
plt.legend(['DOW x KOSPI', regr_line])
22+
plt.title(f'DOW x KOSPI (R = {regr.rvalue.2f})')
23+
plt.xlabel('Dow Jones Industrial Average')
24+
plt.ylabel('KOSPI')
25+
plt.show()
Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
import pandas as pd
2+
from urllib.request import urlopen
3+
from bs4 import BeautifulSoup
4+
from matplotlib import pyplot as plt
5+
6+
url = 'https://finance.naver.com/item/sise_day.nhn?code=068270&page=1'
7+
with urlopen(url) as doc
8+
html = BeautifulSoup(doc, 'lxml')
9+
pgrr = html.find('td', class_='pgRR')
10+
s = str(pgrr.a['href']).split('=')
11+
last_page = s[-1]
12+
13+
df = pd.DataFrame()
14+
sise_url = 'https://finance.naver.com/item/sise_day.nhn?code=068270'
15+
for page in range(1, int(last_page)+1)
16+
page_url = '{}&page={}'.format(sise_url, page)
17+
df = df.append(pd.read_html(page_url, header=0)[0])
18+
19+
df = df.dropna()
20+
df = df.iloc[030]
21+
df = df.sort_values(by='날짜')
22+
23+
plt.title('Celltrion (close)')
24+
plt.xticks(rotation=90)
25+
plt.plot(df['날짜'], df['종가'], 'co-')
26+
plt.show()
Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
import pandas as pd
2+
from urllib.request import urlopen
3+
from bs4 import BeautifulSoup
4+
from matplotlib import pyplot as plt
5+
from matplotlib import dates as mdates
6+
from mpl_finance import candlestick_ohlc
7+
from datetime import datetime
8+
9+
url = 'https://finance.naver.com/item/sise_day.nhn?code=068270&page=1'
10+
with urlopen(url) as doc:
11+
html = BeautifulSoup(doc, 'lxml')
12+
pgrr = html.find('td', class_='pgRR')
13+
s = str(pgrr.a['href']).split('=')
14+
last_page = s[-1]
15+
16+
df = pd.DataFrame()
17+
sise_url = 'https://finance.naver.com/item/sise_day.nhn?code=068270'
18+
for page in range(1, int(last_page)+1):
19+
page_url = '{}&page={}'.format(sise_url, page)
20+
df = df.append(pd.read_html(page_url, header=0)[0])
21+
22+
df = df.dropna()
23+
df = df.iloc[0:30]
24+
df = df.sort_values(by='날짜')
25+
for idx in range(0, len(df)):
26+
dt = datetime.strptime(df['날짜'].values[idx], '%Y.%m.%d').date()
27+
df['날짜'].values[idx] = mdates.date2num(dt)
28+
ohlc = df[['날짜','시가','고가','저가','종가']]
29+
30+
plt.figure(figsize=(9, 6))
31+
ax = plt.subplot(1, 1, 1)
32+
plt.title('Celltrion (candle stick)')
33+
candlestick_ohlc(ax, ohlc.values, width=0.7, colorup='red', colordown='blue')
34+
ax.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m-%d'))
35+
plt.grid(color='gray', linestyle='--')
36+
plt.show()
Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
import matplotlib.pyplot as plt
2+
from Investar import Analyzer # ①
3+
4+
mk = Analyzer.MarketDB() # ②
5+
df = mk.get_daily_price('005930', '2017-07-10', '2018-06-30') # ③
6+
7+
plt.figure(figsize=(9, 6))
8+
plt.subplot(2, 1, 1)
9+
plt.title('Samsung Electronics (Investar Data)')
10+
plt.plot(df.index, df['close'], 'c', label='Close') # ④
11+
plt.legend(loc='best')
12+
plt.subplot(2, 1, 2)
13+
plt.bar(df.index, df['volume'], color='g', label='Volume')
14+
plt.legend(loc='best')
15+
plt.show()
Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
from pandas_datareader import data as pdr
2+
import yfinance as yf
3+
yf.pdr_override()
4+
import matplotlib.pyplot as plt
5+
6+
df = pdr.get_data_yahoo('005930.KS', '2017-01-01') # ①
7+
8+
plt.figure(figsize=(9, 6))
9+
plt.subplot(2, 1, 1) # ②
10+
plt.title('Samsung Electronics (Yahoo Finance)')
11+
plt.plot(df.index, df['Close'], 'c', label='Close') # ③
12+
plt.plot(df.index, df['Adj Close'], 'b--', label='Adj Close') # ④
13+
plt.legend(loc='best')
14+
plt.subplot(2, 1, 2) # ⑤
15+
plt.bar(df.index, df['Volume'], color='g', label='Volume') # ⑥
16+
plt.legend(loc='best')
17+
plt.show()
Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
import numpy as np
2+
import pandas as pd
3+
import matplotlib.pyplot as plt
4+
from Investar import Analyzer
5+
6+
mk = Analyzer.MarketDB()
7+
stocks = ['삼성전자', 'SK하이닉스', '현대자동차', 'NAVER']
8+
df = pd.DataFrame()
9+
for s in stocks:
10+
df[s] = mk.get_daily_price(s, '2016-01-04', '2018-04-27')['close']
11+
12+
daily_ret = df.pct_change()
13+
annual_ret = daily_ret.mean() * 252
14+
daily_cov = daily_ret.cov()
15+
annual_cov = daily_cov * 252
16+
17+
port_ret = []
18+
port_risk = []
19+
port_weights = []
20+
21+
for _ in range(20000):
22+
weights = np.random.random(len(stocks))
23+
weights /= np.sum(weights)
24+
25+
returns = np.dot(weights, annual_ret)
26+
risk = np.sqrt(np.dot(weights.T, np.dot(annual_cov, weights)))
27+
28+
port_ret.append(returns)
29+
port_risk.append(risk)
30+
port_weights.append(weights)
31+
32+
portfolio = {'Returns': port_ret, 'Risk': port_risk}
33+
for i, s in enumerate(stocks):
34+
portfolio[s] = [weight[i] for weight in port_weights]
35+
df = pd.DataFrame(portfolio)
36+
df = df[['Returns', 'Risk'] + [s for s in stocks]]
37+
38+
df.plot.scatter(x='Risk', y='Returns', figsize=(8, 6), grid=True)
39+
plt.title('Efficient Frontier')
40+
plt.xlabel('Risk')
41+
plt.ylabel('Expected Returns')
42+
plt.show()
Lines changed: 52 additions & 0 deletions

0 commit comments

Comments
 (0)