#encoding: utf8
import tushare as ts
import os
import csv
import time
import pandas as pd
import math
import numpy as np
from scipy.stats import norm
def sigma(code):
# 定义交易天数
n = 70
difflntotal = []
##定义时间
today = str(time.strftime('%Y-%m-%d', time.localtime(time.time())))
df = ts.get_k_data(code, start='2017-01-01', end=today, ktype='d')
for i in range(n):
# 前日收盘价
xclose = df.iloc[i - n - 1].close
# 昨日收盘价
yclose = df.iloc[i - n].close
# 计算对数
lnxclose = math.log(xclose, math.e)
lnyclose = math.log(yclose, math.e)
# 计算对数差并传入数组
diffln = lnyclose - lnxclose
difflntotal.append(diffln)
# print(xclose,yclose,lnxclose,lnyclose,diffln)
#print(difflntotal)
#昨日收盘价
yclose_default=df.iloc[-1].close
# 计算标准差
stdclose = np.std(difflntotal)
# 计算volitality
volitality = stdclose * 100 * math.sqrt(256)
#print(stdclose, volitality)
return yclose_default,volitality
#计算B-S定价公式
def bs(code,month,rate):
#计算volitality
sig=sigma(code)
vol=sig[1]/100
yclose=sig[0]
#定义默认值 s现股价格 k执行价格 t周期 r利率
s=100
k=100
t=month/12
r=rate
#计算B-S D1
#D1=(math.log(s/k,math.e)+(r+np.square(vol)/2)*t)/(vol*np.sqrt(t))
#计算B-S D2
#D2=D1-vol*np.sqrt(t)
#计算 询价
#call=s*norm.cdf(D1)-s*math.exp(-r*t)*norm.cdf(D2)
#计算 OUT价
#out=k*math.exp(-r*t)*norm.cdf(-D2)-s*norm.cdf(-D1)
#计算估价
#call_fix=call/1.13
#返回收盘价、波动率、1月报价、2月报价、3月报价
return yclose,vol
##上市3000家公司
list_csv=csv.reader(open('/usr/local/bin/csvtestlist.csv'))
##定义文件时间
todayformat=str(time.strftime('%Y%m%d',time.localtime(time.time())))
filename_20d='/usr/local/bin/stockvol'+todayformat+'.txt'
#每家公司最终结果
##计算每家公司的volitality
for row in list_csv:
#rowpub=row[0].zfill(6) 不足6位以0补齐
#print(rowpub)
#print(row)
try:
#输入股票code,周期month,利率10%~12%
bs_result = bs(row[0],1,0.12)
except:
default=0
row.append(bs_result[0])
row.append(default)
print(row)
else:
row.append(bs_result[0])
row.append(bs_result[1])
print(row)
#保存每条公司vol数据
out=open(filename_20d,'a')
#csv_write=csv.writer(out,dialect='excel')
#csv_write.writerow(row)
out.write('\n'+str(row))