# Python function to Matlab

25 ビュー (過去 30 日間)
david crowley 2021 年 4 月 27 日

I have the following moving average function developed in Python3 that I need to convert into MATLAB. However, I can't seem to find the correct syntax.
#defines the moving average function
def ma(df, window_size):
return df.groupby('ticker')['close'].apply(lambda x:x.rolling(center=False,window=window_size).mean())
#defines the periods for the moving average calculations
def ma_periods(df, months):
for month in months:
df['{}mo_ma'.format(month)] = ma(monthly_raw_data, month)
return df
#specify the moving average periods to calculate
periods = ma_periods(monthly_raw_data, [6,9,12])

サインインしてコメントする。

### 回答 (4 件)

Anagha Mittal 2021 年 6 月 17 日
MATLAB provides an inbuilt function called 'movavg' for calculating the moving average of any data.
Here is the documentation for reference: https://www.mathworks.com/help/finance/movavg.html
##### 0 件のコメント表示非表示 -1 件の古いコメント

サインインしてコメントする。

Akanksha Shrimal 2022 年 4 月 26 日
Hi,
It is my understanding that you want to compute the moving average in MATLAB similar to Python3 ‘rolling’ function.
The ‘movavg’ function of MATLAB computes the moving average.
Please refer to this documentation for more detail.
Hope this helps.
##### 0 件のコメント表示非表示 -1 件の古いコメント

サインインしてコメントする。

Steven Lord 2022 年 4 月 26 日
As @Anagha Mittal and @Akanksha Shrimal have stated there is a function in Financial Toolbox called movavg.
However I'd recommend instead using the movmean function included in MATLAB.
Alternately if you don't want to use movmean and don't want to convert your Python code to MATLAB code you can still use MATLAB. See this category of the documentation for information about how to directly call Python from within MATLAB.
##### 0 件のコメント表示非表示 -1 件の古いコメント

サインインしてコメントする。

Al Danial 2022 年 5 月 4 日
Looks like monthly_raw_data is a Pandas dataframe. Can you post a small input file (.csv or other) that loads into a representative dataframe? I want to give @Steven Lord's alternate suggestion a try and write the MATLAB/Python interface. Even if a hybrid MATLAB/Python implementation is not your desired final solution, it can prove valuable as a reference solution for your ultimate MATLAB-only implementation.

サインインしてコメントする。

### カテゴリ

Find more on Call Python from MATLAB in Help Center and File Exchange

### Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by