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')
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") #시가 : 아침에 주식시장이 문을 열고나서 처음 이루어진 거래가격 #종가: 주식시장이 문을 닫을 때의 가격 #주가가 올랐을 때는 빨간색으로 표현하며 = ‘양봉’ #주가가 내렸을 때는 파란색으로 = ‘음봉’ #캔들의 두꺼운 부분의 양쪽 끝은 시가와 종가 #양봉의 경우 가격이 아래에서 위로 올라갔다는 의미 # = 두꺼운 부분의 아래쪽이 시가, 윗부분이 종가. 음봉의 경우 반대 #캔들의 얇은선의 양 끝은 해당 장 시점의 최고가&최저가
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")
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') # 수정 종가 시각화 # 시각화 옵션(graph) 코드 # (시각화 강의에서 별도로 다루는 내용입니다) plt.legend(loc='best') plt.xticks(rotation = 45) plt.grid() plt.savefig("plot.png") elice_utils.send_image("plot.png")#추세:우상향 그래프
# 주식 데이터 불러오기 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() #그래프를 그린 후 초기화 # 커널 밀도함수를 이용해 분포 살펴보기 df['Fluctuation Rate'].plot.kde() plt.title('Fluctuation Rate KDE plot') # 현재까지 그려진 그래프를 보여줌 plt.savefig("hist1.png") elice_utils.send_image("hist1.png") #주가 데이터가 0에 가장 가까운 것=변동성이 적은 주식
time_edit = [] for i in range(0,len(time_list)) : time_edit.append(time_list[i][8:10]) first_count = 0 second_count = 0 for i in range(0,len(time_edit)) : if (time_edit[i] == "03") : first_count = first_count + 1 else : second_count = second_count + 1 print(first_count) print(second_count) slices_hours = [first_count, second_count] activities = ['first_day', 'second_day'] colors = [ 'gray', 'blue'] plt.pie(slices_hours, labels=activities, colors=colors, startangle=90, autopct='%.1f%%') plt.show() plt.savefig("image.svg",format="svg") elice_utils.send_image("image.svg") if __name__ == "__main__": main()
# Cluster Lables(0, 1, 2) clusters = np.zeros(len(X)) # Error func. - Distance between new centroids and old centroids error = dist(C, C_old, None) print('initial error: ', error) # Loop will run till the error is less than the threshold value while error >= 1e-4: # Q4. Assigning each value to its closest cluster for i in range(len(X)): distances = dist(X[i], C) cluster = np.argmin(distances) clusters[i] = cluster # Storing the old centroid values C_old = deepcopy(C) # Q5. Finding the new centroids by taking the average value for i in range(K): points = [X[j] for j in range(len(X)) if clusters[j] == i] C[i] = np.mean(points, axis=0) error = dist(C, C_old, None) print('final error: ', error) print('final Centroid: ', C) # Plotting along with the final Centroids plt.scatter(C[:, 0], C[:, 1], marker='*', s=250, c='r') plt.savefig("final_cluster.png") eu.send_image("final_cluster.png")
test_size=0.25, random_state=42) # Q2. Create the KMeans model kmeans = KMeans(init='k-means++', n_clusters=10, random_state=42) # Q3. Compute cluster centers and predict cluster index for each samples clusters = kmeans.fit_predict(x_train) print('Clusters: ', clusters) # Create an isomap and fit the `digits` data to it X_iso = Isomap(n_neighbors=10).fit_transform(x_train) # Create a plot with subplots in a grid of 1X2 fig, ax = plt.subplots(1, 2, figsize=(8, 4)) # Adjust layout fig.suptitle('Predicted Versus Training Labels', fontsize=14, fontweight='bold') fig.subplots_adjust(top=0.85) # Add scatterplots to the subplots ax[0].scatter(X_iso[:, 0], X_iso[:, 1], c=clusters) ax[0].set_title('Predicted Training Labels') ax[1].scatter(X_iso[:, 0], X_iso[:, 1], c=y_train) ax[1].set_title('Actual Training Labels') plt.savefig("digits.png") eu.send_image("digits.png")
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() # 그래프를 표시합니다. plt.savefig('graph.png') elice_utils.send_image('graph.png')