Trading Signal: Moving Average

I have a problem with the section 7 unit 5 of the Momentum Trading Strategies Course. I'm coding the trading signal using a moving average and I'm doing an error defining the portfolio. Do you know where am I doing wrong?


5. TRADING SIGNAL MOVING AVERAGE 

#Moving average: Calculate the 10 days simple moving average of the portfolio value.

#Trading signal: Set the signal as 1 when the portfolio value is more than the simple moving average. If this condition is not satisfied, the signal will return 0, which means no position. If we are already long, then 0 would imply an exit.

#Strategy returns: Multiply the strategy returns with portfolio returns.



import numpy as np

import matplotlib.pyplot as plt

%matplotlib inline

plt.style.use('seaborn-darkgrid')

import pandas as pd



def get_strategy_returns_sma(portfolio):

    # Calculate the simple moving average of period 10

    portfolio['sma10'] = portfolio.value.rolling(window=10).mean()

    # Create a trading signal

    portfolio['signal'] = np.where(portfolio.value > portfolio.sma10,1,0)

    # Calculate the strategy returns

    portfolio['str_returns'] = portfolio['returns'].shift(-1) * portfolio['signal']

    return portfolio



def plot_signal(portfolio):

    portfolio['value'].plot(color='blue')    

    plt.fill_between(portfolio.index, portfolio.value, where=(portfolio.signal==1), facecolor='g', alpha=0.2)      

    plt.legend()

    plt.ylabel('Portfolio Value',color='r')

    # Plot the signal values    

    portfolio['signal'].plot(secondary_y=True,figsize=(15,10),color='grey', linestyle='dotted')

    plt.ylabel('Signal',color='r')

    plt.show()



portfolio = get_strategy_returns_sma(portfolio)    

plot_signal(portfolio)

---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-18-2a3c04e28417> in <module>
     29     plt.show()
     30 
---> 31 portfolio = get_strategy_returns_sma(portfolio)
     32 plot_signal(portfolio)
     33 

NameError: name 'portfolio' is not defined

Hi Giacomo Minotti,

You need to define the portfolio dataframe first, then only you can use it in your code.

So, I suggest running the jupyter notebook from the first code cell to the last cell sequentially.

It will solve your problem.

I have attached the code below where the portfolio has been defined that you can find in section 7, unit 5 of the Momentum Trading Strategies.

# Retrieve data in stock_list from 2019 January onwards
stock_data = data.loc['2019-1':,top_decile.index]
# Calculate the daily percentage change of prices
stock_data_pc = stock_data.pct_change()
# Create a new dataframe called portfolio
portfolio = pd.DataFrame()
# Calculate the average returns of stocks
portfolio['returns'] = stock_data_pc.mean(axis=1)
# Calculate cumulative returns of portfolio
portfolio['value'] = (portfolio+1).cumprod()
# Drop any rows with nan values
portfolio = portfolio.dropna()
portfolio.value.plot(color='b',figsize=(10,7))
plt.ylabel("Portfolio value")
plt.show()

Hope it helps.