想法是创建一个股票分析图表。当我尝试在pandas数据框中创建“中间”列时,我收到错误。我希望该列包含开盘价和收盘价的平均值。数据源为iex
源代码:
from pandas_datareader import data
import pandas
import datetime
start=datetime.datetime(2018,4,1)
end=datetime.datetime(2018,4,12)
df=data.DataReader(name="AAPL",data_source="iex",start=start,end=end)
def inc_dec (c,o):
if c>o:
value="Increase"
elif c<o:
value="Decrease"
else:
value ="Equal"
return value
df["status"]=[inc_dec(c,o) for c,o in zip(df.close,df.open)]
df["Middle"]=[(df.open+df.close)/2,2]
p=figure(plot_width=1000,plot_height=500,x_axis_type='datetime')
p.title.text="Cadlesticks Chart"
p.xaxis.axis_label="TIME"
hours=60*60*100
p.rect(df.index[df.status=="Decrease"],(df.open+df.close)/2,hours,abs(df.open-df.close),
fill_color="Red",line_color="black")
p.rect(df.index[df.status=="Increase"],round((df.open+df.close)/2,2),hours,abs(df.open-df.close),
fill_color="green",line_color="black")
p.rect(df.index[df.status=="Equal"],round((df.open+df.close)/2,2),hours,abs(df.open-df.close),
fill_color="green",line_color="black")
output_file("Stock_analysis.html")
show(p)
输出和错误:
1y
---------------------------------------------------------------------------
ValueError:值的长度与索引的长度
不匹配答案 0 :(得分:2)
尝试此代码:您应该导入numpy并只复制df ['Middle']代码。
from pandas_datareader import data
import numpy as np
import pandas
import datetime
start=datetime.datetime(2018,4,1)
end=datetime.datetime(2018,4,12)
df=data.DataReader(name="AAPL",data_source="iex",start=start,end=end)
def inc_dec (c,o):
if c>o:
value="Increase"
elif c<o:
value="Decrease"
else:
value ="Equal"
return value
df["status"]=[inc_dec(c,o) for c,o in zip(df.close,df.open)]
df["Middle"]=round(np.mean(df.open+df.close), 2)