導入や演習部を除けばプログラミングの基礎は5時間ほどで 学習する事ができます。
時間のない方、また、これからは子供のプログラミングが必修になるということですので
その親御さん世代の方にもオススメできます。
この講座ではプログラミングを学習するのに
楽しく役立つプログラミングの面白さを学んでいきましょう。
import matplotlib.pyplot as plt %matplotlib inline
import numpy as np import matplotlib.pyplot as plt %matplotlib inline # 乱数を生成 x = np.random.rand(100) y = np.random.rand(100) # 散布図を描画 plt.scatter(x, y)
#サイズ、色、不透明度、線のサイズ、色を指定 plt.scatter(x, y, s=600, c="pink", alpha=0.5, linewidths="2",edgecolors="red")
#グラフのタイトル、X 軸、Y 軸の名前 (ラベル)、グリッド線を表示
plt.scatter(x, y)
plt.title("This is a title")
plt.xlabel("x axis")
plt.ylabel("y axis")
plt.grid(True)
# 乱数を 100 件生成 value = np.random.rand(100) # 散布図を表示 plt.scatter(x, y, s=100, c=value, cmap='Blues') # カラーバーを表示 plt.colorbar()
#正規化における最大値 (0.6)、最小値 (0.4) を指定 plt.scatter(x, y, s=100, c=value, cmap='Blues', vmin=0.4, vmax=0.6) plt.colorbar()
#棒の色、枠線の色、太さを設定 plt.bar(left, height, color="#FF5B70", edgecolor="#CC4959", linewidth=4)
#タイトル、X 軸、Y 軸のラベルを出力
plt.bar(left, height, tick_label=label, align="center")
plt.title("This is a title")
plt.xlabel("x axis")
plt.ylabel("y axis")
plt.grid(True)
#Y 軸方向のエラーバーを黒色 (black) で表示 yerr = np.array([10, 20, 30, 40, 50]) plt.bar(left, height, yerr=yerr, ecolor="black")
#積み上げ棒グラフ height1 = np.array([100, 200, 300, 400, 500]) height2 = np.array([1000, 800, 600, 400, 200]) plt.bar(left, height1, color="green") plt.bar(left, height2, bottom=height1, color="orange")
titanic_df[['Age','Sex']].head()
titanic_df[100:104]
fx_df = pd.read_csv('data/DAT_ASCII_USDJPY_M1_201710.csv',
sep=';',
names=('Time','Open','High','Low','Close',''),
index_col='Time',
parse_dates=True)
fx_df['2017-10-01 17:03:00':'2017-10-01 17:07:00']
titanic_df = pd.read_csv('data/titanic_train.csv')
# Age が70より上の行
titanic_df[titanic_df.Age > 70]
# Ageが71より大きい Age Sex カラムのみ取得
titanic_df[['Age','Sex']][titanic_df.Age > 71]
# Sex がmale の行を抽出
titanic_df[titanic_df['Sex'].isin(['male'])].head(3)
titanic_df[titanic_df['Name'].str.contains('Henry')].head(3)
titanic_df[titanic_df['Name'].str.contains('Henry') & titanic_df['Sex'].isin(['male'])].head(3)
# 欠損値の有る行の削除
titanic_df.dropna().count()
titanic_df.dropna(subset=['Age']).count()
titanic_df['job'] = 'nojob'
titanic_df.head()
data = {'a':[0, 1], 'b':[2, 3]}
d_df = pd.DataFrame(data=data)
d_df
data2 = {'a':[5,6], 'b':[8, 9]}
d_df2 = pd.DataFrame(data=data2)
d_df2
d_df.append(d_df2,ignore_index=True)
titanic_df = pd.read_csv('data/titanic_train.csv')
titanic_df["Pclass"].value_counts()
titanic_df.sort_values("Age",ascending=True).head(4)
# Pclassごとの合計
titanic_df.groupby('Pclass').sum()
# Pclass , Sex ごとの個数
titanic_df.groupby(['Pclass','Sex']).count()
# Ageごとに Fare , Pclass の平均をだす
titanic_df.groupby('Age')[['Fare','Pclass']].mean().head(5)
dataM1 = pd.read_csv('data/DAT_ASCII_USDJPY_M1_201710.csv',
sep=';',
names=('Time','Open','High','Low','Close', ''),
index_col='Time',
parse_dates=True)
dataM1.head(5)
# dfのデータからtfで指定するタイムフレームの4本足データを作成する関数
def TF_ohlc(df, tf):
x = df.resample(tf).ohlc()
O = x['Open']['open']
H = x['High']['high']
L = x['Low']['low']
C = x['Close']['close']
ret = pd.DataFrame({'Open': O, 'High': H, 'Low': L, 'Close': C},
columns=['Open','High','Low','Close'])
return ret.dropna()
def MAonSeries(s, ma_period, ma_method):
return pd.Series(MAonArray(s.values, ma_period, ma_method), index=s.index)
def iEMA(df, ma_period, ma_shift=0, ma_method='EMA', applied_price='Close'):
return MAonSeries(df[applied_price], ma_period, ma_method).shift(ma_shift)
def MAonArray(a, ma_period, ma_method):
if ma_method == 'SMA':
y = SMAonArray(a, ma_period)
elif ma_method == 'EMA':
y = EMAonArray(a, 2/(ma_period+1))
elif ma_method == 'SMMA':
y = EMAonArray(a, 1/ma_period)
elif ma_method == 'LWMA':
h = np.arange(ma_period, 0, -1)*2/ma_period/(ma_period+1)
y = lfilter(h, 1, a)
y[:ma_period-1] = np.nan
return y
def EMAonArray(x, alpha):
x[np.isnan(x)] = 0
y = np.empty_like(x)
y[0] = x[0]
for i in range(1,len(x)):
y[i] = alpha*x[i] + (1-alpha)*y[i-1]
return y
def SMAonArray(x, ma_period):
x[np.isnan(x)] = 0
y = np.empty_like(x)
y[:ma_period-1] = np.nan
y[ma_period-1] = np.sum(x[:ma_period])
for i in range(ma_period, len(x)):
y[i] = y[i-1] + x[i] - x[i-ma_period]
return y/ma_period
df_5m = TF_ohlc(dataM1, '5Min') # 5分足
df_10m = TF_ohlc(dataM1, '10Min') # 10分足
df_15m = TF_ohlc(dataM1, '15Min') # 15分足
df_30m = TF_ohlc(dataM1, '30Min') # 30分足
df_1H = TF_ohlc(dataM1, '1H') # 1時間足
df_4H = TF_ohlc(dataM1, '4H') # 4時間足
df_1D = TF_ohlc(dataM1, 'D') # 日足
# 移動平均線(EMA)
FastMA_1H = iEMA(df_1H, 5) #短期移動平均
MiddMA_1H = iEMA(df_1H, 10) #中期移動平均
SlowMA_1H = iEMA(df_1H, 20) #長期移動平均
df = pd.DataFrame({'Close': df_1H['Close'] , 'FastMA': FastMA_1H, '': MiddMA_1H , 'SlowMA': SlowMA_1H})
display_charts(df, chart_type="stock", title="MA cross", figsize=(960,640), grid=True)
import pandas as pd import numpy as np
import matplotlib import matplotlib.pyplot as plt %matplotlib inline最後の行のinline指定はjupyter上で可視化をさせるためのコードで
| 引数 | 内容 |
|---|---|
| data | numpy ndarray(構造化または同種) Dict、またはDataFrame,Dictには、Series、 配列、定数、またはリストのようなオブジェクト |
| index | 結果のフレームに使用するインデックス。 入力データのインデックス情報がなく インデックスが提供されていない場合は デフォルトでnp.arange(n) |
| columns | 結果のフレームに使用する列ラベル。 列ラベルが指定されていない場合 デフォルトはnp.arange(n) |
| dtype | dtype、デフォルトなし 強制するデータ型。 単一のdtypeのみが許可されます。Noneの場合、推論 |
empty_df = pd.DataFrame()
c_df = pd.DataFrame(columns=[1,2])
c_df = pd.DataFrame(index=[1,2])index=[インデックス名配列] とします。
data = {'a':[0, 1], 'b':[2, 3]}
d_df = pd.DataFrame(data=data)
d_df | a | b | |
|---|---|---|
| 0 | 0 | 2 |
| 1 | 1 | 3 |
date = pd.date_range('2012-1-1', '2012-1-2', freq='D')
di_df = pd.DataFrame(data, index=date)
di_df| a | b | |
|---|---|---|
| 2012-01-01 | 0 | 2 |
| 2012-01-02 | 1 | 3 |
data2 = {'4':11 , '6':22 , '7':33}
e_df = pd.DataFrame(list(data2.items()),columns=['column1','column2'])
e_df| column1 | column2 | |
|---|---|---|
| 0 | 4 | 11 |
| 1 | 7 | 33 |
| 2 | 6 | 22 |
np_df = pd.DataFrame(np.random.randint(low=0, high=10, size=(5, 5)),
columns=['a', 'b', 'c', 'd', 'e'])
np_df| a | b | c | d | e | |
|---|---|---|---|---|---|
| 0 | 6 | 1 | 9 | 9 | 7 |
| 1 | 3 | 2 | 2 | 5 | 2 |
| 2 | 0 | 6 | 6 | 2 | 9 |
| 3 | 8 | 0 | 1 | 1 | 1 |
| 4 | 2 | 4 | 8 | 0 | 8 |
from sklearn.datasets import load_iris iris = load_iris() # データフレームに読み込み iris_df = pd.DataFrame(iris.data, columns=iris.feature_names) # データフレーム内容表示(上から3行) iris_df.head(3)
sepal length (cm) | sepal width (cm) | petal length (cm) | petal width (cm) | |
|---|---|---|---|---|
| 0 | 5.1 | 3.5 | 1.4 | 0.2 |
| 1 | 4.9 | 3.0 | 1.4 | 0.2 |
| 2 | 4.7 | 3.2 | 1.3 | 0.2 |
|
引数 |
内容 |
|
sep |
区切り文字 デフォルト: ‘,’ タブ '\t' セミコロン ';' |
|
delimiter |
sep の代わりに区切り文字を指定可能 デフォルト: None |
|
header |
ヘッダ行の行数を整数で指定 デフォルト: ‘infer’ ヘッダーなしは header=None |
|
names |
ヘッダ名をリストで指定 デフォルト: None 指定方法 names=('Time','Open') |
|
index_col |
行のインデックスに用いる列 デフォルト: None 数値か列名で指定 |
|
dtype |
各行のデータタイプ 例: {‘a’: np.float64, ‘b’: np.int32} デフォルト: None |
|
skiprows |
先頭から読み込みをスキップする行数 デフォルト: None |
|
skipfooter |
末尾から読み込みをスキップする行数 デフォルト: None |
|
nrows |
読み込む行数 デフォルト: None |
|
quotechar |
ダブルクォーテーションなどでクオートされている場合のクオート文字 デフォルト: ‘”‘ |
|
escapechar |
エスケープされている場合のエスケープ文字 デフォルト: None |
|
comment |
コメント行の行頭文字を指定 指定した文字で始まる行を無視 デフォルト: None |
|
encoding |
文字コード デフォルト: None 指定方法 ’utf-8′, ‘shift_jis’, ‘euc_jp’ |
|
parse_dates |
datetime型で読み込むcolumn名(リストや辞書) |
|
date_parser |
parse_datesで指定したcolumnを読み込む自作関数 |
|
na_values |
欠損値とする文字列(リスト) |
titanic_df = pd.read_csv('data/titanic_train.csv')
titanic_df.head(3)
|
PassengerId |
Survived |
Pclass |
Name |
Sex |
Age |
SibSp |
Parch |
Ticket |
Fare |
Cabin |
Embarked |
||
|
0 |
1 |
0 |
3 |
Braund, Mr. Owen Harris |
male |
22.0 |
1 |
0 |
A/5 21171 |
7.2500 |
NaN |
S |
|
|
1 |
2 |
1 |
1 |
Cumings, Mrs. John Bradley (Florence Briggs Th... |
female |
38.0 |
1 |
0 |
PC 17599 |
71.2833 |
C85 |
C |
|
|
2 |
3 |
1 |
3 |
Heikkinen, Miss. Laina |
female |
26.0 |
0 |
0 |
STON/O2. 3101282 |
7.9250 |
NaN |
S |
|
fx_df = pd.read_csv('data/DAT_ASCII_USDJPY_M1_201710.csv',
sep=';',
names=('Time','Open','High','Low','Close',''),
index_col='Time',
parse_dates=True)
fx_df.head()
|
Open |
High |
Low |
Close |
|
||
|
Time |
|
|
|
|
|
|
|
2017-10-01 17:00:00 |
112.627 |
112.658 |
112.526 |
112.526 |
0 |
|
|
2017-10-01 17:01:00 |
112.536 |
112.536 |
112.480 |
112.510 |
0 |
|
|
2017-10-01 17:03:00 |
112.512 |
112.532 |
112.510 |
112.510 |
0 |
|
|
2017-10-01 17:04:00 |
112.513 |
112.514 |
112.513 |
112.514 |
0 |
|
|
2017-10-01 17:05:00 |
112.519 |
112.531 |
112.519 |
112.530 |
0 |
|
dcf_df = pd.read_excel('data/DCFData.xlsx')
dcf_df
|
企業名 |
証券コード |
会計年度 |
売上高 |
営業利益 |
当期純利益 |
支払利息(直近決算期) |
支払利息(前々決算期) |
有利子負債(直近決算期) |
有利子負債(前々決算期) |
ベータ値 |
減価償却費 |
現金同等物 |
有価証券(売却可能) |
投資有価証券(売却可能) |
株価 |
発行済株式数 |
リスクフリーレート |
||
|
0 |
株式会社ファーストリテイリング |
9983 |
2016 |
1786473000000 |
127292000000 |
48052000000 |
39420000000 |
1141000000 |
640457000000 |
388900000000 |
1.24 |
36797000000 |
385431000000 |
0 |
13132000000 |
43130 |
106074000 |
0.00082 |
|
|
1 |
豊商事 |
8747 |
2014 |
4237000000 |
-95000000 |
-255000000 |
0 |
0 |
1250000000 |
1118000000 |
0.77 |
244000000 |
5210000000 |
0 |
881000000 |
400 |
|
|
|
titanic_df = pd.read_csv('data/titanic_train.csv')
titanic_df.describe()
|
PassengerId |
Survived |
Pclass |
Age |
SibSp |
Parch |
Fare |
||
|
count |
891.000000 |
891.000000 |
891.000000 |
714.000000 |
891.000000 |
891.000000 |
891.000000 |
|
|
mean |
446.000000 |
0.383838 |
2.308642 |
29.699118 |
0.523008 |
0.381594 |
32.204208 |
|
|
std |
257.353842 |
0.486592 |
0.836071 |
14.526497 |
1.102743 |
0.806057 |
49.693429 |
|
|
min |
1.000000 |
0.000000 |
1.000000 |
0.420000 |
0.000000 |
0.000000 |
0.000000 |
|
|
25% |
223.500000 |
0.000000 |
2.000000 |
NaN |
0.000000 |
0.000000 |
7.910400 |
|
|
50% |
446.000000 |
0.000000 |
3.000000 |
NaN |
0.000000 |
0.000000 |
14.454200 |
|
|
75% |
668.500000 |
1.000000 |
3.000000 |
NaN |
1.000000 |
0.000000 |
31.000000 |
|
|
max |
891.000000 |
1.000000 |
3.000000 |
80.000000 |
8.000000 |
6.000000 |
512.329200 |
|
titanic_df = pd.read_csv('data/titanic_train.csv')
titanic_df.mean()
PassengerId 446.000000 Survived 0.383838 Pclass 2.308642 Age 29.699118 SibSp 0.523008 Parch 0.381594 Fare 32.204208 dtype: float64
titanic_df = pd.read_csv('data/titanic_train.csv')
titanic_df.sum()
PassengerId 397386.0000 Survived 342.0000 Pclass 2057.0000 Age 21205.1700 SibSp 466.0000 Parch 340.0000 Fare 28693.9493 dtype: float64
titanic_df = pd.read_csv('data/titanic_train.csv')
titanic_df.count()
PassengerId 891 Survived 891 Pclass 891 Name 891 Sex 891 Age 714 SibSp 891 Parch 891 Ticket 891 Fare 891 Cabin 204 Embarked 889 dtype: int64
titanic_df.var()
PassengerId 66231.000000 Survived 0.236772 Pclass 0.699015 Age 211.019125 SibSp 1.216043 Parch 0.649728 Fare 2469.436846 dtype: float64
titanic_df.var(ddof=False)
PassengerId 66156.666667 Survived 0.236506 Pclass 0.698231 Age 210.723580 SibSp 1.214678 Parch 0.648999 Fare 2466.665312 dtype: float64
titanic_df.std()
PassengerId 257.353842 Survived 0.486592 Pclass 0.836071 Age 14.526497 SibSp 1.102743 Parch 0.806057 Fare 49.693429 dtype: float64
titanic_df.std(ddof=False)
PassengerId 257.209383 Survived 0.486319 Pclass 0.835602 Age 14.516321 SibSp 1.102124 Parch 0.805605 Fare 49.665534 dtype: float64
import numpy as np
array_n1 = np.arange(1,10).reshape(3,3) print(np.sqrt(25)) print(np.sqrt([2,3,4])) print(np.sqrt(array_n1))
5.0 [ 1.41421356 1.73205081 2. ] [[ 1. 1.41421356 1.73205081] [ 2. 2.23606798 2.44948974] [ 2.64575131 2.82842712 3. ]]
exp = np.exp([0,1,2,3,4,5]) exp
array([ 1. , 2.71828183, 7.3890561 , 20.08553692, 54.59815003, 148.4131591 ])
なお定数 e も定義されておりnp.e2.718281828459045
となります次に対数関数は以下が定義されています
np.log(x)np.log2(x)np.log10(x)それぞれこのようになりますnp.log([1,2,np.e, np.e ** 2])
array([ 0. , 0.69314718, 1. , 2. ])
np.log2([1,2,4,np.e, np.e ** 2])
array([ 0. , 1. , 2. , 1.44269504, 2.88539008])
np.log10([1,2,10,100,1000,np.e, np.e ** 2])
array([ 0. , 0.30103 , 1. , 2. , 3. ,
0.43429448, 0.86858896])
三角関数も存在します引数 x にはラジアンを指定する必要がありますnp.sin([0,1,2,3,4])
array([ 0. , 0.84147098, 0.90929743, 0.14112001, -0.7568025 ])
これだと分かりづらいので
図にしてみましょう
matplotlibを使って図を作成します
%matplotlib inline は図をjupyter notebookの中に
表示させるために必要なコードです
np.linspaceで複数値を作成し
plt.showで図を表示させます
import matplotlib.pylab as plt
%matplotlib inline
#startからendまでを個数で等分した値を返す
x = np.linspace(-5,5,100)
plt.plot(x, np.sin(x))
plt.xlabel('Angle [rad]')
plt.ylabel('sin(x)')
plt.axis('tight')
plt.show()

最大値が1,最小値が-1になっています
同様にcos , tan も表示させてみます
cos
x = np.linspace(-5,5,100) plt.plot(x, np.cos(x)) plt.xlabel('Angle [rad]') plt.ylabel('cos(x)') plt.axis('tight') plt.show()
tanx = np.linspace(-3.14, 3.14, 100) plt.plot(x, np.tan(x)) plt.xlabel('Angle [rad]') plt.ylabel('tan(x)') plt.axis('tight') plt.show()
タンジェントはちょっと特殊ですね
ここまでの関数の関係性をまとめてグラフにしてみます
x = np.arange(-2*np.pi, 2*np.pi, 0.25) sin = np.sin(x) cos = np.cos(x) tan = np.tan(x) exp = np.exp(x) log = np.log(x) # グラフ表示 plt.plot(x, sin,"-o",lw=2,alpha=0.7,label="sin(x)") plt.plot(x, cos,"-o",lw=2,alpha=0.7,label="cos(x)") plt.plot(x, tan,"-o",lw=2,alpha=0.7,label="tan(x)") plt.plot(x, exp,"-o",lw=2,alpha=0.7,label="exp(x)") plt.plot(x, log,"-o",lw=2,alpha=0.7,label="log(x)") plt.xlabel("$x$", fontsize=30) # x軸のラベル plt.ylabel("$y$", fontsize=30) # y軸のラベル plt.xlim([-4, 4]) # x軸の範囲 plt.ylim([-4, 4]) # y軸の範囲 plt.grid() # グリッドの表示 plt.legend(fontsize=10) # 凡例の表示 plt.show() # グラフの描画matplotlibによる可視化は非常に基本的なテクニックで値を配列に格納し、グラフ化することで
データが把握しやすくなるので
ぜひ覚えておきましょう
numpyには値を生成する関数も多く存在します
まずは標準正規分布に従うランダム値を返すrandn
from numpy.random import * import matplotlib.pyplot as plt Rand1 = randn(10000) # 標準正規分布で乱数を1万個生成 plt.hist(Rand1, bins=100) # 100本のヒストグラムを作成 plt.show()

from numpy.random import * import matplotlib.pyplot as plt Rand2 = rand(10000) plt.hist(Rand2, bins=100) plt.show()

randint(1,10,10)
array([8, 3, 8, 6, 4, 1, 8, 7, 9, 2])
from numpy import *
jk = ["チョキ","グー","パー"]
weight = [0.1,0.2,0.7] # 重み付け
for i in range(10):
print(random.choice(jk, p=weight)) # 指定した確率で1個を抽出
グー パー パー パー チョキ パー パー グー チョキ パー
from numpy import * import matplotlib.pyplot as plt
rw = 1000 # 歩数 step = random.choice([-1,1],rw) # +1 or -1 をn個生成 position = cumsum(step) plt.plot(position)

sample1 = np.array([-2.7, -1.3, -0.9, 0.4, 1.5, 0.1, 2.0]) np.round(sample1)
array([-3., -1., -1., 0., 2., 0., 2.])
np.trunc(sample1)
array([-2., -1., -0., 0., 1., 0., 2.])
np.floor(sample1)
array([-3., -2., -1., 0., 1., 0., 2.])
np.ceil(sample1)
array([-2., -1., -0., 1., 2., 1., 2.])
np.fix(sample1)
array([-2., -1., -0., 0., 1., 0., 2.])