def show_tweets_by_month(): ''' 앞서 작성한 함수를 이용해 월별 트윗 개수를 보여주는 그래프를 출력합니다. ''' months = range(1, 13) num_tweets = [len(filter_by_month(trump_tweets, month)) for month in months] plt.bar(months, num_tweets, align='center') plt.xticks(months, months) plt.savefig('graph.png') elice_utils = EliceUtils() elice_utils.send_image('graph.png')
from elice_utils import EliceUtils import urllib.request from bs4 import BeautifulSoup elice_utils = EliceUtils() def main(): print("href 출력해보기") list_href = [] url = "http://sports.donga.com/Enter" soup = BeautifulSoup(urllib.request.urlopen(url).read(), "html.parser") # 반복문을 사용해 원하는 정보 range(3,23)까지 find("a")["href"] 를 사용해서 # href 모두 수집하여 list_href에 저장 for i in range(3, 23): list_href.append( soup.find_all("span", class_="tit")[i].find("a")["href"]) # source = soup.find_all("span", class_="tit"): # for i in ragne(3, 23): # link = source[i].find("a")["href"] # list_href.append(link) print(list_href) if __name__ == "__main__": main()
from datetime import datetime import pandas as pd import matplotlib.pyplot as plt import mplfinance as mpf #증권 데이터에 특화된 그래프를 출력하는 라이브러리 import matplotlib.pyplot as plt import matplotlib.ticker as ticker import matplotlib.dates as mdates import numpy as np from elice_utils import EliceUtils elice_utils = EliceUtils() #캔들 차트 그리기 # 주식 데이터 불러오기 df = pd.read_csv('stock.csv', index_col=0, parse_dates=True) df2 = pd.read_csv('stock.csv', index_col=0, parse_dates=True) print('주가 데이터 출력') print(df) # mplfinance 라이브러리를 사용하면 캔들 차트를 간편하게 시각화할 수 있습니다. mc = mpf.make_marketcolors(up='r', down='b') #상승은 빨강, 하락은 파랑 s = mpf.make_mpf_style(marketcolors=mc) #mc로 스타일 저장 mpf.plot(df, type='candle', figscale=1.2, style=s) #type=캔틀차트 표시 # 시각화 함수 plt.savefig("candle-plot.png") elice_utils.send_image("candle-plot.png") #시가 : 아침에 주식시장이 문을 열고나서 처음 이루어진 거래가격 #종가: 주식시장이 문을 닫을 때의 가격 #주가가 올랐을 때는 빨간색으로 표현하며 = ‘양봉’
from datetime import datetime #날짜와 시간을 쉽게 조작할 수 있게 하는 클래스 제공 import pandas as pd import matplotlib.pyplot as plt from elice_utils import EliceUtils elice_utils = EliceUtils() # 주식 데이터 불러오기 df = pd.read_csv('stock.csv') print('초기 데이터 확인') print(df) # 주식 데이터 전처리하기(이전 문제에서 실행했던 코드) df['tomorrow Adj Close'] = df['Adj Close'].shift( -1) # 당일 종가가 아니라 다음 날 종가를 새로운 컬럼으로 추가하기 df['Fluctuation'] = df['tomorrow Adj Close'] - df[ 'Adj Close'] # 주가 변동 데이터(다음날 종가 - 오늘 종가) df['Fluctuation Rate'] = df['Fluctuation'] / df[ 'Adj Close'] # 주가 변동률 데이터(변동 / 오늘 종가) # 변동률의 시각화 plt.figure(figsize=(12, 8)) # 표현할 그래프의 크기 설정 plt.plot(df.index, df['Fluctuation Rate']) # 변동률 데이터 시각화.x축:df.index plt.axhline(y=0, color='red', ls='--') # y축:변동률. 변동률 폭을 관찰하기 위한 기준 수평선 추가 # 시각화 옵션 코드 # (시각화 강의에서 별도로 다루는 내용입니다) plt.legend(loc='best') plt.grid() plt.savefig("plot3.png") #시계열 데이터(Time Serise Data) elice_utils.send_image("plot3.png")
from datetime import datetime #날짜와 시간을 쉽게 조작할 수 있게 하는 클래스 제공 import pandas as pd import matplotlib.pyplot as plt from elice_utils import EliceUtils elice_utils = EliceUtils() # 주식 데이터 불러오기:[105 rows x 7 columns] df = pd.read_csv('stock.csv') print('초기 데이터 확인') print(df) # 주식 데이터 전처리하기(이전 문제에서 실행했던 코드) ma5 = df['Adj Close'].rolling(window=5).mean() ma20 = df['Adj Close'].rolling(window=20).mean() ma60 = df['Adj Close'].rolling(window=60).mean() df.insert(len(df.columns), "MA5", ma5) df.insert(len(df.columns), "MA20", ma20) df.insert(len(df.columns), "MA60", ma60) vma5 = df['Volume'].rolling(window=5).mean() df.insert(len(df.columns), "VMA5", vma5) # 이동평균선의 시각화 plt.plot(df.index, df['MA5'], label = "MA5") # 이동평균선 시각화 index:x축, 범례:ma5 plt.plot(df.index, df['Adj Close'], label='Adj Close') # 수정 종가 시각화
from datetime import datetime #날짜와 시간을 쉽게 조작할 수 있게 하는 클래스 제공 import pandas as pd import matplotlib.pyplot as plt from elice_utils import EliceUtils elice_utils = EliceUtils() # 주식 데이터 불러오기 df = pd.read_csv('stock.csv') print('초기 데이터 확인') print(df) # 주식 데이터 전처리하기(이전 문제에서 실행했던 코드) df['tomorrow Adj Close'] = df['Adj Close'].shift( -1) # 당일 종가가 아니라 다음 날 종가를 새로운 컬럼으로 추가하기 df['Fluctuation'] = df['tomorrow Adj Close'] - df[ 'Adj Close'] # 주가 변동 데이터(다음날 종가 - 오늘 종가) df['Fluctuation Rate'] = df['Fluctuation'] / df[ 'Adj Close'] # 주가 변동률 데이터(변동 / 오늘 종가) # 히스토그램을 이용해 분포 살펴보기 #해당 계급에 값이 얼마나 많은지 파악 가능 df['Fluctuation Rate'].plot.hist() plt.title('Fluctuation Rate Histogram') # 현재까지 그려진 그래프를 보여줌 plt.savefig("hist1.png") elice_utils.send_image("hist1.png") plt.cla() #그래프를 그린 후 초기화 # 커널 밀도함수를 이용해 분포 살펴보기
from elice_utils import EliceUtils elice_utils = EliceUtils() import urllib.request from bs4 import BeautifulSoup import matplotlib.pyplot as plt def main(): url = "http://news.jtbc.joins.com/section/index.aspx?scode=20" req = urllib.request.Request(url) sourcecode = urllib.request.urlopen(url).read() soup = BeautifulSoup(sourcecode, "html.parser") time_list = [] for i in range(3,22): time_list.append(soup.find_all("span", class_="date")[i].get_text().strip()) time_edit = [] for i in range(0,len(time_list)) : time_edit.append(time_list[i][8:10]) first_count = 0 second_count = 0
# Task 1. K-means clustering from scratch import numpy as np import pandas as pd from sklearn.datasets import make_blobs from matplotlib import pyplot as plt from copy import deepcopy from elice_utils import EliceUtils eu = EliceUtils() # Check versions print('numpy version: ', np.__version__) print('pandas version: ', pd.__version__) np.random.seed(12345) # Q1. Create a dataset (X and y) with 3 clusters usng sklearn.datasets.make_blobs X, y = make_blobs(n_samples=800, n_features=2, centers=3, random_state=12345) #print(X.shape,y.shape) # Q2: define a function to calculate Euclidean distance def dist(a, b, ax=1): """ :param a: 1-D input array :param b: 1-D input array :param axis: an integer for the axis of a and b along which to compute the vector norms :return: Eucleadian distance (float) """ return np.linalg.norm(a - b, axis=ax) # axis = 1 행연산
# I am very sorry for # * not obeying PEP8, # * abusing & spamming array comprehension instead of for-loop, # * using dynamic import although it is not dynamic, # * using __setitem__ to avoid variable-assignment limit in lambda, # (:= operator was possible, but that is implemented in Python 3.8) # * creating useless lambda function for each loop, # * finally, last but not least, using not-documented properties (in cs1 libraries) # But I hope you TA guys enjoy this one-lined code. # If you enjoyed this, please push 'Like' and 'Subscribe' button in git.nenw.dev (GitHub @HelloWorld017) """ # --- Your code ends here --- ######################################## download_message = '⬇ Download the result image file from the link below ⬇' print('#' * len(download_message)) print(download_message) sleep(0.1) # Save your image object as a file. image.save_as('./result.png') # Show a download link for your result image file. utils = EliceUtils() utils.send_file('./result.png') sleep(0.1) print('#' * len(download_message))
import numpy as np import matplotlib.pyplot as plt from sklearn.cluster import KMeans from sklearn.datasets import load_digits from sklearn.preprocessing import scale from sklearn.model_selection import train_test_split from sklearn.manifold import Isomap from elice_utils import EliceUtils eu = EliceUtils() np.random.seed(42) digits = load_digits() # Q1. scale digits dataset data = scale(digits.data) n_samples, n_features = data.shape n_digits = len(np.unique(digits.target)) labels = digits.target x_train, x_test, y_train, y_test = train_test_split(data, labels, test_size=0.25, random_state=42) # Q2. Create the KMeans model
# CSV, JSON 모듈을 임포트합니다. import csv import json from elice_utils import EliceUtils elice_utils = EliceUtils() def books_to_json(src_file, dst_file): ''' CSV 데이터를 JSON 형태로 변환합니다. ''' # 아래 함수를 완성하세요. books = [] with open(src_file) as src: reader = csv.reader(src, delimiter=',') # 각 줄 별로 대응되는 book 딕셔너리를 만듭니다. for row in reader: print(row) # 책 정보를 저장하는 딕셔너리를 생성합니다. book = { 'title': row[0], 'author': row[1], 'genre': row[2], 'pages': int(row[3]), 'publisher': row[4] } books.append(book)
import matplotlib.pyplot as plt import matplotlib.font_manager as fm from elice_utils import EliceUtils elice_utils = EliceUtils() # 날짜 별 온도 데이터를 세팅합니다. dates = ["1월 {}일".format(day) for day in range(1, 32)] temperatures = list(range(1, 32)) # 막대 그래프의 막대 위치를 결정하는 pos를 선언합니다. pos = range(len(dates)) # 한국어를 보기 좋게 표시할 수 있도록 폰트를 설정합니다. font = fm.FontProperties(fname='./NanumBarunGothic.ttf') # 막대의 높이가 빈도의 값이 되도록 설정합니다. plt.bar(pos, temperatures, align='center') # 각 막대에 해당되는 단어를 입력합니다. plt.xticks(pos, dates, rotation='vertical', fontproperties=font) # 그래프의 제목을 설정합니다. plt.title('1월 중 기온 변화', fontproperties=font) # Y축에 설명을 추가합니다. plt.ylabel('온도', fontproperties=font) # 단어가 잘리지 않도록 여백을 조정합니다. plt.tight_layout()