我遇到无法修复的错误,将在下面显示。而且,经过优化的代码足以被视为专业的编码器吗?
我正在尝试编写一个可以在整个项目中回顾的类。
__init__()
块进行编码的参考,而没有提及数据源,但稍后会引用它吗? get_sd()
?似乎缺少end参数,但它在那里。 这是我的代码:
import pandas as pd
import requests
from bs4 import BeautifulSoup
import datetime as dt
import matplotlib.pyplot as plt
from pandas_datareader import data as pdr
import fix_yahoo_finance as yf
import numpy as np
import math
yf.pdr_override()
class Ret:
def __init__(self, ticker, start, end):
data = yf.download(ticker, start, end, actions=True)
self.returns = data["Return"] = (data["Close"] - data["Close"].shift(1)) / data["Close"].shift(1)
self.CumRet = data["CumRet"] = data["Return"].cumsum()
self.RetDiv = data["RetDiv"] = (returns + data["Dividends"] / data["Close"])
self.CumRetDiv = data["CumRetDiv"] = data["RetDiv"].cumsum()
def get_sd(self, ticker, start, end):
return self.returns
stocks = ["MMM",]
start = "2006-01-01"
# input("Enter start year") +
end = dt.date.today()
Ret.get_sd("AAPL", start, end)
print(aapl)
这是我得到的错误:
Traceback (most recent call last):
File "C:/Users/ruleb/Desktop/python test/Ptf_Project/Get_data_prices.py", line 51, in <module>
Ret.get_sd("AAPL", start, end)
TypeError: get_sd() missing 1 required positional argument: 'end'
Process finished with exit code 1
编辑,我试图进行如下修改:
stocks = ["MMM"]
start = "2008-01-01"
end = dt.date.today()
class Ret:
def __init__(self, ticker, start, end):
return
def get_sd(self):
return np.std(self.Returns)
def get_data(self):
data = yf.download(ticker, start, end, actions=True)
self.Returns = data["Return"] = (data["Close"] - data["Close"].shift(1)) / data["Close"].shift(1)
self.CumRet = data["CumRet"] = data["Return"].cumsum()
self.RetDiv = data["RetDiv"] = (data["Return"] + data["Dividends"] / data["Close"])
self.CumRetDiv = data["CumRetDiv"] = data["RetDiv"].cumsum()
return data
myRet = Ret(stocks,start,end)
myData = myRet.get_data
print(myData)
但是我明白了:
<bound method Ret.get_data of <__main__.Ret object at 0x031ED310>>
答案 0 :(得分:0)
在问题的编辑版本中查看代码,您需要调用方法:将myRet.get_data
更改为myRet.get_data()
。
class Ret:
def __init__(self):
# it is a good practice to initialize the attributes
# in '__init__()', even if you are going to use them later
self.Returns = None
self.CumRet = None
self.RetDiv = None
self.CumRetDiv = None
def get_sd(self):
return np.std(self.Returns)
def get_data(self):
data = yf.download(ticker, start, end, actions=True)
self.Returns = data["Return"] = (data["Close"] - data["Close"].shift(1)) / data["Close"].shift(1)
self.CumRet = data["CumRet"] = data["Return"].cumsum()
self.RetDiv = data["RetDiv"] = (data["Return"] + data["Dividends"] / data["Close"])
self.CumRetDiv = data["CumRetDiv"] = data["RetDiv"].cumsum()
return data
myRet = Ret(stocks, start, end)
myData = myRet.get_data()
print(myData)