python - 如何在 Python 中使用类变量作为方法的默认参数?
问题描述
我正在尝试将类变量Stock.today
用作方法的默认参数buy_and_hold
,但是,我的代码不起作用。类变量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,然后在函数体中分配您实际想要的值:
def buy_and_hold(self,frequency,start,end=None,yfbenchticker='^SPX'):
if end is None:
end = Stock.today
但是,正如 Mark Ransom 评论的那样,您应该能够使用end=today
.
推荐阅读
- python - 作为行级函数的参数传递的 pandas 数据框列,以将列的每个值应用于其各自的行
- three.js - 字符导向ThreeJS
- python - Python,使用多线程退出带有用户输入的 While 循环(cntrl+c 不起作用)
- python - 计算并保存具有日期的列之间的差异
- node.js - 如何从 LoopBack 模型文件生成 ERD
- c++ - 创建具有独特功能但数据类型相同的对象
- oracle - 杀死 dba_jobs_running 中的 oracle 作业
- twitter-bootstrap - Bootstrap 3 modal 从页脚开始,就像 Badoo 上的一样
- sql - 识别具有相同 ID 的列
- sql - 使用 SQL 查询的 Oracle SQL 开发人员的数据源名称