Python 金融时间序列matplotlib图的嵌套循环

Python 金融时间序列matplotlib图的嵌套循环,python,matplotlib,Python,Matplotlib,在学习python和matplotlib时,我正在尝试打印所选代码的图形。我已经写了下面的代码,它工作得很好,除了打印整个股票代码列表的图例,我理解它为什么这样做,但我不明白如何让它只打印与该图相关的股票代码。 我还觉得,作为一个初学者,我可能写了太多的代码行,如果有人能指导我如何减少这些代码,这将帮助我学习正确的方法 #!/usr/bin/env python3 import numpy as np import datetime import pandas as pd import pand

在学习python和matplotlib时,我正在尝试打印所选代码的图形。我已经写了下面的代码,它工作得很好,除了打印整个股票代码列表的图例,我理解它为什么这样做,但我不明白如何让它只打印与该图相关的股票代码。 我还觉得,作为一个初学者,我可能写了太多的代码行,如果有人能指导我如何减少这些代码,这将帮助我学习正确的方法

#!/usr/bin/env python3
import numpy as np
import datetime
import pandas as pd
import pandas.io.data
from pandas import Series, DataFrame

import matplotlib.pyplot as plt
import matplotlib as mpl

tickers=["ADBE","AAPL","GME","SNDK"]
roll_pd=30
num_std=2
flist=[]
ts_cutoff_days=-220
flag=1
start=datetime.datetime(2008,7,1)
end=datetime.date.today()

for ticker in tickers:
    time_srs=pd.io.data.get_data_yahoo(ticker,start,end)
    #time_srs.head()
    fname=ticker+"_ohlc.csv"
    print (fname)
    time_srs.to_csv(fname) 
    flist.append(fname)

for fn in flist:
    #print(fn)
    df=pd.read_csv(fn,index_col='Date',parse_dates=True)
    df.head()
    df.index
    close_px=df['Adj Close']
    ts=df['Adj Close'][ts_cutoff_days:]
    if flag==0:
        px_srs=close_px
    else:
        px_srs=ts

    mavg=pd.rolling_mean(px_srs,roll_pd)
    mstd=pd.rolling_std(px_srs,roll_pd)

    rets=px_srs / px_srs.shift(1) - 1
    rets.head()


    plt.figure()
    plt.plot(px_srs.index, px_srs,color='k',label=tickers)# this is where I am making the error
    plt.plot(mavg.index, mavg,label='mavg',color='red')
    plt.fill_between(mstd.index,mavg-num_std*mstd,mavg+num_std*mstd,color='b',alpha=0.2)
    plt.legend(loc='best')
    plt.axes().yaxis.grid(True)
    plt.show()

if flag==0:
    df1 = pd.io.data.get_data_yahoo(tickers,start, end)['Adj Close']
else:
    df1 = pd.io.data.get_data_yahoo(tickers,start, end)['Adj Close'][ts_cutoff_days:]# I tried writing [ts] instead of ['Adj Close'][ts_cutoff_days:], but it gave me an error, so I had to write this above if-else condition to create df1 correctly

我认为你应该扔掉你的
flist
,因为所有的信息都已经在
股票中了。。然后你可以做:

...

for ticker in tickers:
    df=pd.read_csv(ticker + 'ohlc.csv',index_col='Date',parse_dates=True)
    ...
    plt.plot(px_srs.index, px_srs,color='k',label=ticker)
如果您担心更改文件名,那么您可以为此创建一个简单的函数,并在读取和写入文件时使用它

另一种可能是在flist中放入一个元组:

for ticker in tickers:
    ...
    flist.append((ticker, fname))
然后在下一个循环中使用此元组:

for ticker, fn in flist:
    ...

这还允许您使用
ticker
作为绘图标签。

我认为您需要设置plt.title而不是标签:

plt.title = ticker

好吧,我想更改标签,而不是标题。我担心上面显示的
flist.append
不起作用,我收到一个错误。它对您有效吗?@user3766123:应该有效,因为它只是在
flist
中添加一个元组(ticker,fname)。这一行应该替换原始代码中的行
flist.append(fname)
(即在上面的循环中)。如果您仍然收到错误消息,请告诉哪一条和哪一行。确保括号正确。修复了这个问题。有没有关于减少代码数量的建议lines@User3766123:在python中,减少代码行数不是目标:)快速浏览一下代码,我有两个问题:您真的需要CSV文件吗(如果不创建CSV文件,如果需要,重新加载刚刚保存的数据效率很低)?为什么有两个for循环遍历相同的数据?(如果您在代码中定义了函数,这是有意义的。)有很多风格上的微妙之处,但是您可能会通过使用代码检查得到最好的答案:不,您的代码还不错。谢谢您的反馈。我会试着把它修好。我不知道有一个codereview站点,我肯定会使用它