程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Use pandas to efficiently handle monthly stock returns (the last day of each month is not fixed)

編輯:Python

Monthly yield

After inquiry , Monthly yield =( Closing price at the end of this month - The closing price at the end of last month )/ The closing price at the end of last month

Data sources

NetEase Finance - ZTE data , It is comprehensive and supports downloading historical data
http://quotes.money.163.com/trade/lsjysj_000063.html?year=1997&season=4

What's the problem ?

As month end data is required , But there are Spring Festival holidays and 2 The end of the month may not be 31 and 30 Number , Then there are more months and years , So take python To solve the problem ! According to the year - Group by month , Then return the first value of the group ( Month end data )

Code

""" author: wpc date: 2020-12-16 16:30 """
# Introduce modules 
import pandas as pd
import numpy as np
# Reading data , The encoding format is used wps. It helped me become GBK
df = pd.read_csv('data/zx.csv',encoding='GBK')
# Sequence processing , And become 1997-11 This format 
df.index = pd.to_datetime(df[' date '])
time_month = df.index.strftime('%Y-%m')
# Will be 1997-11 Format data 
df.index = time_month
df.groupby(df.index)
# call groupby Of first Method , Returns the first value . That is, the value at the end of the month 
data = df.groupby(df.index).first()
# export csv file 
data.to_csv('monthpro.csv',index=False,encoding='utf-8')
print(df)

And then you can use it Excel Make a simple formula and calculate it !!
Then I deleted what I didn't want , Then take a look at the export results !


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved