python數(shù)據(jù)分析(七)

# -*- coding: utf-8 -*-

from __future__ import division

from numpy.random import randn

import numpy as np

# -*- coding: utf-8 -*-

###通用函數(shù)

arr = np.arange(10)

np.sqrt(arr)

np.exp(arr)

x = randn(8)

y = randn(8)

x

y

np.maximum(x, y) # 元素級(jí)最大值

arr = randn(7) * 5

print arr

np.modf(arr)

###利用數(shù)組進(jìn)行數(shù)據(jù)處理

#向量化

points = np.arange(-5, 5, 0.01) # 1000 equally spaced points

xs, ys = np.meshgrid(points, points)

ys

import matplotlib.pyplot as plt

z = np.sqrt(xs ** 2 + ys ** 2)

z

plt.imshow(z, cmap=plt.cm.gray); plt.colorbar()

plt.title("Image plot of $\sqrt{x^2 + y^2}$ for a grid of values")

plt.draw()

#將條件邏輯表達(dá)為數(shù)組運(yùn)算

xarr = np.array([1.1, 1.2, 1.3, 1.4, 1.5])

yarr = np.array([2.1, 2.2, 2.3, 2.4, 2.5])

cond = np.array([True, False, True, True, False])

result = [(x if c else y)

for x, y, c in zip(xarr, yarr, cond)]

result

result = np.where(cond, xarr, yarr)

result

arr = randn(4, 4)

arr

np.where(arr > 0, 2, -2)

np.where(arr > 0, 2, arr) # set only positive values to 2

# Not to be executed

result = []

for i in range(n):

if cond1[i] and cond2[i]:

result.append(0)

elif cond1[i]:

result.append(1)

elif cond2[i]:

result.append(2)

else:

result.append(3)

# Not to be executed

np.where(cond1 & cond2, 0,

np.where(cond1, 1,

np.where(cond2, 2, 3)))

# Not to be executed

result = 1 * cond1 + 2 * cond2 + 3 * -(cond1 | cond2)

#數(shù)學(xué)與統(tǒng)計(jì)方法

arr = np.random.randn(5, 4) # 標(biāo)準(zhǔn)正態(tài)分布數(shù)據(jù)

arr.mean()

np.mean(arr)

arr.sum()

arr.mean(axis=1)

arr.sum(0)

arr = np.array([[0, 1, 2], [3, 4, 5], [6, 7, 8]])

arr.cumsum(0)

arr.cumprod(1)

#用于布爾型數(shù)組的方法

arr = randn(100)

(arr > 0).sum() # 正值的數(shù)量

bools = np.array([False, False, True, False])

bools.any()

bools.all()

#排序

arr = randn(8)

arr

arr.sort()

arr

arr = randn(5, 3)

arr

arr.sort(1)

arr

large_arr = randn(1000)

large_arr.sort()

large_arr[int(0.05 * len(large_arr))] # 5%分位數(shù)

#唯一化以及其他的集合邏輯

names = np.array(['Bob', 'Joe', 'Will', 'Bob', 'Will', 'Joe', 'Joe'])

np.unique(names)

ints = np.array([3, 3, 3, 2, 2, 1, 1, 4, 4])

np.unique(ints)

sorted(set(names))

values = np.array([6, 0, 0, 3, 2, 5, 6])

np.in1d(values, [2, 3, 6])

###線(xiàn)性代數(shù)

x = np.array([[1., 2., 3.], [4., 5., 6.]])

y = np.array([[6., 23.], [-1, 7], [8, 9]])

x

y

x.dot(y) ?# 等價(jià)于np.dot(x, y)

np.dot(x, np.ones(3))

np.random.seed(12345)

from numpy.linalg import inv, qr

X = randn(5, 5)

mat = X.T.dot(X)

inv(mat)

mat.dot(inv(mat))

q, r = qr(mat)

r

###隨機(jī)數(shù)生成

samples = np.random.normal(size=(4, 4))

samples

from random import normalvariate

N = 1000000

get_ipython().magic(u'timeit samples = [normalvariate(0, 1) for _ in xrange(N)]')

get_ipython().magic(u'timeit np.random.normal(size=N)')

# 范例:隨機(jī)漫步

import random

position = 0

walk = [position]

steps = 1000

for i in xrange(steps):

step = 1 if random.randint(0, 1) else -1

position += step

walk.append(position)

np.random.seed(12345)

nsteps = 1000

draws = np.random.randint(0, 2, size=nsteps)

steps = np.where(draws > 0, 1, -1)

walk = steps.cumsum()

walk.min()

walk.max()

(np.abs(walk) >= 10).argmax()

