Skip to content

Commit b8e92fe

Browse files
Add files via upload
1 parent da84e53 commit b8e92fe

10 files changed

+631
-0
lines changed

Python_01_Dowload__YahooData.py

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
# -*- coding: utf-8 -*-
2+
"""
3+
Created on Fri Nov 27 08:09:11 2020
4+
5+
@author: Tin
6+
"""
7+
# Download stock historical data from Yahoo Finance
8+
9+
import yfinance as yf
10+
yf.pdr_override()
11+
12+
13+
# input
14+
symbol = 'AAPL'
15+
start = '2014-01-01'
16+
end = '2018-01-01'
17+
18+
19+
# dataframe
20+
df = yf.download(symbol,start,end)
21+
22+
# View the first 5 rows
23+
print('First 5 Rows')
24+
print(df.head())
25+
print('-'*80)
26+
27+
# View the last 5 rows
28+
print('Last 5 Rows')
29+
print(df.tail())

Python_02_Modify_Date.py

Lines changed: 150 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,150 @@
1+
# -*- coding: utf-8 -*-
2+
"""
3+
Created on Fri Nov 27 08:09:11 2020
4+
5+
@author: Tin
6+
"""
7+
# Modify Yahoo Dataframe Date
8+
import pandas as pd # Dataframe Library
9+
pd.set_option('max_columns', None) # To show all columns
10+
11+
import yfinance as yf
12+
yf.pdr_override()
13+
14+
15+
# input
16+
symbol = 'AAPL'
17+
start = '2014-01-01'
18+
end = '2018-01-01'
19+
20+
21+
# dataframe
22+
data = yf.download(symbol,start,end)
23+
24+
# View the first 5 rows
25+
print('First 5 Rows')
26+
print(data.head())
27+
print('-'*80)
28+
29+
30+
# Date becomes a columns
31+
df = data.copy() # Copy the original data
32+
dfn = df.reset_index()
33+
print(dfn.head())
34+
print('-'*80)
35+
36+
37+
# Add Year, Month, Day
38+
df['Year'] = df.index.year
39+
df['Month'] = df.index.month
40+
df['Day'] = df.index.day
41+
print('Year, Month, & Day')
42+
print(df.head())
43+
print('-'*80)
44+
45+
46+
# Convert Daily to Weekly
47+
weekly = data.copy()
48+
weekly = weekly.resample('W').last()
49+
print('Weekly Data')
50+
print(weekly.head())
51+
print('-'*80)
52+
53+
54+
# Convert Daily to Monthly
55+
monthly = data.copy()
56+
monthly = monthly.resample('1M').mean()
57+
print('Monthly Data')
58+
print(monthly.head())
59+
print('-'*80)
60+
61+
62+
# Choose Particular Year to analyze
63+
monthly = data.copy()
64+
monthly = monthly.reset_index()
65+
y2017 = monthly[monthly['Date'].dt.year==2017]
66+
print("Analyze Particular Year in Historical Data")
67+
print(y2017)
68+
print('-'*80)
69+
70+
71+
month_name = data.copy()
72+
# Convert Daily to Monthly
73+
# 'BMS', which stands for "business month start frequency"
74+
# 'BM', which stands for "business month end frequency"
75+
month_name = month_name.asfreq('BM')
76+
print('Number of the Month')
77+
print(month_name.head())
78+
print('-'*80)
79+
80+
81+
import calendar
82+
month_name['Month_Number'] = month_name.index.month
83+
month_name['Month_ABBR'] = month_name['Month_Number'].apply(lambda x: calendar.month_abbr[x])
84+
print('Abbreviation for Months')
85+
print(month_name.head())
86+
print('-'*80)
87+
88+
89+
print('Month Name')
90+
month_name['Month_Name'] = month_name['Month_Number'].apply(lambda x: calendar.month_name[x])
91+
print(month_name.head())
92+
print('-'*80)
93+
94+
95+
# Pivot Table Date
96+
df_months = pd.pivot_table(df, index=df.index.month, columns=df.index.year, values = 'Adj Close') # each months
97+
print('Year by Year')
98+
print(df_months)
99+
print('-'*80)
100+
101+
102+
df_days = pd.pivot_table(df, index=df.index.day, columns=df.index.year, values = 'Adj Close') # daily for one whole months
103+
print('Year by Year in daily rows')
104+
print(df_days)
105+
print('-'*80)
106+
107+
108+
df_all_columns = pd.pivot_table(df, index=df.index.month, columns=df.index.year)
109+
print('All columns in yearly')
110+
print(df_all_columns)
111+
print('-'*80)
112+
113+
114+
stock_data = df.copy()
115+
stock_data['Year'] = df.index.year
116+
stock_data['Month'] = df.index.month
117+
stock_data['Day'] = df.index.day
118+
stock_data['Week_Day'] = df.index.dayofweek
119+
stock_data['Week_Day_Name'] = df.index.strftime('%A')
120+
print('Number of day with M-F')
121+
print(stock_data.tail(10))
122+
print('-'*80)
123+
124+
125+
approach1 = stock_data.groupby(['Year', 'Month']).first()['Adj Close']
126+
print('# of Month')
127+
print(approach1.tail(12))
128+
print('-'*80)
129+
130+
131+
approach2 = stock_data.groupby(['Year', 'Day']).first()['Adj Close']
132+
print('# of Day')
133+
print(approach2.tail(12))
134+
print('-'*80)
135+
136+
137+
print('Convert Date to String')
138+
string_date = data.copy()
139+
string_date['Date'] = string_date.index
140+
print(string_date.head())
141+
print('-'*80)
142+
143+
144+
string_date['Date'] = string_date['Date'].dt.strftime("%Y%m%d").astype(int)
145+
print('Convert Date to Numbers')
146+
print(string_date.head())
147+
148+
149+
150+

