无法理解vars()在代码中的作用[重复]

问题描述 投票:0回答:1

这个问题在这里已有答案:

所以在代码中,我共享多个股票数据已经通过用户定义的函数下载,用户定义的函数以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
python pandas algorithmic-trading
1个回答
0
投票

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

通常,在可读性和可靠性方面,使用字典是一种非常优越的方法。

© www.soinside.com 2019 - 2024. All rights reserved.