# 一次模擬多個(gè)隨機(jī)漫步

nwalks = 5000

nsteps = 1000

draws = np.random.randint(0, 2, size=(nwalks, nsteps)) # 0 or 1

steps = np.where(draws > 0, 1, -1)

walks = steps.cumsum(1)

walks

walks.max()

walks.min()

hits30 = (np.abs(walks) >= 30).any(1)

hits30

hits30.sum() # 到達(dá)30或-30的數(shù)量

crossing_times = (np.abs(walks[hits30]) >= 30).argmax(1)

crossing_times.mean()

steps = np.random.normal(loc=0, scale=0.25,

size=(nwalks, nsteps))

###利用NumPy進(jìn)行歷史股價(jià)分析

import sys

#讀入文件

c,v=np.loadtxt('data.csv', delimiter=',', usecols=(6,7), unpack=True)

#計(jì)算成交量加權(quán)平均價(jià)格

vwap = np.average(c, weights=v)

print "VWAP =", vwap

#算術(shù)平均值函數(shù)

print "mean =", np.mean(c)

#時(shí)間加權(quán)平均價(jià)格

t = np.arange(len(c))

print "twap =", np.average(c, weights=t)

#尋找最大值和最小值

h,l=np.loadtxt('data.csv', delimiter=',', usecols=(4,5), unpack=True)

print "highest =", np.max(h)

print "lowest =", np.min(l)

print (np.max(h) + np.min(l)) /2

print "Spread high price", np.ptp(h)

print "Spread low price", np.ptp(l)

#統(tǒng)計(jì)分析

c=np.loadtxt('data.csv', delimiter=',', usecols=(6,), unpack=True)

print "median =", np.median(c)

sorted = np.msort(c)

print "sorted =", sorted

N = len(c)

print "middle =", sorted[(N - 1)/2]

print "average middle =", (sorted[N /2] + sorted[(N - 1) / 2]) / 2

print "variance =", np.var(c)

print "variance from definition =", np.mean((c - c.mean())**2)

#股票收益率

c=np.loadtxt('data.csv', delimiter=',', usecols=(6,), unpack=True)

returns = np.diff( c ) / c[ : -1]

print "Standard deviation =", np.std(returns)

logreturns = np.diff( np.log(c) )

posretindices = np.where(returns > 0)

print "Indices with positive returns", posretindices

annual_volatility = np.std(logreturns)/np.mean(logreturns)

annual_volatility = annual_volatility / np.sqrt(1./252.)

print "Annual volatility", annual_volatility

print "Monthly volatility", annual_volatility * np.sqrt(1./12.)

#日期分析

from datetime import datetime

# Monday 0

# Tuesday 1

# Wednesday 2

# Thursday 3

# Friday 4

# Saturday 5

# Sunday 6

def datestr2num(s):

return datetime.strptime(s, "%d-%m-%Y").date().weekday()

dates, close=np.loadtxt('data.csv', delimiter=',', usecols=(1,6),

converters={1: datestr2num}, unpack=True)

print "Dates =", dates

averages = np.zeros(5)

for i in range(5):

indices = np.where(dates == i)

prices = np.take(close, indices)

avg = np.mean(prices)

print "Day", i, "prices", prices, "Average", avg

averages[i] = avg

top = np.max(averages)

print "Highest average", top

print "Top day of the week", np.argmax(averages)

bottom = np.min(averages)

print "Lowest average", bottom

print "Bottom day of the week", np.argmin(averages)

#周匯總

def datestr2num(s):

return datetime.strptime(s, "%d-%m-%Y").date().weekday()

dates, open, high, low, close=np.loadtxt('data.csv', delimiter=',',

usecols=(1, 3, 4, 5, 6), converters={1: datestr2num}, unpack=True)

close = close[:16]

dates = dates[:16]

# get first Monday

first_monday = np.ravel(np.where(dates == 0))[0]

print "The first Monday index is", first_monday

# get last Friday

last_friday = np.ravel(np.where(dates == 4))[-1]

print "The last Friday index is", last_friday

weeks_indices = np.arange(first_monday, last_friday + 1)

print "Weeks indices initial", weeks_indices

weeks_indices = np.split(weeks_indices, 3)

print "Weeks indices after split", weeks_indices

def summarize(a, o, h, l, c):

monday_open = o[a[0]]

week_high = np.max( np.take(h, a) )

week_low = np.min( np.take(l, a) )

friday_close = c[a[-1]]

return("APPL", monday_open, week_high, week_low, friday_close)

weeksummary = np.apply_along_axis(summarize, 1, weeks_indices, open, high, low, close)

