numpy 学习笔记4

encoding=utf-8

利用numpy 进行历史股价分析

import numpy as np
import sys

读入文件

c, v = np.loadtxt(‘data.csv’, delimiter=’,’, usecols=(4, 6), unpack=True)
print ‘c=’, c
print ‘v=’, v

计算成交量加权平均价格

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

算术平局值函数

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

时间加权平均价格

t = np.arange(len(c))
print ‘t=’, t
print ” 加权平均价格: twap = “, np.average(c, weights=t)
print ‘test1’
h, l = np.loadtxt(‘data.csv’, delimiter=’,’, usecols=(4, 5), unpack=True)
print ‘h = ‘, h
print ‘l = ‘, l
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 ‘max-min=’, np.max(h) - np.min(h)
print ‘Spread low.price ‘, np.ptp(l)
print ‘max-min=’, np.max(l) - np.min(l)

统计分析

c = np.loadtxt(‘data.csv’, delimiter=’,’, usecols=(6,), unpack=True)
print ‘c=’, c

数据进行排序

sorted = np.msort(c)
print ‘c:sorted ‘, sorted

中间平均值的获取,如果是奇数,获取中间的那个数字,如果是偶数,最中间的两个数值取平均值

print ‘median = ‘, np.median(c)
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)
print ‘c=’, c
print ‘c[:-1]’, c[:-1]
print ‘np.diff(c):’, np.diff(c)
print ‘c[:-1]:’, c[:-1]
returns = np.diff(c) / c[:-1]
print ‘returns:’, returns

简单的收益率计算

print ‘standard deviatio = ‘, np.std(returns)

对数收益率

print ‘c=’, c
returns = np.diff(np.log(c))
print returns

查看历史波动率,需要用到对数波动率

posretindices = np.where(returns > 0)
logreturns = np.diff(np.log(c))
print ‘test1’

获取年化波动率

annual_volatility = np.std(logreturns) / np.mean(logreturns)
print ‘annual_volatility’, annual_volatility
annual_volatility = annual_volatility / np.sqrt(1. / 252.)
print “annual_volatility”, annual_volatility

获取月度交易率

print “Monthly valatility “, annual_volatility * np.sqrt(1. / 12.)
print ‘test’

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值