![](/img/trans.png)
[英]How can I use a class instance variable as an argument for a method decorator in Python?
[英]How can I use a class variable in Python as a default argument for a method?
我正在尝试使用 class 变量Stock.today
作为方法buy_and_hold
的默认参数,但是,我的代码不起作用。 class 变量today
将今天的日期作为字符串返回。 如果我手动键入完全相同的字符串(即“2020-6-18”)作为默认参数,则代码有效。 如何使用Stock.today
使代码运行?
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import time
from datetime import datetime
import yfinance as yf
class Stock:
year = time.strftime('%Y')
month = time.strftime('%m').replace("0","")
day = time.strftime('%d').replace("0","")
today = Stock.year + '-' + Stock.month + '-' + Stock.day
def __init__(self,ticker):
self.ticker = ticker
# frequency as string # start and end are strings "Y-M-D" # Benchmark as string
def buy_and_hold(self,frequency,start,end=Stock.today,yfbenchticker='^SPX'):
sdate_list =[]
for date in start.split("-"):
sdate_list.append(int(date))
sdate = datetime(year=sdate_list[0],month=sdate_list[1],day=sdate_list[2])
edate_list = []
for date in end.split("-"):
edate_list.append(int(date))
edate = datetime(year=edate_list[0],month=edate_list[1],day=edate_list[2])
stock = yf.Ticker(self.ticker).history(interval=frequency,start=sdate,end=edate)
stock.drop(['Dividends','Stock Splits'],axis=1, inplace=True)
bench = yf.Ticker(yfbenchticker).history(interval=frequency,start=sdate,end=edate)
bench.drop(['Dividends','Stock Splits'],axis=1, inplace=True)
# Interpolate missing values
if stock.isnull().values.any() == True:
stock['Close'].fillna(value=stock['Close'].mean())
if bench.isnull().values.any() == True:
bench['Close'].fillna(value=stock['Close'].mean())
# Calculate cumulative returns
stock['Cumulative return'] = stock['Close'] / stock['Close'].iloc[0]
bench['Cumulative return'] = bench['Close'] / bench['Close'].iloc[0]
# Plot cumulative returns
stock['Cumulative return'].plot(color='#00008b',figsize=(16,8))
plt.plot(bench['Cumulative return'], color='#cd2b00')
plt.xlabel('Date')
plt.ylabel('Multiplier')
plt.legend((self.ticker,yfbenchticker),loc=0,prop={'size':10})
plt.show()
return bench
amd = Stock("AMD")
解决此问题的一种方法是使用默认值 None,然后在 function 正文中分配您实际需要的值:
def buy_and_hold(self,frequency,start,end=None,yfbenchticker='^SPX'):
if end is None:
end = Stock.today
但是,正如 Mark Ransom 评论的那样,您应该只能使用end=today
。
使用 self 而不是 Stock 并将初始化放在构造函数中
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.