鱼C论坛

 找回密码
 立即注册
查看: 2983|回复: 1

函数问题

[复制链接]
发表于 2022-12-17 21:48:18 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
请 根据模板要求,使用 python、numpy、scipy 和 pandas 完成下列函数的定义,给出函
数的说明和注释,并在 if __name__=”__main__”:下给出实例进行测试和验证,给出函数测试
的曲线图。
要求,根据数学定义和公式计算,定义下列函数的参数、代码实现和返回值。


WMA Weighted Moving Average
函数参考格式:WMA(close, timeperiod=30)
模板如下,但是我只写了一点点,实在写不下去了,代码有点乱。

求求有人帮我一下,实在没看懂,跟我提供一下思路也行
  1. ########################################################################
  2. #
  3. # Functions for calculating Total Return, Annualized Returns, etc.
  4. #
  5. ########################################################################
  6. #
  7. # This file is part of Big data Analysis with Python Course:
  8. #
  9. # Published under the UIBE License. See the file LICENSE for details.
  10. #
  11. # Copyright 2022 by San Zhang
  12. ########################################################################

  13. import numpy as np
  14. import pandas as pd
  15. from numba import jit
  16. import data
  17. from data_keys import *

  18. ########################################################################
  19. # Constants.

  20. # Average number of days in a year. Normal years have 365 days,
  21. # but every 4th year is a leap-year with 366 days.
  22. DAYS_PER_YEAR = 365.25

  23. # Average number of business- or trading-days in a year.
  24. BDAYS_PER_YEAR = 251.67

  25. ########################################################################
  26. # Public functions.
  27. #函数介绍:WMA函数:以不同权重对股价赋予一定的权重再相加
  28. #用dataframe创建过去35天的股票价格记录

  29. data={"日期":pd.Series(range(1,35))}
  30. share_data = pd.DataFrame(data)
  31. def WMA(close, timeperiod=30):
  32.     #设置权重
  33.     weights = np.array(range(1, n + 1))

  34.     sum_weights = np.sum(weights)
  35.     weight1 = weights/sum_weights
  36.     # 公式计算:以日期从新到旧权重依次下降,且所选数据权重和为1,分别乘上当期收盘股票价格来预测下期股票价格


  37.     Total_Return[t] = Total_Return[t - 1] * (Dividend[t] + Share_Price[t]) / Share_Price[t - 1]
  38.     res = close.rolling(window=n).apply(lambda x: np.sum(weights * x) / sum_weights, raw=False)
  39.     return res



  40. def total_return(df):
  41.     """
  42.     Calculate the "Total Return" of a stock when dividends are
  43.     reinvested in the stock.

  44.     The formula is:

  45.     Total_Return[t] = Total_Return[t-1] * (Dividend[t] + Share_Price[t]) / Share_Price[t-1]

  46.     :param df:
  47.         Pandas data-frame assumed to contain SHARE_PRICE and DIVIDEND.
  48.     :return:
  49.         Pandas series with the Total Return.
  50.     """

  51.     # Copy the relevant data so we don't change it.
  52.     df2 = df[[SHARE_PRICE, DIVIDEND]].copy()

  53.     # Fill NA-values in the Dividend-column with zeros.
  54.     df2[DIVIDEND].fillna(0, inplace=True)

  55.     # Calculate the daily Total Return.
  56.     tot_ret_daily = (df2[DIVIDEND] + df2[SHARE_PRICE]) / df2[SHARE_PRICE].shift(1)

  57.     # Calculate the cumulative Total Return.
  58.     tot_ret = tot_ret_daily.cumprod()

  59.     # Replace the first row's NA with 1.0
  60.     tot_ret.iloc[0] = 1.0

  61.     return tot_ret


  62. def annualized_returns(series, years):
  63.     """
  64.     Calculate the annualized returns for all possible
  65.     periods of the given number of years.

  66.     For example, given the Total Return of a stock we want
  67.     to know the annualized returns of all holding-periods
  68.     of 10 years.

  69.     :param series:
  70.         Pandas series e.g. with the Total Return of a stock.
  71.         Assumed to be daily data.
  72.     :param years:
  73.         Number of years in each period.
  74.     :return:
  75.         Pandas series of same length as the input series. Each
  76.         day has the annualized return of the period starting
  77.         that day and for the given number of years. The end of
  78.         the series has NA for the given number of years.
  79.     """

  80.     # Number of days to shift data. All years have 365 days
  81.     # except leap-years which have 366 and occur every 4th year.
  82.     # So on average a year has 365.25 days.
  83.     days = int(years * 365.25)

  84.     # Calculate annualized returns for all periods of this length.
  85.     # Note: It is important we have daily (interpolated) data,
  86.     # otherwise the series.shift(365) would shift much more than
  87.     # a year, if the data only contains e.g. 250 days per year.
  88.     ann_return = (series.shift(-days) / series) ** (1 / years) - 1.0

  89.     return ann_return


  90. def prepare_ann_returns(df, years, key=PSALES, subtract=None):
  91.     """
  92.     Prepare annualized returns e.g. for making a scatter-plot.
  93.     The x-axis is given by the key (e.g. PSALES) and the y-axis
  94.     would be the annualized returns.

  95.     :param df:
  96.         Pandas DataFrame with columns named key and TOTAL_RETURN.
  97.     :param years:
  98.         Number of years for annualized returns.
  99.     :param key:
  100.         Name of the data-column for x-axis e.g. PSALES or PBOOK.
  101.     :param subtract:
  102.         Pandas Series to be subtracted from ann-returns
  103.         to adjust for e.g. growth in sales-per-share.
  104.     :return:
  105.         (x, y) Pandas Series with key and adjusted ANN_RETURN.
  106.     """

  107.     # Create a new data-frame so we don't modify the original.
  108.     # We basically just use this to sync the data we are
  109.     # interested in for the common dates and avoid NA-data.
  110.     df2 = pd.DataFrame()

  111.     # Copy the key-data e.g. PSALES.
  112.     df2[key] = df[key]

  113.     # Calculate all annualized returns for all periods of
  114.     # the given number of years using the Total Return.
  115.     ann_return = annualized_returns(series=df[TOTAL_RETURN], years=years)

  116.     if subtract is None:
  117.         # Add the ann-returns to the new data-frame.
  118.         df2[ANN_RETURN] = ann_return
  119.     else:
  120.         # Calculate all annualized returns for the series
  121.         # that must be subtracted e.g. sales-per-share.
  122.         ann_return_subtract = annualized_returns(series=subtract, years=years)

  123.         # Subtract the ann. returns for the total return
  124.         # and the adjustment (e.g. sales-per-share).
  125.         # Then add the result to the new data-frame.
  126.         df2[ANN_RETURN] = ann_return - ann_return_subtract

  127.     # Drop all rows with NA.
  128.     df2.dropna(axis=0, how='any', inplace=True)

  129.     # Retrieve the relevant data.
  130.     x = df2[key]
  131.     y = df2[ANN_RETURN]

  132.     return x, y


  133. if __name__ == "__main__":



复制代码
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

发表于 2023-2-16 17:05:37 | 显示全部楼层
1 if name=main这里没有调用主函数
2 python变量名支持中文,就算你用英文变量名也就算了,注释为什么要英文?
3 对程序、函数描述的注释用3双引号,也不应该用#啊
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2025-4-25 02:33

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表