首先让我说 Python 的 ggplot 是一个伟大的开始,并感谢开发人员投入的工作。目前我在同一个情节上有两个主要问题。如果我绘制 8 只或更少的股票,图像看起来不错,只是图例超出了图形区域(问题 1)。如果我绘制超过 8 只股票,则该图会触发一些明显不代表数据的不稳定线。此外,图例不会调整大小,而是省略了额外的股票代码(问题 2)。任何帮助表示赞赏。谢谢!
体面的情节代码:
import datetime
from ggplot import *
import pandas.io.data as web
import pandas as pd
import numpy as np
start = datetime.datetime(2014,1,1)
end = datetime.datetime(2014, 3,19)
stocks = ['APO','AVG','FI','ANIK','CELG','PACW','CBOE','BIIB']
stockData = {}
for ticker in stocks:
stockData[ticker] = web.get_data_yahoo(ticker, start, end)
price = pd.DataFrame({tic: data['Adj Close'] for tic, data in stockData.iteritems()})
returns = price.pct_change()
returns = returns.apply(cumsum)
rt = returns.index
returns['Date'] = rt
# plotting the cum performance for each security
ret = pd.melt(returns, id_vars='Date')
plot = ggplot(aes(x='Date', y='value', color='variable'),data=ret) +geom_line()
# plotting the equity curve of the theoretical portfolio
zt = returns
del zt['Date']
zt = zt.apply(np.sum, axis=1)
z = pd.DataFrame(zt, index=zt.index)
z['Date'] = rt
z.columns = ['equity curve', 'Date']
ret2 = pd.melt(z, id_vars='Date')
plot2 = ggplot(aes(x='Date', y='value'),data=ret2) +geom_line()
print plot
print plot2
错误的情节代码:
import datetime
from ggplot import *
import pandas.io.data as web
import pandas as pd
import numpy as np
start = datetime.datetime(2014,1,1)
end = datetime.datetime(2014, 3,19)
stocks = ['APO','AVG','FI','ANIK','CELG','PACW','CBOE','BIIB','ISIS', 'SDRL'] # <-- notice two additional tickers
stockData = {}
for ticker in stocks:
stockData[ticker] = web.get_data_yahoo(ticker, start, end)
price = pd.DataFrame({tic: data['Adj Close'] for tic, data in stockData.iteritems()})
returns = price.pct_change()
returns = returns.apply(cumsum)
rt = returns.index
returns['Date'] = rt
# plotting the cum performance for each security
ret = pd.melt(returns, id_vars='Date')
plot = ggplot(aes(x='Date', y='value', color='variable'),data=ret) +geom_line()
# plotting the equity curve of the theoretical portfolio
zt = returns
del zt['Date']
zt = zt.apply(np.sum, axis=1)
z = pd.DataFrame(zt, index=zt.index)
z['Date'] = rt
z.columns = ['equity curve', 'Date']
ret2 = pd.melt(z, id_vars='Date')
plot2 = ggplot(aes(x='Date', y='value'),data=ret2) +geom_line()
print plot
print plot2