print "Week summary", weeksummary

np.savetxt("weeksummary.csv", weeksummary, delimiter=",", fmt="%s")

#真實(shí)波動(dòng)幅度均值

h, l, c = np.loadtxt('data.csv', delimiter=',', usecols=(4, 5, 6), unpack=True)

N =20

h = h[-N:]

l = l[-N:]

print "len(h)", len(h), "len(l)", len(l)

print "Close", c

previousclose = c[-N -1: -1]

print "len(previousclose)", len(previousclose)

print "Previous close", previousclose

truerange = np.maximum(h - l, h - previousclose, previousclose - l)

print "True range", truerange

atr = np.zeros(N)

atr[0] = np.mean(truerange)

for i in range(1, N):

atr[i] = (N - 1) * atr[i - 1] + truerange[i]

atr[i] /= N

print "ATR", atr

#簡(jiǎn)單移動(dòng)平均線(xiàn)

from matplotlib.pyplot import plot

from matplotlib.pyplot import show

N = 5

weights = np.ones(N) / N

print "Weights", weights

c = np.loadtxt('data.csv', delimiter=',', usecols=(6,), unpack=True)

sma = np.convolve(weights, c)[N-1:-N+1]

t = np.arange(N - 1, len(c))

plot(t, c[N-1:], lw=1.0)

plot(t, sma, lw=2.0)

show()

#指數(shù)移動(dòng)平均線(xiàn)

x = np.arange(5)

print "Exp", np.exp(x)

print "Linspace", np.linspace(-1, 0, 5)

N = 5

weights = np.exp(np.linspace(-1., 0., N))

weights /= weights.sum()

print "Weights", weights

c = np.loadtxt('data.csv', delimiter=',', usecols=(6,), unpack=True)

ema = np.convolve(weights, c)[N-1:-N+1]

t = np.arange(N - 1, len(c))

plot(t, c[N-1:], lw=1.0)

plot(t, ema, lw=2.0)

show()

#布林帶

N = 5

weights = np.ones(N) / N

print "Weights", weights

c = np.loadtxt('data.csv', delimiter=',', usecols=(6,), unpack=True)

sma = np.convolve(weights, c)[N-1:-N+1]

deviation = []

C = len(c)

for i in range(N - 1, C):

if i + N < C:

dev = c[i: i + N]

else:

dev = c[-N:]

averages = np.zeros(N)

averages.fill(sma[i - N - 1])

dev = dev - averages

dev = dev ** 2

dev = np.sqrt(np.mean(dev))

deviation.append(dev)

deviation = 2 * np.array(deviation)

print len(deviation), len(sma)

upperBB = sma + deviation

lowerBB = sma - deviation

c_slice = c[N-1:]

between_bands = np.where((c_slice < upperBB) & (c_slice > lowerBB))

print lowerBB[between_bands]

print c[between_bands]

print upperBB[between_bands]

between_bands = len(np.ravel(between_bands))

print "Ratio between bands", float(between_bands)/len(c_slice)

t = np.arange(N - 1, C)

plot(t, c_slice, lw=1.0)

plot(t, sma, lw=2.0)

plot(t, upperBB, lw=3.0)

plot(t, lowerBB, lw=4.0)

show()

#線(xiàn)性模型

N = int(sys.argv[1])

c = np.loadtxt('data.csv', delimiter=',', usecols=(6,), unpack=True)

b = c[-N:]

b = b[::-1]

print "b", b

A = np.zeros((N, N), float)

print "Zeros N by N", A

for i in range(N):

A[i, ] = c[-N - 1 - i: - 1 - i]

print "A", A

(x, residuals, rank, s) = np.linalg.lstsq(A, b)

print x, residuals, rank, s

print np.dot(b, x)

#趨勢(shì)線(xiàn)

def fit_line(t, y):

A = np.vstack([t, np.ones_like(t)]).T

return np.linalg.lstsq(A, y)[0]

h, l, c = np.loadtxt('data.csv', delimiter=',', usecols=(4, 5, 6), unpack=True)

pivots = (h + l + c) / 3

print "Pivots", pivots

t = np.arange(len(c))

sa, sb = fit_line(t, pivots - (h - l))

ra, rb = fit_line(t, pivots + (h - l))

support = sa * t + sb

resistance = ra * t + rb

condition = (c > support) & (c < resistance)

print "Condition", condition

between_bands = np.where(condition)

print support[between_bands]

print c[between_bands]

print resistance[between_bands]

between_bands = len(np.ravel(between_bands))

print "Number points between bands", between_bands

print "Ratio between bands", float(between_bands)/len(c)

