I’m working on a Python script that uses the pandas library to manipulate data. However, I’m encountering an error that I can’t seem to resolve. Here’s the relevant part of my code:
import pandas as pd
# Create a dataframe to store the capital over time
capital_df = pd.DataFrame(columns=['time', 'capital'])
# Some code here...
# Append the current capital to the dataframe
capital_df = capital_df.append({'time': df.index[i], 'capital': capital}, ignore_index=True)
When I run this code, I get the following error:
Exception has occurred: AttributeError
'DataFrame' object has no attribute 'append'
This is strange because append
is a standard method for pandas DataFrame objects. I’ve checked and capital_df
is indeed a DataFrame when append
is called.
Here’s what I’ve tried so far to resolve this issue:
- Checked for any variable or function named
capital_df
that might be overwriting the DataFramecapital_df
. - Updated my pandas library using pip.
- Checked my pandas version to make sure it’s updated.
- Restarted my Python environment.
- Uninstalled and reinstalled pandas.
Despite these efforts, the issue persists.
Any help would be greatly appreciated. Thank you!
My full codes are attached below:
import pandas as pd
import matplotlib.pyplot as plt
import time
import requests
# Define the stock symbol and your API key
symbol = 'AAPL'
api_key = 'API'
# Define the initial capital
initial_capital = 10000
capital = initial_capital
# Create a dataframe to store the capital over time
capital_df = pd.DataFrame(columns=['time', 'capital'])
while True:
# Download minute-level data for the current trading day
url = f'https://www.alphavantage.co/query?function=TIME_SERIES_INTRADAY&symbol={symbol}&interval=1min&apikey={api_key}'
response = requests.get(url)
data = response.json()
df = pd.DataFrame(data['Time Series (1min)']).T
df = df.rename(columns={'1. open': 'Open', '2. high': 'High', '3. low': 'Low', '4. close': 'Close', '5. volume': 'Volume'})
df = df.astype(float)
# Calculate 20 day moving average and standard deviation
df['20_day_mean'] = df['Close'].rolling(window=20).mean()
df['20_day_std'] = df['Close'].rolling(window=20).std()
# Create signals based on the z-score
df['z_score'] = (df['Close'] - df['20_day_mean']) / df['20_day_std']
df['signals'] = 0
df.loc[df['z_score'] > 1, 'signals'] = -1
df.loc[df['z_score'] < -1, 'signals'] = 1
# Simulate trading
for i in range(1, len(df)):
# If the signal is 1, buy the stock
if df['signals'].iloc[i] == 1:
capital -= df['Close'].iloc[i]
# If the signal is -1, sell the stock
elif df['signals'].iloc[i] == -1:
capital += df['Close'].iloc[i]
# Append the current capital to the dataframe
capital_df = capital_df.append({'time': df.index[i], 'capital': capital}, ignore_index=True)
# Plot the capital over time
plt.figure(figsize=(10, 5))
plt.plot(capital_df['time'], capital_df['capital'])
plt.title('Capital Over Time')
plt.xlabel('Time')
plt.ylabel('Capital')
plt.show()
print('Current earning:', capital - initial_capital)
# Wait for 1 minute
time.sleep(60)
Sym Sym is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.