无法理解代码中vars()的作用

时间:2019-04-02 04:18:16

标签: python pandas algorithmic-trading

因此在代码中,我正在共享多个股票数据,这些数据已通过用户定义的功能下载,并且用户定义的功能以CSV格式存储数据 然后我们必须使用代码来计算一些统计数据,例如点击率,每日收益,交易总数以及其他一些不是问题的内容 问题出在以下代码中,讲师已使用vars()函数,似乎每个股票数据帧都存储在该vars()对象中,然后调用一些操作,如计算len中的值每个股票数据框都可以通过添加vars()来完成,并在每个数据框上进行操作,如果有人回答问题可以在下面的此特定代码中更详细地解释var()的作用,以及有什么作用,那将是很好的

我能够理解代码vars()不清楚

stocks = ['MSFT','IBM', 'GM', 'ACN', 'GOOG']
end=datetime.datetime.now().date() 
start=end-pd.Timedelta(days=365*5) # ONLY FIVE YEARS Of HISTORICAL DATA CAN BE DOWNLOADED FROM 'IEX'

def hist_data(stocks):
    stock_df=web.DataReader(stocks,'iex',start,end)
    stock_df['Name']=stocks
    fileName=stocks+'_data.csv'#this code is actually gaiving adding '_data.csv' to everay stock name in stocks varialble above.by this we will be able to write individual stock data downloaded to csv fromat 
    stock_df.to_csv(fileName) # writing individual stock data to csv format 

with futures.ThreadPoolExecutor(len(stocks)) as executor:
    result=executor.map(hist_data,stocks)
print('completed')

all_stats=[]

for stock in stocks:
    df = pd.read_csv(stock+'_data.csv',index_col=0)
    df.columns
    df['Daily returns'] = df['close'] /df['open'] -1
    vars()['df_'+stock] = df.copy()

    #Calculation of Loss and profit trades
    loss=np.where(vars()['df_'+stock]['Daily returns']<0)# so u see this code is first calling the data frame 'df_'+stock so a stock data is stored in it where we named each stock dataframe
    profit=np.where(vars()['df_'+stock]['Daily returns']>0)

    #Calculation of trade counts
    total_trades = len(vars()['df_' + stock]) # as we are taking a trade evry single day so we can count the lenght of dataframe 
    loss_trades = len(loss[0]) # [0] this argument is there because without this code would return zero 
    profit_trades = len(profit[0])

    #Calculation of hit ratios
    hit_ratio= profit_trades/(loss_trades + profit_trades)
    total_returns=np.cumsum(vars()['df_'+stock]['Daily returns'])    
    vars()['df_'+stock]['Cum Returns']=total_returns 

    stats=[stock,hit_ratio,total_returns[len(total_returns)-1]]
    all_stats.append(stats)
    headings=['Stock Name','Hit Ratio','Final Return']

    #Final Result of all the calculations
    final_result=pd.DataFrame(all_stats, columns=headings)

    plt.plot(vars()['df_'+stock].index.values,vars()['df_'+stock]['Cum Returns'],label=stock)
    plt.legend()

#results are as expected

1 个答案:

答案 0 :(得分:0)

使用vars()[variable]允许您使用变量来命名另一个变量。

通常,就可读性和可靠性而言,一种更好的方法是使用字典。