Python_03_save_csv.py

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
# -*- coding: utf-8 -*-
2+
"""
3+
Created on Fri Dec 4 18:55:42 2020
4+
5+
@author: Tin
6+
"""
7+
# Save Data to CSV
8+
import warnings
9+
warnings.filterwarnings("ignore")
10+
11+
import yfinance as yf
12+
yf.pdr_override()
13+
14+
# input
15+
symbol = 'AMD'
16+
start = '2014-01-01'
17+
end = '2019-01-01'
18+
19+
# Read data
20+
data = yf.download(symbol,start,end)
21+
22+
# Output data into CSV
23+
# To save in your certain folder, change the Users name
24+
data.to_csv("C:/Users/Finance/Desktop/AMD.csv")
25+
26+
27+
28+
symbols = ['PFE','TGT','MA','UNH','VZ','V','WMT','GS']
29+
start = '2014-01-11'
30+
end = '2019-01-01'
31+
stocks_info = yf.download(symbols, start, end)['Adj Close']
32+
stocks_data = stocks_info.iloc[::]
33+
print(stocks_data)
34+
35+
# Output data into CSV
36+
stocks_data.to_csv("C:/Users/Finance/Desktop/stocks_data.csv")

Python_04_Plot_Charts.py

Lines changed: 147 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,147 @@
1+
# -*- coding: utf-8 -*-
2+
"""
3+
Created on Fri Nov 27 08:09:11 2020
4+
5+
@author: Tin
6+
"""
7+
# Plot Line Charts
8+
import pandas as pd # Dataframe Library
9+
import matplotlib.pyplot as plt # Plot Chart Library
10+
11+
pd.set_option('max_columns', None) # To show all columns
12+
13+
import yfinance as yf
14+
yf.pdr_override()
15+
16+
17+
# input
18+
symbol = 'AAPL'
19+
start = '2014-01-01'
20+
end = '2018-01-01'
21+
22+
23+
# dataframe
24+
data = yf.download(symbol,start,end)
25+
26+
# View the first 5 rows
27+
print('First 5 Rows')
28+
print(data.head())
29+
print('-'*80)
30+
31+
print('Line Chart')
32+
plt.figure(figsize=(12,8))
33+
plt.plot(data['Adj Close'])
34+
plt.title("Stock Line Chart")
35+
plt.legend(loc='best')
36+
plt.xlabel("Date")
37+
plt.ylabel("Price")
38+
plt.show()
39+
print('-'*80)
40+
41+
42+
print('Line Chart with Grid')
43+
plt.figure(figsize=(12,8))
44+
plt.plot(data['Adj Close'])
45+
plt.title("Stock Line Chart")
46+
plt.grid()
47+
plt.legend(loc='best')
48+
plt.xlabel("Date")
49+
plt.ylabel("Price")
50+
plt.show()
51+
print('-'*80)
52+
53+
54+
print('Render the grid')
55+
fig, ax = plt.subplots()
56+
data.plot(kind='line', y= 'Adj Close', ax=ax)
57+
# Turn on the grid
58+
ax.grid()
59+
plt.title("Stock Line Chart")
60+
plt.legend(loc='best')
61+
plt.xlabel("Date")
62+
plt.ylabel("Price")
63+
plt.show()
64+
print('-'*80)
65+
66+
67+
print('Customize the grid')
68+
fig, ax = plt.subplots()
69+
data.plot(kind='line', y= 'Adj Close', ax=ax)
70+
# Don't allow the axis to be on top of your data
71+
ax.set_axisbelow(True)
72+
# Customize the grid
73+
ax.grid(linestyle='-', linewidth='0.5', color='red')
74+
plt.title("Stock Line Chart")
75+
plt.xlabel("Date")
76+
plt.ylabel("Price")
77+
plt.show()
78+
print('-'*80)
79+
80+
81+
print('Major grid & Minor Grid')
82+
plt.figure(figsize=(12,8))
83+
plt.plot(data['Adj Close'])
84+
plt.minorticks_on()
85+
plt.grid(b=True, which='major', color='b', linestyle='-')
86+
plt.grid(b=True, which='minor', color='r', linestyle='--')
87+
plt.title("Stock Line Chart")
88+
plt.xlabel("Date")
89+
plt.ylabel("Price")
90+
plt.show()
91+
print('-'*80)
92+
93+
94+
import seaborn as sns # Plot Library 0.9.0 Version
95+
# conda install -c anaconda seaborn=0.9.0
96+
plt.figure(figsize=(10,5))
97+
sns.lineplot(data=data, x=data.index, y='Adj Close')
98+
print('-'*80)
99+
100+
plt.figure(figsize=(10,5))
101+
top = plt.subplot2grid((4,4), (0, 0), rowspan=3, colspan=4)
102+
bottom = plt.subplot2grid((4,4), (3,0), rowspan=1, colspan=4)
103+
top.plot(data.index, data['Adj Close'])
104+
bottom.bar(data.index, data['Volume'])
105+
106+
# set the labels
107+
top.axes.get_xaxis().set_visible(False)
108+
top.set_title('Stock Price and Volume')
109+
top.set_ylabel('Adj Closing Price')
110+
bottom.set_ylabel('Volume')
111+
print('-'*80)
112+
113+
114+
# Candlestick
115+
from mpl_finance import candlestick_ohlc
116+
from matplotlib import dates as mdates
117+
118+
# Converting date to pandas datetime format
119+
dfc = data.copy()
120+
dfc = dfc.reset_index()
121+
dfc['Date'] = pd.to_datetime(dfc['Date'])
122+
dfc['Date'] = dfc['Date'].apply(mdates.date2num)
123+
# dfc.head()
124+
125+
fig = plt.figure(figsize=(14,10))
126+
ax1 = plt.subplot(2, 1, 1)
127+
candlestick_ohlc(ax1,dfc.values, width=0.5, colorup='g', colordown='r', alpha=1.0)
128+
ax1.xaxis_date()
129+
ax1.xaxis.set_major_formatter(mdates.DateFormatter('%d-%m-%Y'))
130+
ax1.set_title('Stock '+ symbol +' Closing Price')
131+
ax1.set_ylabel('Price')
132+
133+
134+
135+
136+
import plotly.graph_objs as go
137+
# from plotly.offline import init_notebook_mode, iplot
138+
139+
df = data.copy()
140+
# Plot OHLC Bar Chart
141+
trace = go.Ohlc(x=df['12-2016'].index,
142+
open=df['12-2016'].Open,
143+
high=df['12-2016'].High,
144+
low=df['12-2016'].Low,
145+
close=df['12-2016'].Close)
146+
data = [trace]
147+
iplot(data, filename='simple_ohlc')

0 commit comments

Comments
 (0)