Open kimo opened 1 month ago
I made a small change to your script to return the figure, as the last expression is what is saved and previewed in the sheets:
=
import yfinance as yf
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
stock_data = yf.download('AAPL', start='2020-01-01', end='2023-01-01')
stock_data['SMA_50'] = stock_data['Close'].rolling(window=50).mean()
stock_data['SMA_200'] = stock_data['Close'].rolling(window=200).mean()
stock_data['Signal'] = 0 # 0 means hold
stock_data.loc[stock_data.index[50:], 'Signal'] = np.where(stock_data['SMA_50'][50:] > stock_data['SMA_200'][50:], 1, 0)
stock_data['Position'] = stock_data['Signal'].diff() # Signal changes (buy/sell)
#print(stock_data[['Close', 'SMA_50', 'SMA_200', 'Signal', 'Position']].tail())
figure = plt.figure(figsize=(10, 5))
plt.plot(stock_data['Close'], label='AAPL Price', color='blue')
plt.plot(stock_data['SMA_50'], label='50-Day SMA', color='red')
plt.plot(stock_data['SMA_200'], label='200-Day SMA', color='green')
plt.title('Apple Price with SMA Crossover Strategy')
plt.legend()
figure
I also added "pyfinance" to the packages and reloaded the view.
Then the background worker did load PyOdide (in about 9s), at which time the figure was shown as an empty plot. Looking at the Developer Console, I did see an error (which is somehow escaping the error capturing logic that is built into PySheets).
Failed to get ticker 'AAPL' reason: 'PyScriptResponse' object has no attribute 'cookies'
That last one is an internal error in PySheets that is attempting to monkey path request
so that call work on PyScript, which it normally does not. And indeed, PyScriptResponse is currently missing a 'cookies' field.
Here is what I see in the Devtools Console
Here is the error(i think)
Below is the code.