应小编的要求,写了个返回股票在某时间段涨跌幅的函数
涨跌幅函数为rangeChange(stockSymbol, startDate, endDate)
年化收益函数为annualizedReturn(stockSymbol, startDate, endDate)
这个代码已经很简化了,功能强大。你要说再加啥功能,我也不知道加啥了。小编一定要让我多写一点,无语
from jqdatasdk import *
import pandas as pd
from datetime import datetime, timedelta # 导入datetime模块
auth('username','code') #输入用户名密码
def rangeChange(stockSymbol, startDate, endDate):
#返回区间内股票的收益率
df = get_price(stockSymbol, start_date=startDate, end_date=endDate, frequency='daily', fields=['pre_close',"close"],skip_paused=False, fq='pre')
startDateF=datetime.strptime(startDate, "%Y-%m-%d")
if df.index[0]==startDateF:
#如果初始日为交易日,取该交易日的收盘价
startPrice=df.ix[0,1]
else:
#如果初始日为非交易日,取之前最近交易日的收盘价
startPrice=df.ix[0,0]
endPrice=df.ix[-1,1]
return endPrice/startPrice-1
def annualizedReturn(stockSymbol, startDate, endDate):
performance=rangeChange(stockSymbol, startDate, endDate)
startDateF=datetime.strptime(startDate, "%Y-%m-%d")
endDateF=datetime.strptime(endDate, "%Y-%m-%d")
calDays=(endDateF-startDateF).days
annualReturn=(1 performance)**(1/(calDays/365))-1
return annualReturn
#############
#用户输入
startDate="2015-01-01"#输入初始日
endDate="2018-02-01" #输入到期日
stockSymbol='000001.XSHE' #输入股票代码
##############
performance=rangeChange(stockSymbol, startDate, endDate)
print(performance)
annualReturn=annualizedReturn(stockSymbol, startDate, endDate)
print(annualReturn)