首页 > 解决方案 > 如何在 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")

标签: pythonclassmethods

解决方案


解决此问题的一种方法是使用默认值 None,然后在函数体中分配您实际想要的值:

def buy_and_hold(self,frequency,start,end=None,yfbenchticker='^SPX'):
    if end is None:
        end = Stock.today

但是,正如 Mark Ransom 评论的那样,您应该能够使用end=today.


推荐阅读