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