[Python] python adding new columns to dataframe

Discussão em 'Python' iniciado por Stack, Junho 1, 2025.

  1. Stack

    Stack Membro Participativo

    I am downloading some finance data and then adding new columns to a dataframe. But, when I saved the dataframe to an Excel file, the new columns I created are not getting saved in Excel.

    import yfinance as yf
    import pandas as pd
    import time


    stock_data = yf.download(tickers="AAPL", interval="1d", period="3y")

    stock_data['SMA50'] = stock_data['Close'].rolling(window=50).mean()
    stock_data['SMA200'] = stock_data['Close'].rolling(window=200).mean()
    stock_data['buy?'] = ""

    df = pd.DataFrame(stock_data)

    for row in df.itertuples():
    sma200 = row[7]
    close = row[1]
    if(sma200 > close):
    print("buy!")
    row[8] = "buy!"


    writer = pd.ExcelWriter('AAPL.xlsx', engine='xlsxwriter')
    df.to_excel(writer, sheet_name="datas", startrow=1, header=False, index=True)
    workbook = writer.book
    worksheet = writer.sheets["datas"]

    writer.close()

    Continue reading...

Compartilhe esta Página