【问题标题】:Writing a function编写函数
【发布时间】:2018-06-20 08:17:39
【问题描述】:

所以我编写了一个运行良好的程序。它根据股票代码从网站中提取股票数据,然后根据我想要的行和列将其放入 Excel 电子表格中。我希望能够对多只股票进行此操作,但是我不知道如何编写函数。所以,我一直在做的是一遍又一遍地复制和粘贴代码。我的代码中唯一改变的参数是代码和标记为 r、x 和 y 的行号。有人可以帮我为我的程序编写一个函数吗?

fd = gm.FinancialsDownloader()
fd_frames = fd.download('AAPL')
wb = UpdateWorkbook(r'C:\Users\vince\Project\Stock Python Project\Spreadsheet.xlsx', worksheet=1)
i_s = fd_frames['income_statement']
i_s.set_index('title', inplace=True)
i_s = i_s.drop('parent_index', axis=1)
i_s = i_s.loc[['Revenue','Operating expenses']] #Add all the names you want from income statement
i_s = i_s/(10**9)

b_s = fd_frames['balance_sheet']
b_s.set_index('title', inplace=True)
b_s = b_s.drop('parent_index', axis=1)
b_s = b_s.loc[['Assets','Current assets']]
b_s = b_s/(10**9)

c_f = fd_frames['cash_flow']
c_f.set_index('title', inplace=True)
c_f = c_f.drop('parent_index', axis=1)
c_f = c_f.loc[['Free Cash Flow','Operating cash flow']]
c_f = c_f/(10**9)

r = 6  # starts at whatever row
c = 13 # column 'M'
for l in i_s.values.tolist():
    for item in l:
        wb.ws.cell(row=r, column=c).value = item
        c += 1 # Column 'N'
    c = 13
    r += 1

x = 21   
for l in b_s.values.tolist():
    for item in l:
        wb.ws.cell(row=x, column=c).value = item
        c += 1 # Column 'N'
    c = 13
    x += 1

y = 41
for l in c_f.values.tolist():
    for item in l:
        wb.ws.cell(row=y, column=c).value = item
        c += 1 # Column 'N'
    c = 13
    y += 1
wb.save()

【问题讨论】:

    标签: excel function user-defined-functions


    【解决方案1】:

    你可以用纯javascript制作一个函数,比如

    function demo(var1,var2,var3,var4){
    
        // custom code and calculation here 
    
    }
    
        //In your case you can use above function like this
    
    function getFinancialData(ticker,r,x,y){
    // your above calculation here
    }
    
      // call the getFinancialData and pass the dynamic value of ticker, r,x and y
    
       getFinancialData(ticker,r,x,y);
    

    【讨论】:

    • 感谢您的评论,这在 Python 中很难实现吗?
    • 对于 python 只使用 def 而不是函数
    • 所以我尝试了,但我一直收到名称错误。它告诉我 NameError: name 'AAPL' is not defined。苹果是我试图通过的股票代码
    • stackoverflow.com/questions/21122540/…>
    • 是的,我尝试引用该问题来修复错误,但它似乎不起作用。我仍然得到同样的错误。感谢您的洞察力
    猜你喜欢
    • 2021-12-04
    • 2017-02-02
    • 2021-03-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-14
    • 2011-12-27
    相关资源
    最近更新 更多