print "Tomorrows support", sa * (t[-1] + 1) + sb

print "Tomorrows resistance", ra * (t[-1] + 1) + rb

a1 = c[c > support]

a2 = c[c < resistance]

print "Number of points between bands 2nd approach" ,len(np.intersect1d(a1, a2))

plot(t, c)

plot(t, support)

plot(t, resistance)

show()

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末纺且,一起剝皮案震驚了整個(gè)濱河市洗鸵,隨后出現(xiàn)的幾起案子峭梳,更是在濱河造成了極大的恐慌酪捡,老刑警劉巖,帶你破解...
    沈念sama閱讀 217,542評(píng)論 6 504
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件侨把,死亡現(xiàn)場(chǎng)離奇詭異窗看,居然都是意外死亡,警方通過(guò)查閱死者的電腦和手機(jī)荒给,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,822評(píng)論 3 394
  • 文/潘曉璐 我一進(jìn)店門(mén)丈挟,熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái),“玉大人志电,你說(shuō)我怎么就攤上這事曙咽。” “怎么了挑辆?”我有些...
    開(kāi)封第一講書(shū)人閱讀 163,912評(píng)論 0 354
  • 文/不壞的土叔 我叫張陵例朱,是天一觀的道長(zhǎng)。 經(jīng)常有香客問(wèn)我鱼蝉,道長(zhǎng)洒嗤,這世上最難降的妖魔是什么? 我笑而不...
    開(kāi)封第一講書(shū)人閱讀 58,449評(píng)論 1 293
  • 正文 為了忘掉前任魁亦,我火速辦了婚禮渔隶,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘洁奈。我一直安慰自己间唉,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,500評(píng)論 6 392
  • 文/花漫 我一把揭開(kāi)白布利术。 她就那樣靜靜地躺著呈野,像睡著了一般。 火紅的嫁衣襯著肌膚如雪印叁。 梳的紋絲不亂的頭發(fā)上被冒,一...
    開(kāi)封第一講書(shū)人閱讀 51,370評(píng)論 1 302
  • 那天军掂,我揣著相機(jī)與錄音,去河邊找鬼姆打。 笑死良姆,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的幔戏。 我是一名探鬼主播玛追,決...
    沈念sama閱讀 40,193評(píng)論 3 418
  • 文/蒼蘭香墨 我猛地睜開(kāi)眼,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼闲延!你這毒婦竟也來(lái)了痊剖?” 一聲冷哼從身側(cè)響起,我...
    開(kāi)封第一講書(shū)人閱讀 39,074評(píng)論 0 276
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤垒玲,失蹤者是張志新(化名)和其女友劉穎陆馁,沒(méi)想到半個(gè)月后,有當(dāng)?shù)厝嗽跇?shù)林里發(fā)現(xiàn)了一具尸體合愈,經(jīng)...
    沈念sama閱讀 45,505評(píng)論 1 314
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡叮贩,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,722評(píng)論 3 335
  • 正文 我和宋清朗相戀三年,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了佛析。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片益老。...
    茶點(diǎn)故事閱讀 39,841評(píng)論 1 348
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡,死狀恐怖寸莫,靈堂內(nèi)的尸體忽然破棺而出捺萌,到底是詐尸還是另有隱情,我是刑警寧澤膘茎,帶...
    沈念sama閱讀 35,569評(píng)論 5 345
  • 正文 年R本政府宣布桃纯,位于F島的核電站,受9級(jí)特大地震影響披坏,放射性物質(zhì)發(fā)生泄漏态坦。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,168評(píng)論 3 328
  • 文/蒙蒙 一刮萌、第九天 我趴在偏房一處隱蔽的房頂上張望驮配。 院中可真熱鬧,春花似錦着茸、人聲如沸。這莊子的主人今日做“春日...
    開(kāi)封第一講書(shū)人閱讀 31,783評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)。三九已至灰殴,卻和暖如春敬特,著一層夾襖步出監(jiān)牢的瞬間掰邢,已是汗流浹背。 一陣腳步聲響...
    開(kāi)封第一講書(shū)人閱讀 32,918評(píng)論 1 269
  • 我被黑心中介騙來(lái)泰國(guó)打工伟阔, 沒(méi)想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留辣之,地道東北人。 一個(gè)月前我還...
    沈念sama閱讀 47,962評(píng)論 2 370
  • 正文 我出身青樓皱炉,卻偏偏與公主長(zhǎng)得像怀估,于是被迫代替她去往敵國(guó)和親。 傳聞我的和親對(duì)象是個(gè)殘疾皇子合搅,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,781評(píng)論 2 354

推薦閱讀更多精彩內(nèi)容